【问题标题】:Querying an IndexedDB compound index with a shorter array使用较短的数组查询 IndexedDB 复合索引
【发布时间】:2014-11-29 22:28:10
【问题描述】:

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}

我哪里错了?

【问题讨论】:

    标签: javascript indexeddb


    【解决方案1】:

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

    【讨论】:

    • 干杯@Ivan!这正是我们想要的
    【解决方案2】:

    您应该使用键范围IDBKeyRange.bound([0], [0, '']),以便包含以[0] 开头的所有键。

    【讨论】:

    • 这确实有效,但我想我不明白为什么。 bound 不应该比较为 >= 和
    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多