Indexes and queries
Learn to add an index to an object store and run range queries.
Creating an index
An index lets you search quickly by a field inside an object store. It is created with store.createIndex(name, keyPath); you can then run get, getAll or cursor queries against it.
const index = store.createIndex('by_date', 'date');Here 'by_date' is the index name and 'date' is the indexed field. You can now look up records by their date field.
Range queries with IDBKeyRange
IDBKeyRange defines a range of keys and is used in index queries. For example IDBKeyRange.only(x) matches only x, while IDBKeyRange.lowerBound(y) covers y and above.
const range = IDBKeyRange.only('2024-01-01');
index.getAll(range);This way you can fetch all records matching a specific date or a numeric range in one call.
Exercise Create store and index
Assign a function to request.onupgradeneeded. Inside, read event.target.result into a db variable. Create the 'notes' store with db.createObjectStore and { keyPath: 'id' }, assign it to store. Then call store.createIndex to create the 'by_date' index on the 'date' keyPath.
Show example solution
request.onupgradeneeded = function(event) {
const db = event.target.result;
const store = db.createObjectStore('notes', { keyPath: 'id' });
store.createIndex('by_date', 'date');
};
Test yourself
-
What does an index provide?
- It bumps the database version
- It deletes all records
- It creates a new object store
- Fast lookups by a specific field
Show answer
Fast lookups by a specific field — Correct! An index enables fast lookups by a field.
-
Create an index
const index = store.____('by_date', 'date');Show answer
const index = store.createIndex('by_date', 'date'); -
Match index terms
- createIndex
- create an index
- IDBKeyRange
- key range
- index.getAll
- fetch all matches
- index.get
- fetch one record