IndexedDB - 范围
当我们不想一次获取所有数据时,我们可以使用范围。 当我们想要获取特定范围内的数据时,我们只使用范围。 我们使用 IDBKeyRange 对象定义范围。 该对象有 4 个方法,分别是 −
- upperBound()
- lowerBound()
- bound()
- only()
语法
IDBKeyRange.lowerBound(indexKey); IDBKeyRange.upperBound(indexKey); IDBKeyRange.bound(lowerIndexKey, upperIndexKey);
以下是各种范围代码的列表 −
S.No. | 范围代码和描述 |
---|---|
1 | All keys ≥ a DBKeyRange.lowerBound(a) |
2 | All keys > a IDBKeyRange.lowerBound(a, true) |
3 | All keys ≤ b IDBKeyRange.upperBound(b) |
4 | All keys < b IDBKeyRange.upperBound(b, true) |
5 | All keys ≥ a && ≤ b IDBKeyRange.bound(a, b) |
6 | All keys > a &&< b IDBKeyRange.bound(a, b, true, true) |
7 | All keys > a && ≤ b IDBKeyRange.bound(a, b, true, false) |
8 | All keys ≥ a && < b IDBKeyRange.bound(a, b, false, true) |
9 | The key = c IDBKeyRange.only(c) |
我们通常使用索引来使用范围,在语法中,索引键代表索引键路径值。
示例
使用 get() 和 getAll() 方法检索范围代码的各种示例如下 −
class.get(‘student’) class.getAll(IDBKeyRange.bound(‘science’,’math’) class.getAll(IDBKeyRange.upperbound(‘science’,true) class.getAll() class.getAllKeys(IDBKeyRange.lowerbound(‘student’,true))
HTML 示例
考虑下面的 HTML 示例来获取范围代码 −
<!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 upperquery =store.getAll(IDBKeyRange.upperBound('2', true)); upperquery.onsuccess = function(){ document.write("upperquery",upperquery.result); } transaction.oncomplete = function(){ db.close; } } </script> </body> </html>
输出
database opened successfully upperquery (4) [{...}, {...}, {...}, {...}] arg1: (4) [{...}, {...}, {...}, {...}] 0: {id: 1, name: 'jason', branch: 'IT'} 1: {id: 2, name: 'praneeth', branch: 'CSE'} 2: {id: 3, name: 'palli', branch: 'EEE'} 3: {id: 4, name: 'deevana', branch: 'CSE'} length: 4 [[Prototype]]: Array(0) [[Prototype]]: Object