2017-09-26 33 views
0

我使用Dexie.JSIndexedDB一起使用。 目前,有一個愚蠢的查詢寫成:優化IndexedDB查詢

return db.events.each((element) => { 
    let d = element.cause.data; 
    if (d.hasOwnProperty('deleted') && (false == d.deleted) && 
     d.hasOwnProperty('abbreviation') && 
     d.hasOwnProperty('contents') && (d.abbreviation == key)) { 
    snippet = d.contents; 
    } 
}).then(() => { 
    return snippet; 
}); 

它工作正常,但慢如大型數據庫糖蜜。我是否應該在db.events中應用where的每個集合上運行?這會提高性能嗎?

謝謝

+0

在像'(cause.data)'這樣的各種子句中嘗試使用'keyPath'' - 得到了一個關於缺少索引的異常。 –

回答

1

是如果假設你的「鑰匙」變量是一個可索引類型:字符串,數字,日期,TypedArray或陣列,可以優化這樣的查詢:

首先,確保添加索引 「cause.data.abbreviation」 上db.events:

db.version(2).stores({ 
    events: 'yourPrimaryKey, cause.data.abbreviation' 
}); 

然後,改寫本查詢:

return db.events 
    // Let indexedDB sort out all items matching given key: 
    .where('cause.data.abbreviation').equals(key) 
    // Filter the rest manually using Collection.filter(): 
    .filter(element => { 
    let d = element.cause.data; 
    return (d.hasOwnProperty('deleted') && (false == d.deleted) && 
     d.hasOwnProperty('contents')); 
    }) 
    // Execute the query and only return the first match: 
    .first();