IndexedDB是否有内置方法获取不等于特定值的所有记录?
IndexedDB 实现“不等于特定值”查询的方案
IndexedDB本身没有直接提供不等于特定值的内置键范围方法,你尝试的IDBKeyRange.bound(value, value, true, true)会报错,核心原因是这个方法要求起始值必须小于等于结束值,当两者相等且同时设置排除边界时,生成的键范围是无效的,自然触发错误。
要实现类似SQL中SELECT * FROM table WHERE field1 <> 'somedata'的效果,最高效的方式是拆分两个合法的键范围分别查询,再合并结果:
- 查询小于目标值的记录:使用
IDBKeyRange.upperBound(targetValue, true)(第二个参数true表示排除目标值本身) - 查询大于目标值的记录:使用
IDBKeyRange.lowerBound(targetValue, true)
如果你的查询字段是对象存储的主键,或者已经为该字段创建了索引,这种分范围查询的效率远高于全量遍历过滤。
代码示例
假设你要查询yourTableName中field1不等于'somedata'的记录,且已为field1创建索引:
// 打开只读事务 const transaction = db.transaction('yourTableName', 'readonly'); const store = transaction.objectStore('yourTableName'); const fieldIndex = store.index('field1'); const matchedRecords = []; // 第一步:查询所有小于'somedata'的记录 const lowerRange = IDBKeyRange.upperBound('somedata', true); fieldIndex.openCursor(lowerRange).onsuccess = (e) => { const cursor = e.target.result; if (cursor) { matchedRecords.push(cursor.value); cursor.continue(); } else { // 第二步:查询所有大于'somedata'的记录 const upperRange = IDBKeyRange.lowerBound('somedata', true); fieldIndex.openCursor(upperRange).onsuccess = (e) => { const cursor = e.target.result; if (cursor) { matchedRecords.push(cursor.value); cursor.continue(); } else { // 所有查询完成,处理结果 console.log('匹配的记录:', matchedRecords); } }; } };
如果没有为查询字段创建索引,那确实只能通过全量遍历对象存储并手动过滤不符合条件的记录,但这种方式性能会差很多,建议优先为查询字段创建索引。
内容的提问来源于stack exchange,提问作者Tony Tomov
相关产品推荐
相关产品推荐

