Indexeddb 简明教程

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 −

  1. Searching by a key value or a key range.

  2. Searching based on another object field.

Searching by Key

我们可以通过对一个可接受的键范围使用 IDBKeyRange 对象,来搜索精确的键值或键值范围。IDBKeyRange 对象具有以下调用:

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 −

  1. IDBKeyRange.lowerBound(lower, [open]) for >=lower

  2. IDBKeyRange.upperBound(upper, [open]) for >=upper

  3. IDBKeyRange.bound(lower, upper, [lowerOpen] , [upperOpen]) between lower and upper

  4. 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

  1. store.get(query) − Search for the first value in the store by a key or a range

  2. store.getAll([query],[count]) − Search for all values in the store till the limit of the count mentioned.

  3. store.getKey(query) − search for the first key for which the query is satisfied.

  4. store.getAllKeys([query],[count]) − search for all the keys for which the query is satisfied till the limit of the count is completed.

  5. store.count([query]) − get the total count of the keys for which the query is satisfied.

Example

在此示例中,我们使用 getAll() 方法检索所有对象,并按其键来搜索对象:

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 - 索引名称

name − Index Name

keyPath - 将在对象字段的路径上进行搜索

keyPath − Searching will be done on the path to the object field

options - 选项分为 2 类

options − options are of 2 types

  1. unique − Objects in the store with a unique value will be present at the key path and duplicates cannot be made of them.

  2. 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.

  1. the index will track the price field.

  2. If the price is not unique we can’t set the unique option.

  3. If the price is not an array then multiEntry is not applicable.

Example

在以下示例中,我们创建一个事务,并使用 getAll() 函数检索所有对象。检索这些对象后,我们搜索该事务中的对象值。如果找到,则返回该对象;如果没有,则返回 false。

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

搜索对象存储中值的 HTML 脚本实现如下:

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