使用较短的数组查询IndexedDB复合索引 [英] Querying an IndexedDB compound index with a shorter array

查看:254
本文介绍了使用较短的数组查询IndexedDB复合索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

IndexedDB allows you to make indexes on multiple properties. Like if you have objects like {a: 0, b: 0} you can make an index on a and b.

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

The behavior of compound indexes is pretty weird, but apparently it is supposed to be possible to query with an array that is shorter than the compound index. So in my example, I should be able to query on something like [0] and get results for a==0.

但是我似乎无法使它正常工作.这是一个示例,其中您可以在JS Bin上运行:

But I can't seem to get that to work. Here's an example which 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();
        }
      };
    }
  };
};

这又是JS Bin链接.

我看到的输出是:

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}

我要去哪里错了?

推荐答案

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

You should use key range IDBKeyRange.bound([0], [0, '']), so that all keys started with [0] included.

这篇关于使用较短的数组查询IndexedDB复合索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆