优化IndexedDB查询

时间:2017-09-26 16:15:16

标签: javascript nosql indexeddb dexie

我正在使用Dexie.JSIndexedDB合作。 目前,有一个愚蠢的查询写为:

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

它工作正常,但在大型数据库上作为糖蜜的速度很慢。我应该在应用了where的db.events集合中运行每个集合吗?这会改善表现吗?

谢谢

1 个答案:

答案 0 :(得分:1)

如果假设您的“key”变量属于可索引类型:是字符串,数字,日期,TypedArray或Array,则可以像这样优化查询:

首先,确保在db.events:

上添加索引“cause.data.abbreviation”
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();