查询具有较短数组的 IndexedDB 复合索引

Querying an IndexedDB compound index with a shorter array

本文关键字:IndexedDB 复合 索引 数组 查询      更新时间:2023-09-26

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

复合索引

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

但我似乎无法做到这一点。下面是一个可以在 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();
        }
      };
    }
  };
};

这里又是JS垃圾桶链接。

我看到的输出是:

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, []])

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

只是为了解释为什么 Ivan(以及 Kyaw(的答案确实有效:可以比较不同类型的值

只有当你确定你正在比较数字时,你才能使用IDBKeyRange.bound([x], [x, MAX_NUMBER])(如果b(或IDBKeyRange.bound([x], [x, ''])但在一般情况下(假设没有数组子键(,你必须放置一个空数组([](作为b子项的上限。

来自 W3C 规范:

数字键小于日期键。日期键小于字符串钥匙。字符串键小于二进制键。二进制键小于数组键