我想通过 indexeddb 获取列表数据,类似实现以下 SQL 的结果:
select * from table where user_id = 101 and order_id < 1000 order by order order_id desc limit 20
简述下:
1.获取某个用户(101)的所有记录
2.要求 order_id < 1000
3.按照倒序返回 20 条数据。
最终的结果应该是:
user_id = 101的,order_id 为 979 - 999 区间的数据。
以上需求,实现起来感觉好难。
let value = [user_id];
let objectStore = this.db.transaction([storeName]).objectStore(storeName)
let indexCondition = objectStore.index(index)
indexCondition.getAll(value)
这样虽然可以获取到这个用户的所有数据,但是不能排序,也不能limit。
let value = [user_id];
let objectStore = this.db.transaction([storeName]).objectStore(storeName)
let indexCondition = objectStore.index(index)
indexCondition.openCursor(IDBKeyRange.only(value), 'prev');
var res = [];
request.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
} else {
console.log('结束',res)
resolve(res
}
};
上面这个,虽然可以通过游标判断够条数,然后停止读取,实现 limit 。
但是不能满足 where order_id < 1000 的条件,这里返回的是整个用户所有的数据。
各位大佬,有没有好的解决方案呢?
最终解决方案:
按照查询需求创建索引,这样缺点是不能动态调整,如果查询字段可变,就不能很好满足。
比如,上文需要按照 user_id = 101 过滤,并按照 order_id 过滤取 < 1000 的几条数据。
创建索引
[user_id, order_id]
查询按照以下方式就可以取到数据。