0

我正在Dexie.JS使用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 和 applied 组成的集合上运行每个where吗?那会提高性能吗?

谢谢

4

1 回答 1

1

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

首先,确保在 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();
于 2017-09-27T08:18:47.727 回答