![](/img/trans.png)
[英]Using IndexedDB Like SQL. Query with multiple index values that are not in a range
[英]Indexeddb search multi values on same index
我在IndexedDB數據庫中記錄了JSON流,但無法在同一索引上用多個值進行相等性搜索。
我的資料:
datas = [
{name : 'Test P1', location : 'P1'},
{name : 'Test P1', location : 'P1'},
{name : 'Test P2', location : 'P2'},
{name : 'Test P2', location : 'P2'},
{name : 'Test P3', location : 'P3'},
{name : 'Test P3', location : 'P3'},
{name : 'Test P3', location : 'P3'}
]
數據庫建設和要求:
// In onupgradeneeded
var objectStore = db.createObjectStore('entreprises', {keyPath: 'id_loc'});
objectStore.createIndex("name", "name");
objectStore.createIndex("location", "location");
//In query section
var transaction = db.transaction('entreprises','readonly');
var store = transaction.objectStore('entreprises');
var index = store.index('location');
// I want select only records where location = P1 and location = P2
var request = index.openCursor(IDBKeyRange.only(['P1', 'P2']));
// Select the first matching record
var request = index.get(IDBKeyRange.only(['P1', 'P2']));
查詢找到我任何記錄。 有可能這樣做嗎? 謝謝 。
通過為每個查詢創建游標來使用多查詢技術
index.get(IDBKeyRange.only('P1')).onsuccess = cursorHandler;
index.get(IDBKeyRange.only('P2')).onsuccess = cursorHandler;
cursorHandler
應將結果按主鍵存儲在排序的數組中。
我懷疑您是否可以將數組與only()
,API也沒有這樣說,請在下面檢查IDBKeyRange.only() 。
可能就是這對您不起作用的原因。
IDBKeyRange接口的only()方法創建一個包含單個值的新鍵范圍。
因此,您可以做的是打開“ P1”或“ P2”(行數較少的那個)的游標,然后遍歷游標以檢查它是否包含其他必需的值。 下面是我為方便參考而創建的示例,因此請對其進行調整,以進行更改,例如刪除“位置”,“ P1”,“ P2”等硬編碼值。
var resultArr = [];
var keyRange = IDBKeyRange.only("P1");
cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onerror = function(event) {
if (errorCallBack && typeof(errorCallBack) == 'function') {
errorCallBack(event);
}
};
cursorHandler.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
if(cursor.value != null && cursor.value != undefined){
if(cursor.value["location"] == "P2"){
resultArr.push(cursor.value);
}
}
cursor["continue"]();
} else{
var resultObj = {"rows" : resultArr};
if (successCallBack && typeof(successCallBack) == 'function') {
successCallBack(resultObj);
}
}
return;
};
也許嘗試這樣的事情:
// ...
objectStore.createIndex('locIndex',['loc1','loc2']);`
// ...
var index = store.index('locIndex');
var request = index.openCursor(IDBKeyRange.only(['P1', 'P2']));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.