You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在IndexedDB中声明和使用复合索引?(含实体结构与存储示例)

如何在IndexedDB中声明和使用复合索引?(含实体结构与存储示例)

嘿,咱们一步步拆解IndexedDB里复合索引的玩法,先从要存储的数据结构说起:

首先用TypeScript接口定义好咱们的实体规范,确保数据结构统一:

interface Entity {
  id: number
  created_at: Date
  updated_at: Date
  title: string
}

接下来创建对象仓库和复合索引。这里咱们先建一个名为entities的对象仓库,把id设为主键且开启自增;然后创建一个复合索引index_by_creation_date,它基于created_at和id两个字段——这么做的好处是,既能按创建时间排序,又能靠唯一的id避免相同创建时间的记录出现排序冲突:

const store = database.createObjectStore("entities", {
  keyPath: "id",
  autoIncrement: true,
});

store.createIndex("index_by_creation_date", ["created_at", "id"], {
  unique: true, // 因为[created_at, id]的组合是唯一的,所以可以设为true
});

讲完声明,再说说怎么用这个复合索引,给你两个常用场景:

  • 按创建时间排序遍历所有实体:
    直接打开索引的游标,默认就会按复合索引的顺序(先created_at升序,再id升序)遍历数据:
    const transaction = database.transaction("entities", "readonly");
    const store = transaction.objectStore("entities");
    const index = store.index("index_by_creation_date");
    
    index.openCursor().onsuccess = (event) => {
      const cursor = event.target.result;
      if (cursor) {
        console.log("实体:", cursor.value);
        cursor.continue();
      }
    };
    
  • 查询指定时间之后创建的实体:
    利用索引的范围查询能力,快速定位符合时间条件的记录:
    const targetDate = new Date("2024-01-01");
    const transaction = database.transaction("entities", "readonly");
    const store = transaction.objectStore("entities");
    const index = store.index("index_by_creation_date");
    
    // 匹配created_at >= targetDate的所有记录
    const range = IDBKeyRange.lowerBound([targetDate, 0]);
    index.getAll(range).onsuccess = (event) => {
      console.log("2024年1月1日后创建的实体:", event.target.result);
    };
    

备注:内容来源于stack exchange,提问作者Biller Builder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 17:19:52