Indexeddb 简明教程

IndexedDB - Ranges

如果我们不想一次获得全部数据,则使用范围。如果我们只想获得特定范围内的的数据,则使用范围。我们使用 IDBKeyRange 对象来定义范围。此对象具有 4 个方法,分别是 −

  1. upperBound()

  2. lowerBound()

  3. bound()

  4. only()

Syntax

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

下表列出了各种范围代码 −

S.No.

Range Codes & Description

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)

我们通常使用索引来使用范围,并且在句法中,索引键表示索引键路径值。

Examples

使用 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 Example

考虑以下 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>

Output

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