javascript - 使用较短的数组查询 IndexedDB 复合索引

标签 javascript indexeddb

IndexedDB 允许您在多个属性上创建索引。就像如果你有像 {a: 0, b: 0} 这样的对象,你可以在 ab 上建立索引。

复合索引的行为是pretty weird ,但显然应该可以使用比复合索引短的数组进行查询。所以在我的示例中,我应该能够查询类似 [0] 的内容并获得 a==0 的结果。

但我似乎无法让它发挥作用。这是一个例子 you can run on JS Bin :

var db;

request = indexedDB.open("test", 1);
request.onerror = function (event) { console.log(event); };

request.onupgradeneeded = function (event) {
  var db = event.target.result;
  db.onerror = function (event) { console.log(event); };

  var store = db.createObjectStore("store", {keyPath: "id", autoIncrement: true});
  store.createIndex("a, b", ["a", "b"], {unique: true});

  store.add({a: 0, b: 0});
  store.add({a: 0, b: 1});
  store.add({a: 1, b: 0});
  store.add({a: 1, b: 1});
};

request.onsuccess = function (event) {
  db = request.result;
  db.onerror = function (event) { console.log(event); };

  console.log("Only [0, 0]");
  db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.only([0, 0])).onsuccess = function (event) {
    var cursor = event.target.result;
    if (cursor) {
      console.log(cursor.value);
      cursor.continue();
    } else {
      console.log("Any [0, x]");
      db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.only([0])).onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          console.log(cursor.value);
          cursor.continue();
        }
      };
    }
  };
};

Here is the JS Bin link again.

我看到的输出是:

Only [0, 0]
Object {a: 0, b: 0, id: 1}
Any [0, x]

但我希望看到:

Only [0, 0]
Object {a: 0, b: 0, id: 1}
Any [0, x]
Object {a: 0, b: 0, id: 1}
Object {a: 0, b: 1, id: 2}

我哪里错了?

最佳答案

Kyaw Tun 回答的一个稍微更一般的版本:如果已知所有键都是具有两个非数组元素的数组,并且您想要匹配 [x, <any>] 的键。 , 使用 IDBKeyRange.bound([x], [x, []]) .

关于javascript - 使用较短的数组查询 IndexedDB 复合索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203075/

相关文章:

javascript - 如何将backgrid与backbone布局管理器集成

javascript - 使用 JavaScript 从网站获取特定内容

c# - 使用正则表达式删除 JavaScript

indexeddb - IDBDatabase.transaction 中不推荐使用数字事务模式。使用 "readonly"或 "readwrite"

javascript - 如何禁用离线优先应用程序中的连接检查(Chrome - Android 和 Safari iOS)

javascript - 带有 xml 的两个按钮 javascript(需要一些帮助)

javascript - 在现有状态转换期间无法更新

javascript - 使用indexedb或ydn查询多个键(其中之一的范围)

google-chrome - 我或我的应用如何知道 Chrome 正在丢弃索引的数据库项目?

javascript - 如何从两个地方使用 IndexedDB