Understanding Indexes
You'll learn how to create indexes on IndexedDB object stores so you can query data by properties other than the primary key.
What Are Indexes?
Think of an IndexedDB object store like a filing cabinet where each drawer is labeled with a unique ID (the primary key). By default, you can only find items by opening the drawer with the matching ID number. But what if you want to find all files by author name or date? That's where indexes come in.
An index creates an additional way to look up data—like adding colored tabs to your filing cabinet that let you quickly jump to items based on different properties. Instead of searching through every record, you can efficiently query by any indexed property.
Creating an Index
Indexes are created during the onupgradeneeded event when you set up or modify your database structure. You call createIndex() on an object store:
request.onupgradeneeded = function(event) {
const db = event.target.result;
// Create an object store
const store = db.createObjectStore('users', { keyPath: 'id' });
// Create an index on the 'email' property
store.createIndex('emailIndex', 'email', { unique: true });
// Create an index on 'lastName' (non-unique)
store.createIndex('lastNameIndex', 'lastName', { unique: false });
};
The first argument is the index name, the second is the property to index, and the third specifies options like whether values must be unique.
Now you can efficiently find users by email or last name, not just by their ID!
Key Takeaway: Indexes let you query IndexedDB object stores by any property, not just the primary key, making data retrieval fast and flexible.