IndexedDB - 范围


当我们不想一次获取所有数据时,我们可以使用范围。当我们想要获取特定范围内的数据时,我们只使用范围。我们使用IDBKeyRange对象定义范围。该对象有 4 个方法,分别是 -

  • 上界()
  • 下界()
  • 边界()
  • 仅有的()

句法

IDBKeyRange.lowerBound(indexKey);
IDBKeyRange.upperBound(indexKey);
IDBKeyRange.bound(lowerIndexKey, upperIndexKey);

以下是各种范围代码的列表 -

编号 范围代码和描述
1

所有键 ≥ a

DBKeyRange.lowerBound(a)

2

所有键 > a

IDBKeyRange.lowerBound(a, true)

3

所有键 ≤ b

IDBKeyRange.upperBound(b)

4

所有键 < b

IDBKeyRange.upperBound(b, true)

5

所有键 ≥ a && ≤ b

IDBKeyRange.bound(a, b)

6

所有键 > a &&< b

IDBKeyRange.bound(a, b, true, true)

7

所有键 > a && ≤ b

IDBKeyRange.bound(a, b, true, false)

8

所有键 ≥ a && < b

IDBKeyRange.bound(a, b, false, true)

9

关键=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