IndexedDB索引必须在onupgradeneeded中createObjectStore后立即用createIndex创建,不可动态添加;查询时需通过index.get()或index.openCursor()等API利用索引,避免全表扫描,并依据查询模式合理设计单列或复合索引。

创建索引:在 objectStore 创建时或升级时定义
IndexedDB 的索引必须在 objectStore 创建阶段 或数据库版本升级(onupgradeneeded)中声明,不能在已有 objectStore 上动态添加。关键是在调用 createObjectStore() 后,立即用 createIndex() 方法建立索引。
例如,存储用户数据,按邮箱和注册时间查询:
request.onupgradeneeded = (event) => {
const db = event.target.result;
const store = db.createObjectStore('users', { keyPath: 'id' });
// 创建唯一索引(邮箱不可重复)
store.createIndex('by-email', 'email', { unique: true });
// 创建非唯一、可空、支持范围查询的索引(如查某天之后注册的用户)
store.createIndex('by-createdAt', 'createdAt', {
unique: false,
multiEntry: false
});
};
高效查询:用 index + openCursor 或 get/getAll
查单条记录优先用 index.get(key),查多条用 index.openCursor(range) 或 index.getAll(range)。避免全表扫描(即不用 store.openCursor() 遍历整个 store)。
-
精确匹配查询:用
index.get('user@example.com')→ 返回匹配的第一条记录 -
范围查询(如时间区间):构造 KeyRange,再传给
openCursor -
排序查询:索引默认按键升序;加
direction: 'prev'可降序遍历
示例:查 2023 年后注册的所有用户(假设 createdAt 是毫秒时间戳):
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
const transaction = db.transaction('users');
const store = transaction.objectStore('users');
const index = store.index('by-createdAt');
const lowerBound = new Date('2023-01-01').getTime();
const range = IDBKeyRange.lowerBound(lowerBound);
const request = index.openCursor(range);
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
console.log(cursor.value); // { id: 1, email: 'a@b.c', createdAt: 1672531200000 }
cursor.continue(); // 继续下一条
}
};
索引设计要点:选对键、控制冗余、注意复合场景
不是越多索引越好——每个索引占用额外存储并拖慢写入速度。应围绕真实查询模式设计:
- 单字段高频查询(如 email、status)→ 建单列索引
-
多条件等值查询(如 status = 'active' AND role = 'admin')→ 考虑复合索引(IndexedDB 不原生支持多字段索引,需将字段拼成一个结构化键,如
{ status: 'active', role: 'admin' }存为新属性,再对此属性建索引) -
避免索引空值或 undefined 字段:设
multiEntry: false且确保字段存在,否则该记录不进入索引 -
区分大小写? IndexedDB 索引是严格字节比较,字符串比较区分大小写;如需忽略大小写,存数据时统一转小写(如
emailLower: user.email.toLowerCase()),再对此字段建索引
调试与验证:确认索引是否生效
开发中容易误以为索引已建但实际未触发。可通过以下方式验证:
- 打开 Chrome DevTools → Application → IndexedDB → 展开数据库 → 查看 objectStore 下是否有对应索引名
- 在查询前打印
store.indexNames,确认索引存在:console.log(store.indexNames); // DOMStringList ['by-email', 'by-createdAt'] - 用
index.count(range)快速检查命中数,比遍历更轻量 - 性能敏感场景可用
performance.now()对比索引查询 vs 全表遍历耗时(尤其数据量 > 1000 条时差异明显)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










