IndexedDB基于谓词获取下一个唯一索引

时间:2013-10-23 00:51:57

标签: javascript indexeddb

是否有办法根据记录中的谓词检索商店中的下一个唯一索引。例如,如果我有一个书店,里面装满了这样的物品:

{name: 'Hello Kitty', author: 'Me', pages: 5}

是否可以在作者上返回下一个唯一索引,但是将唯一性基于最大页数?

index.openKeyCursor('author', IDBCursor.nextunique).onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // How to filter the record by highest number of pages?
    cursor.continue();
  }
};

1 个答案:

答案 0 :(得分:0)

这有点棘手,但你可以做到。我将使用我的库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'

然后,我们open the iterator产生带有降序的光标。第一个光标就是我们想要的。在下一次迭代中,我们跳过重复的作者姓名。这是通过使用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);

请注意,我们只需要迭代唯一的作者而不需要缓冲区内存,因此可以扩展。