返回

用 IDBKeyRange 和 IDBObjectStore.count() 探究 IndexedDB 的范围查询和结果计数

前端

  1. 索引与范围查询

在 IndexedDB 中,索引是用于快速查找记录的一种数据结构。索引可以建立在任何属性之上,当对该属性进行查询时,IndexedDB 将使用索引来查找满足查询条件的记录,从而提高查询效率。

IDBKeyRange 接口表示一个键值范围,它可以用来定义查询的范围。IDBKeyRange 提供了多种方法来创建键值范围,包括:

  • IDBKeyRange.lowerBound():设置范围的下界。
  • IDBKeyRange.upperBound():设置范围的上界。
  • IDBKeyRange.bound():设置范围的上下界。
  • IDBKeyRange.only():仅匹配与给定键值相等的记录。

2. 使用 IDBKeyRange 进行范围查询

使用 IDBKeyRange 进行范围查询的基本步骤如下:

  1. 打开数据库并获取对象存储。
  2. 创建 IDBKeyRange 对象来定义查询范围。
  3. 将 IDBKeyRange 对象作为参数传递给 IDBObjectStore.openCursor() 或 IDBObjectStore.getAll() 方法。
  4. 在游标中迭代结果,并对每个匹配的记录进行处理。

以下代码展示了一个使用 IDBKeyRange 进行范围查询的示例:

const dbName = 'myDatabase';
const storeName = 'myStore';

const request = indexedDB.open(dbName, 1);

request.onsuccess = (event) => {
  const db = event.target.result;
  const transaction = db.transaction([storeName], 'readonly');
  const objectStore = transaction.objectStore(storeName);

  const keyRange = IDBKeyRange.bound('key1', 'key3');
  const cursorRequest = objectStore.openCursor(keyRange);

  cursorRequest.onsuccess = (event) => {
    const cursor = event.target.result;

    if (cursor) {
      // Process the record.
      console.log(cursor.value);

      cursor.continue();
    }
  };
};

3. 使用 IDBObjectStore.count() 统计结果

IDBObjectStore.count() 方法可以统计满足查询条件的记录数量。该方法接受一个 IDBKeyRange 对象作为参数,并返回一个 Promise 对象,该 Promise 对象在查询完成后解析为记录数量。

以下代码展示了一个使用 IDBObjectStore.count() 统计结果的示例:

const dbName = 'myDatabase';
const storeName = 'myStore';

const request = indexedDB.open(dbName, 1);

request.onsuccess = (event) => {
  const db = event.target.result;
  const transaction = db.transaction([storeName], 'readonly');
  const objectStore = transaction.objectStore(storeName);

  const keyRange = IDBKeyRange.bound('key1', 'key3');
  const countRequest = objectStore.count(keyRange);

  countRequest.onsuccess = (event) => {
    const count = event.target.result;

    console.log(`There are ${count} records in the range from 'key1' to 'key3'.`);
  };
};

4. 总结

IDBKeyRange 和 IDBObjectStore.count() 方法是 IndexedDB 中用于进行范围查询和结果计数的两个重要方法。这些方法可以帮助开发者快速高效地查找和处理满足特定查询条件的记录。通过熟练掌握这两个方法,开发者可以充分发挥 IndexedDB 的强大功能,构建出更加高效、灵活的前端存储解决方案。