我在 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'}
]
数据库 build 及要求:
// 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']));
查询找到我的任何记录。可以这样做吗?谢谢。
最佳答案
我怀疑是否可以使用 only()
数组,API 也没有这么说,请检查下面的 IDBKeyRange.only() .
可能这就是它不适合您的原因。
The only() method of the IDBKeyRange interface creates a new key range containing a single value.
因此,您可以做的是打开“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;
};
关于javascript - Indexeddb 在同一索引上搜索多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737219/