What Is an Index?

Learn to understand indexes in IndexedDB.

We'll cover the following

An index in IndexedDB is a data structure that allows us to quickly search for specific data in a database based on a specific property. The purpose of an index is to organize data for efficient retrieval. We can think of it as a special object store for looking up records in another object store called the referenced object store.

Indexes are created for a specific property of the data that we want to be searchable. For example, in a database containing the Student records, creating an index on the class attribute would enable efficient searching and retrieval of all the students of a particular class.

Press + to interact
Illustration to explain indexes
Illustration to explain indexes

In the example above, we have a School database, and inside that, we have a Student object store (like a student database table). On the right side of the picture, we have another table storing the student data based on the class property of the Student. In that, the KeyPath denotes the property for which we’ve created the index. The “Primary key” denotes the unique id of each students data and the “Value” is the actual value.

Note: Each object store can have any number of indexes.

How do indexes work?

When we create an index, IndexedDB stores the value of the indexed property for each object in the database. This allows IndexedDB to quickly find all objects that have a specific value for the indexed property. For example, if we have an index on the product name property, IndexedDB can quickly find all the products that have the name “iPhone.”

Conclusion

Indexes can significantly improve the performance of database queries. Without indexes, IndexedDB would have to scan the entire database for each query. This would be very slow, especially for large databases. If we’re using IndexedDB for operations involving multiple queries, then we should consider creating indexes on the properties that we’ll be querying most often.