如何在IndexedDB中结合id与多键实现多条件数据查询
如何用IndexedDB实现多条件(含主键)查询?
你已经创建了components对象仓库,并建立了componentFloorId, componentRoomId复合索引,现在要实现类似SQL SELECT * FROM components WHERE componentFloorId="1" AND componentRoomId="1" AND id=2的多条件查询,有两种可行方案:
方案1:先通过复合索引筛选,再过滤主键
利用已有的复合索引先查询出符合componentFloorId和componentRoomId的所有数据,再在结果中筛选出id匹配的项。因为id是主键唯一,最终只会得到一条匹配结果。
代码示例:
const txn = db.transaction('components', 'readonly'); const store = txn.objectStore('components'); const index = store.index('componentFloorId, componentRoomId'); // 先获取符合floor和room条件的所有数据 index.getAll([floorIdFromCard, roomIdFromCard]).then(results => { // 筛选出id匹配的项 const targetItem = results.find(item => item.id === targetId); console.log(targetItem); });
方案2:创建包含三个字段的复合索引(更高效)
如果允许修改仓库结构,直接创建一个包含componentFloorId、componentRoomId、id的复合索引,这样可以直接通过索引精准定位目标数据,避免后续筛选,性能更优。
第一步:修改仓库创建代码(如果是新初始化)
var objectStore = db.createObjectStore("components", { keyPath: "id", autoIncrement: true }); // 创建原有的复合索引 objectStore.createIndex('componentFloorId, componentRoomId', ['componentFloorId', 'componentRoomId']); // 创建包含三个字段的复合索引 objectStore.createIndex('componentFloorId, componentRoomId, id', ['componentFloorId', 'componentRoomId', 'id']);
第二步:使用新索引查询
const txn = db.transaction('components', 'readonly'); const store = txn.objectStore('components'); const index = store.index('componentFloorId, componentRoomId, id'); // 直接传入三个条件的值查询 index.get([floorIdFromCard, roomIdFromCard, targetId]).then(targetItem => { console.log(targetItem); });
方案对比
- 方案1:无需修改现有索引结构,适合已上线项目快速适配,但如果符合floor和room条件的数据量较大,后续筛选会有轻微性能损耗。
- 方案2:通过索引直接定位数据,性能最优,但需要额外创建索引,若仓库已有大量数据,需要考虑索引创建的耗时。
内容的提问来源于stack exchange,提问作者Ozgur Baykal
相关产品推荐
相关产品推荐

