Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all IDBIndex key values (instead of object store primary keys)?

Tags:

indexeddb

I have an IndexedDB object store with a primary key and an additional index (with a unique key constraint).

Now I want to retrieve all key values of this index.

Previously, I used IDBIndex.getAllKeys(), but appearently the behaviour of this method has changed to return the object store primary keys instead of the index keys. (I cannot, however, find any documentation, or reference in browser release notes to that effect...)

So my question is: What is the recommended, most performant way to retrieve all index key values?

like image 253
Daniel Avatar asked Dec 08 '25 11:12

Daniel


1 Answers

Do you know why there is an IDBIndex.getAllKeys() method if it returns the same thing as IDBObjectStore.getAllKeys()

One reason for having these two separate methods is that they both accept an optional query argument, which is a key range.

In the case of IDBObjectStore.getAllKeys(query), the key range is a range of primary keys, and result is an array of primary keys

In the case of IDBIndex.getAllKeys(query), the key range is a range of index keys, and result is an array of primary keys

Example:

/* store (key = SSN) */
const users = await db.createObjectStore("users", { keyPath: "SSN" });

/* index (key = surname) */
users.createIndex("surname", "surname");

/* 1. get all SSNs from store */
const keys = await users.getAllKeys();

/* 2. get all SSNs starting between 'a' and 'f' */
const keys = await users.getAllKeys(IDBKeyRange.bound('a', 'f'));

/* 3. get all SSNs from index (same as #1) */
const keys = await users.index("surname").getAllKeys();

/* 4. get all SSNs where surname is between 'a' and 'f' (different to #2) */
const keys = await users.index("surname").getAllKeys(IDBKeyRange.bound('a', 'f'));
like image 80
Scott Avatar answered Dec 10 '25 02:12

Scott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!