1

如何将 IndexedDB 计数方法与复合键一起使用?我学习了如何过滤单个属性。到目前为止,一切都很好,但现在我需要同时进行排序和过滤。

我的对象存储充满了这些对象:

os.put({feed_id:1,id:1,title:"foofoo",time:111});
os.put({feed_id:1,id:2,title:"foobar",time:112});
os.put({feed_id:1,id:3,title:"foobaz",time:113});
os.put({feed_id:3,id:1,title:"bazfoo",time:114});
os.put({feed_id:3,id:2,title:"bazbar",time:115});
os.put({feed_id:3,id:3,title:"bazbaz",time:116});
os.put({feed_id:1,id:4,title:"foofoo",time:122});
os.put({feed_id:1,id:5,title:"foobar",time:121});
os.put({feed_id:1,id:6,title:"foobaz",time:120});
os.put({feed_id:3,id:4,title:"bazfoo",time:119});
os.put({feed_id:3,id:5,title:"bazbar",time:118});
os.put({feed_id:3,id:6,title:"bazbaz",time:117});

我在对象存储上设置了两个索引,一个 (idx_feedid) 具有 keyPath feed_id,它允许我使用 openCursor 获取具有特定提要 id 的所有对象,一个 (idx_ts) 具有 keyPath ["id","feed_id","time"]

问题是迭代 idx_feedid 的结果会给我结果,而不需要对时间戳进行排序。在 SQL 中我很容易做一个SELECT * FROM feeditems WHERE feed_id=3 ORDER BY time DESC,但是如何在 IndexedDB 中做到这一点?

以及如何限制返回的结果以实现分页?从本质上讲,我需要类似 MySQLs LIMIT 0,10/ LIMIT 10,10/ ...

4

2 回答 2

0
于 2013-10-31T21:41:06.503 回答
-1

Use compound index, ['feed_id', 'time'] and query over IDBKeyRange.only([3]) on reverse direction.

Using my open source library, it is dowe as follow:

var schema = {
  stores: [{
    name: 'os',
    indexes: [{
      name: 'feed_id, time',
      keyPath: ['feed_id', 'time']
    }]
  }]
}

var db = new ydn.db.Storage('db name', schema);
var kr = ydn.db.KeyRange.starts([3]);
db.values('os', 'feed_id, time', kr, 10, 0, true).done(function(values) {
  console.log(values); // sorted by descending of time
});

The library support both indexeddb and websql without any dependency. You will also see very fast performance on websql.

If you use shim, compound index may not work properly.

于 2013-11-01T03:19:48.400 回答