- IndexedDB 教程
- IndexedDB - 首页
- IndexedDB - 简介
- IndexedDB - 安装
- IndexedDB - 连接
- IndexedDB - 对象存储
- IndexedDB - 创建数据
- IndexedDB - 读取数据
- IndexedDB - 更新数据
- IndexedDB - 删除数据
- 使用 getAll() 函数
- IndexedDB - 索引
- IndexedDB - 范围
- IndexedDB - 事务
- IndexedDB - 错误处理
- IndexedDB - 搜索
- IndexedDB - 游标
- IndexedDB - Promise 包装器
- IndexedDB - Ecmascript 绑定
- IndexedDB 有用资源
- IndexedDB - 快速指南
- IndexedDB - 有用资源
- IndexedDB - 讨论
IndexedDB - 索引
索引是一种对象存储,用于通过指定的属性存储的参考对象中提取数据。即使索引位于参考对象存储中并包含相同的数据,但它使用指定属性作为其关键路径,而不是参考存储的主键。
索引用于定义数据上的唯一约束,并且在创建对象存储时进行创建。要创建索引,请在对象存储实例上调用 createIndex 方法 -
语法
var myIDBIndex = objectStore.createIndex(indexName, keyPath); var myIDBIndex = objectStore.createIndex(indexName, keyPath, objectParameters);
此方法创建一个并返回一个索引对象。该方法创建了一个采用以下参数的索引 -
索引名称 - 索引的名称。
键路径 - 我们在此处提到主键。
对象参数 - 有两个对象参数。
唯一 - 无法添加重复值。
多条目 - 如果 true,则当 keyPath 解析为数组时,该索引将在索引中添加每个数组元素的条目。如果 false,它将添加一个包含该数组的单个条目。
示例
以下示例显示了对象存储中索引的实现 -
<!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>
输出
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"
广告