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@[email protected]' SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@[email protected]' and age = 30 SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@[email protected]' 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.
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@[email protected]'], ['444-44-4444', 'bill@[email protected]', '']) objectStore.index('ssn, email, age').get(keyRange) objectStore.index('ssn, email, age').get(['444-44-4444', 'bill@[email protected]', 30]) objectStore.index('ssn, email, name').get(['444-44-4444', 'bill@[email protected]', '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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With