Using Indexes for Complex Queries
You'll learn how to query IndexedDB data using indexes instead of primary keys, enabling you to search by any indexed property.
Why Indexes Matter for Queries
So far, you've retrieved records using their primary key—but what if you want to find all users with a specific email address or all products under a certain price? This is where indexes shine. When you create an index on a property (like email or price), IndexedDB lets you query the database using that property directly, without needing to know the primary key.
Think of it like a library: the primary key is like the shelf number, but an index is like the card catalog that lets you search by author, title, or subject.
How to Query Using an Index
First, you access the index from your object store within a transaction. Then you use methods like get() or openCursor() on that index:
const transaction = db.transaction(['users'], 'readonly');
const store = transaction.objectStore('users');
// Access the index created earlier (e.g., on 'email')
const emailIndex = store.index('email');
// Query by indexed property
const request = emailIndex.get('alice@example.com');
request.onsuccess = function(event) {
const user = event.target.result;
console.log('Found user:', user);
};
You can also combine indexes with IDBKeyRange for range queries:
const priceIndex = store.index('price');
const range = IDBKeyRange.bound(10, 50); // Products between $10-$50
priceIndex.openCursor(range).onsuccess = function(event) {
const cursor = event.target.result;
if (cursor) {
console.log('Product:', cursor.value);
cursor.continue();
}
};
Key Takeaway: Indexes let you query IndexedDB by any indexed property, not just the primary key, enabling flexible searches like "find by email" or "find all items in price range."