IndexedDB允许您在多个属性上创建索引。就像您拥有{a: 0, b: 0}
之类的对象一样,您可以在a
和b
上建立索引。
复合索引的行为是pretty weird,但显然可以使用比复合索引短的数组进行查询。所以在我的例子中,我应该可以查询类似[0]
的内容并获得== 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}
我哪里错了?
答案 0 :(得分:1)
您应该使用键范围IDBKeyRange.bound([0], [0, ''])
,以便包含[0]
开头的所有键。
答案 1 :(得分:0)
Kyaw Tun回答的稍微更通用的版本:如果已知所有键都是包含两个非数组元素的数组,并且您想要匹配[x, <any>]
的数组,请使用IDBKeyRange.bound([x], [x, []])