Skip to content

Bulk iteration over a store or an index #344

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
darrachequesne opened this issue Apr 2, 2025 · 0 comments
Open

Bulk iteration over a store or an index #344

darrachequesne opened this issue Apr 2, 2025 · 0 comments

Comments

@darrachequesne
Copy link

darrachequesne commented Apr 2, 2025

Is your feature request related to a problem? Please describe.

Iterating with a cursor over a lot of documents is quite slow and can be made faster with store.getAll(query, count) (but only in ascending order):

function bulkIterate (storeOrIndex, query, direction, bulkSize) {
  if (direction === "next") {
    let offset = query;

    return (async function*() {
      while (true) {
        const items = await storeOrIndex.getAll(offset, bulkSize);

        if (items.length === 0) {
          break;
        }

        for (const item of items) {
          yield { value: item };
        }

        const lastItem = items[items.length - 1];
        const lastItemId = Array.isArray(storeOrIndex.keyPath) ?
          storeOrIndex.keyPath.map((k) => lastItem[k]) : lastItem[storeOrIndex.keyPath];
        if (query instanceof IDBKeyRange && query.upper !== undefined) {
          offset = IDBKeyRange.bound(lastItemId, query.upper, true, query.upperOpen);
        } else {
          offset = IDBKeyRange.lowerBound(lastItemId, true);
        }
      }
    })();
  }

  return storeOrIndex.iterate(query, direction);
}

// usage
for await (const cursor of bulkIterate(store, null, "next", 101)) {
  console.log(cursor.value);
}

Do you see anything wrong with this approach? Else, do you think this could/should be added in the iterate() method here? Or simply mentioned in the README?

Thanks in advance!

Related: w3c/IndexedDB#130

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant