这有点棘手,但你可以做到。我将使用我的库https://bitbucket.org/ytkyaw/ydn-db进行说明,但您可以使用 IndexedDB API。
首先,您必须使用数组 keyPath 使用复合索引(仅支持 Firefox 和 Chrome)。ydn-db 的数据库架构是
var schema = {
stores: [{
name: 'book',
indexes: [{
name: 'author, pages',
keyPath: ['author', 'pages']
}]
}
};
var db = new ydn.db.Storage('db name', schema);
索引'author, pages'
按 排序author
,然后按 排序pages
。然后我们在 ydn-db 中准备游标或创建迭代器。
var iter = new ydn.db.IndexValueIterator('book', 'author, pages');
默认情况下,顺序是升序。在这里,我们希望降序获得最高的页面价值。这在不经意间使作者按降序排序,但没有办法避免。
iter = iter.reverse().unique(); // essentially 'PREV_UNIQUE'
然后,我们以降序打开产生光标的迭代器。第一个光标是我们想要的。在下一次迭代中,我们跳过重复的作者姓名。这是通过使用cursor.continue(next_key)
方法完成的。next_key
已给出,这样它就不会通过使用已知的作者密钥给出尽可能低的值来重复已经获得的内容。
db.open(function(cursor) {
var book = cursor.getValue();
console.log(book);
var effective_key = cursor.getKey();
var author_key = effective_key[0];
var next_key = [author_key];
return next_key; // continue to this or lower than this key.
}, iter);
请注意,我们只需要迭代唯一的作者,不需要缓冲内存,因此是可扩展的。