2013-10-23 38 views
0

有沒有辦法根據記錄上的謂詞檢索商店中的下一個唯一索引。例如,如果我有充分的對象的書店,像這樣: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(); 
    } 
}; 

回答

0

這有點棘手,但你可以做。我將用我的庫https://bitbucket.org/ytkyaw/ydn-db進行說明,但您可以使用IndexedDB API。

首先,您必須使用array 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'); 

默認情況下,訂單以升序排列。這裏我們要降序以獲得最高頁面值。這無意中讓作者按降序排序,但無法避免它。

​​

然後,我們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); 

請注意,我們只需要迭代唯一的作者,並且不需要緩衝存儲器,因此可以擴展。