Indexeddb 简明教程

IndexedDB - Indexes

索引是一种用于从由指定属性存储的参考对象检索数据的对象存储。即使索引在参考对象存储中并且包含相同数据,但它不使用参考存储的主键,而是使用指定的属性作为其关键路径。

索引用于定义针对数据唯一约束,它们在创建对象存储时创建。要创建索引,请在对象存储实例上调用 createIndex 方法 -

Syntax

var myIDBIndex = objectStore.createIndex(indexName, keyPath);
var myIDBIndex = objectStore.createIndex(indexName, keyPath, objectParameters);

此方法创建一个索引对象并返回它。该方法创建包含以下参数的索引 -

  1. Index name - 索引的名称。

  2. Keypath - 我们在此处注明主键。

  3. Object Parameters - 有两个对象参数。

  4. Unique - 无法添加重复值。

  5. Multi entry - 如果为 true,则当 keyPath 解析为 Array 时,索引会为每个数组元素在索引中添加一个条目。如果为 false,它将添加包含 Array 的单个条目。

Example

以下示例显示了在对象存储中实现索引 -

<!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"});
         transaction.oncomplete = function(){
            db.close;
         }
      }
   </script>
</body>
</html>

Output

branchIndex:
1
['CSE']
0: "CSE"
length: 1
4
{id: 4, name: 'deevana', branch: 'CSE'}
branch: "CSE"
id: 4
name: "deevana"
2
['EEE']
0: "EEE"
length: 1
3
{id: 3, name: 'palli', branch: 'EEE'}
branch: "EEE"
id: 3
name: "palli"
3
['IT']
0: "IT"
length: 1
1
{id: 1, name: 'jason', branch: 'IT'}
branch: "IT"
id: 1
name: "jason"