Javascript: Searching indexeddb using multiple indexes

流过昼夜 提交于 2019-12-17 18:29:08

问题


I want to change from WebSql to Indexeddb. However, how would one do SQL queries like

SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com'
SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com' and age = 30
SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com' and name = 'Bill'
etc

with IndexedDB ? For example, I noticed while reading the documentation of indexedDb, that all the examples only query one index at the time. So you can do

var index = objectStore.index("ssn");
index.get("444-44-4444").onsuccess = function(event) {
     alert("Name is " + event.target.result.name);
};

But I need to query multiple indexes at the same time!

I also found some interesting posts about compound indexes, but they only work if you query for all the fields in the compound index.


回答1:


For your example, compound index still work, but requires two compound indexes

 objectStore.createIndex('ssn, email, age', ['ssn', 'email', 'age']); // corrected
 objectStore.createIndex('ssn, email, name', ['ssn', 'email', 'name'])

And query like this

 keyRange = IDBKeyRange.bound(
     ['444-44-4444', 'bill@bill@company.com'],
     ['444-44-4444', 'bill@bill@company.com', '']) 
 objectStore.index('ssn, email, age').get(keyRange)
 objectStore.index('ssn, email, age').get(['444-44-4444', 'bill@bill@company.com', 30])
 objectStore.index('ssn, email, name').get(['444-44-4444', 'bill@bill@company.com', 'Bill'])

Indexes can be arranged in any order, but it is most efficient if most specific come first.

Alternatively, you can also use key joining. Key joining requires four (single) indexes. Four indexes take less storage space and more general. For example, the following query require another compound index

SELECT * FROM customers WHERE ssn = '444-44-4444' and name = 'Bill' and age = 30

Key joining still work for that query.



来源:https://stackoverflow.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!