Search code examples
javascriptnosqlindexeddbdexie

Optimizing IndexedDB query


I am using Dexie.JS to work with IndexedDB. Currently, have a stupid query written as:

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

It is working correctly, but slow as molasses on a large database. Should I run each on a collection made from db.events with applied where? Would that improve performance?

Thank you


Solution

  • Yes if assuming your "key" variable is of an indexable type: string, number, Date, TypedArray or Array, you can optimize the query like this:

    First, make sure to add the index "cause.data.abbreviation" on db.events:

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

    Then, rewrite the query like this:

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