2013-10-31 9 views
0

How to use IndexedDB count method with composite keys?我學會了如何過濾單個屬性。到目前爲止,這麼好,但現在我需要同時進行排序和篩選。有沒有一種方法在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,使用keyPath ["id","feed_id","time"]提供一個(idx_ts)。

問題是迭代idx_feedid的結果給我的結果沒有在時間戳上排序。在SQL中,我很容易做到SELECT * FROM feeditems WHERE feed_id=3 ORDER BY time DESC,但在IndexedDB中如何做到這一點?

我該如何限制返回的結果以實現分頁?實質上,我需要類似MySQLs LIMIT 0,10/LIMIT 10,10/...

+0

[在IndexedDB中,是否有一種方法可以進行排序的複合查詢?](http://stackoverflow.com/questions/12084177/in-indexeddb-is-there-a-way-to-make -a-sorted-compound-query) – Josh

回答

0

不能做限制。即使你嘗試,內部實現也會使用你無法控制的優化,比如總是把前100行加載到RAM中,即使你只想要1也是如此。幸運的是,小規模的應用程序不會受到太大的影響,因爲它仍然非常快。

關於你的問題,看看https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore?redirectlocale=en-US&redirectslug=IndexedDB%2FIDBObjectStore#openCursor()。在飼料ID 3上設置一個IDBKeyRange,並按照'prev'的方向傳遞以降序進行迭代。

編輯:做分頁您可以使用cursor.advance(+或 - n行)

+0

也許你也可以幫我解決這個問題:http://stackoverflow.com/questions/26546716/sort-by-number-date –

-1

使用複合指數,[ 'FEED_ID', '時間']和查詢過IDBKeyRange.only([3])在相反的方向。

用我open source library,這是有人仍然如下:

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 
}); 

庫同時支持IndexedDB的和的WebSQL沒有任何依賴性。您還將在websql上看到非常快的性能。

如果使用墊片,複合索引可能無法正常工作。