IDBKeyRange.only和IDBKeyRange.lowerBound在一个查询中

时间:2015-04-06 10:33:59

标签: javascript indexeddb

我需要将此sql查询转换为IndexedDB语法。

"SELECT * FROM article WHERE userid=100 AND date_created > '2015-1-15 18:00:00'"

我正在考虑这两种解决方案。

userid索引

var articles = [];
objectStore.index('userid').openCursor(100).onsuccess = function(e){
    var cursor = e.target.result;
    if(cursor){
        var article = cursor.value;
        if(new Date(article.date_created) > new Date('2015-1-15 18:00:00')){
            articles.push(article);
        }
        cursor.continue();
    }esle{
        console.log('done');
    }
};

date_created索引

var articles = [];
objectStore.index('date_created').openCursor(IDBKeyRange.lowerBound('2015-1-15 18:00:00')).onsuccess = function(e){
    var cursor = e.target.result;
    if(cursor){
        var article = cursor.value;
        if(article.userid === 100){
            articles.push(article);
        }
        cursor.continue();
    }esle{
        console.log('done');
    }
};

如何在useriddate_created上使用复合索引编写类似的查询?

1 个答案:

答案 0 :(得分:3)

嗯。尝试使用IDKeyRange.bound

function queryArticlesByIdDate(id, date, handleArticle) {
  var openRequest = indexedDB.open(...);
  openRequest.onupgradeneeded = function(event) {
    var db = this.result;
    var articleStore = db.createObjectStore('articles');
    articleStore.createIndex('date-id',['date_created','userid']);
  };
  openRequest.onsuccess = function(event) {
    var db = this.result;
    var articleStore = db.objectStore('articles');
    var dateIdIndex = articleStore.index('date-id');
    var lowerDate = date;
    var upperDate = new Date(date + 1); // or whatever
    var bounds = IDBKeyRange.bound([lowerDate, id], [upperDate, id]);
    var cursorRequest = dateIdIndex.openCursor(bounds);
    cursorRequest.onsuccess = function(event) {
      var cursor = this.result;
      if(!cursor) return;
      handleArticle(cursor.value);
      cursor.continue();
    };
  };
}

queryArticlesByIdDate(5, new Date(...), function handler(article) {
  console.dir(article);
});