IndexedDB – Searching
We encounter many situations where we need to search for values in an object store. Object stores are sorted internally. It can be done by −
- Searching by a key value or a key range.
- Searching based on another object field.
Searching by Key
We can search for exact key values or a range of key values by using IDBKeyRange objects with an acceptable key Range. IDBKeyRange object has the following calls −
-
IDBKeyRange.lowerBound(lower, [open]) for >=lower
-
IDBKeyRange.upperBound(upper, [open]) for >=upper
-
IDBKeyRange.bound(lower, upper, [lowerOpen] , [upperOpen]) between lower and upper
-
IDBKeyRange.only(key) if the range contains only one key.
To perform the actual search we use the query argument on the object store. The different types of methods to perform these operations are
-
store.get(query) − Search for the first value in the store by a key or a range
-
store.getAll([query],[count]) − Search for all values in the store till the limit of the count mentioned.
-
store.getKey(query) − search for the first key for which the query is satisfied.
-
store.getAllKeys([query],[count]) − search for all the keys for which the query is satisfied till the limit of the count is completed.
-
store.count([query]) − get the total count of the keys for which the query is satisfied.
Example
In this example, we are retrieving all the objects using the getAll() method and searching for objects by their key −
class.get(‘student’) class.getAll(IDBKeyRange.bound(‘science’,’math’) class.getAll(IDBKeyRange.upperbound(‘science’,true) class.getAll() class.getAllKeys(IDBKeyRange.lowerbound(‘student’,true))
Searching by a field or index
To search based on other object fields we need to use indexes. An index stores a list of keys for objects that have the value required. Indexes are also internally sorted like object stores.
Syntax
objectStore.createIndex(name, keyPath, [options]);
name − Index Name
keyPath − Searching will be done on the path to the object field
options − options are of 2 types
-
unique − Objects in the store with a unique value will be present at the key path and duplicates cannot be made of them.
-
multi−entry − if the value on the keypath is an array then by default the index will treat the whole array as a key but if we use multi-entry the array members will become index keys.
Example
If we want to search for phones based on price, the example program is as follows −
openRequest.onupgradeneeded = function() { let books = db.createObjectStore(''phone'', {keyPath: ''id''}); let index = books.createIndex(''pricephone'', ''price''); };
To create an index we need to use the upgrade needed.
- the index will track the price field.
- If the price is not unique we can”t set the unique option.
- If the price is not an array then multiEntry is not applicable.
Example
In the following example, we create a transaction and retrieve all the objects using the getAll() function. Once they are retrieved, we search for object values in that transaction. If found, return the object; if not, return false.
let transaction = db.transaction("phones"); let books = transaction.objectStore("phones"); let priceIndex = books.index("price_index"); let request = priceIndex.getAll(7); request.onsuccess = function() { if (request.result !== undefined) { document.write("Phones", request.result); } else { document.write("There are no such phones"); } };
HTML Example
The HTML script implementation to search for values in object store is given below −
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> const request = indexedDB.open("botdatabase",1); request.onupgradeneeded = function(){ const db = request.result; const store = db.createObjectStore("bots",{ keyPath: "id"}); store.createIndex("branch_db",["branch"],{unique: false}); } request.onsuccess = function(){ document.write("database opened successfully"); const db = request.result; const transaction=db.transaction("bots","readwrite"); const store = transaction.objectStore("bots"); const branchIndex = store.index("branch_db"); store.add({id: 1, name: "jason",branch: "IT"}); store.add({id: 2, name: "praneeth",branch: "CSE"}); store.add({id: 3, name: "palli",branch: "EEE"}); store.add({id: 4, name: "abdul",branch: "IT"}); store.put({id: 4, name: "deevana",branch: "CSE"}); const req = branchIndex.getAll(["CSE"]); req.onsuccess = function(){ if(req.result!==undefined){ document.write("bots",req.result); } else{ document.write("There are no such bots"); } }; transaction.oncomplete = function(){ db.close; } } </script> </body> </html>
Output
database opened successfully bots (2) [{...}, {...}] arg1:(2) [{...}, {...}] 0:{id: 2, name: ''praneeth'', branch: ''CSE''} 1:{id: 4, name: ''deevana'', branch: ''CSE''} length:2 [[Prototype]]:Array(0) [[Prototype]]:Object