Getting specific identifiers from Indexeddb

In my project, I use the index-DB browser, and I would like to get some objects from db with specific identifiers. According to MDN , you can use ranges to get the desired results:

According to MDN:

// Only match "Donna" var singleKeyRange = IDBKeyRange.only("Donna"); // Match anything past "Bill", including "Bill" var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill"); // Match anything past "Bill", but don't include "Bill" var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true); // Match anything up to, but not including, "Donna" var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true); // Match anything between "Bill" and "Donna", but not including "Donna" var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true); // To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor() index.openCursor(boundKeyRange).onsuccess = function(event) { var cursor = event.target.result; if (cursor) { // Do something with the matches. cursor.continue(); } }; 

However, what do you do if you want to get an array of specific identifiers that are out of order and not sequential (for example: [91,819,34,24,501]) with a single request?

+6
source share
2 answers

Based on your comment, it seems that you want to do something like SELECT objects FROM objects WHERE object.id = 1 OR object.id = 2 OR object.id = 5 , as one request (request). Unfortunately, indexedDB cannot execute OR style queries (unions). It can only execute AND style requests (intersections).

There is a possible solution if the various identifiers you want to get are known a priori. You can simply save the additional group-id property, put the associated identifiers in separate groups, and then request the group identifier. This, obviously, does not work if the identifiers you want to receive overlap (appear in several groups) or are variables (change of group membership from request to request).

+3
source

You cannot do this with a single query, but you can run multiple queries in parallel:

 var keys = [91,819,34,24,501]; var results = []; keys.forEach(function(key) { store.get(key).onsuccess = function(e) { results.push(e.target.result); if (results.length === keys.length) { // you're done! } }; }); 

Note that the queries must be executed in order, so the order of the results array will correspond to the order of the keys array. If the key is not found, the corresponding result index will contain undefined .

(There is a function request for an indexed DB that supports this directly: https://github.com/w3c/IndexedDB/issues/19 , but there is no final API design yet.)

+2
source

Source: https://habr.com/ru/post/982610/


All Articles