Querying with Key Ranges
What You'll Learn
You'll learn how to create IDBKeyRange objects to query specific ranges of data in IndexedDB using bounds and limits, rather than fetching all records.
Why Key Ranges Matter
Imagine you're searching through a library catalog. Instead of flipping through every single book, you tell the librarian "I want all books published between 2015 and 2020." That's exactly what key ranges do in IndexedDB—they let you specify boundaries for your queries.
The IDBKeyRange Interface
IndexedDB provides the IDBKeyRange object to define ranges of keys you want to retrieve. This is especially powerful when combined with cursors or indexes.
Creating Key Ranges
IDBKeyRange.only(key) — Matches exactly one key:
const singleRange = IDBKeyRange.only(42);
// Retrieves only the record with key 42
IDBKeyRange.lowerBound(lower, open) — Matches keys greater than (or equal to) a value:
const fromRange = IDBKeyRange.lowerBound(100);
// Keys >= 100
const exclusiveRange = IDBKeyRange.lowerBound(100, true);
// Keys > 100
IDBKeyRange.upperBound(upper, open) — Matches keys less than (or equal to) a value:
const upToRange = IDBKeyRange.upperBound(500);
// Keys <= 500
IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) — Matches keys within a range:
const betweenRange = IDBKeyRange.bound(100, 500);
// Keys >= 100 AND <= 500
const exclusiveRange = IDBKeyRange.bound(100, 500, true, true);
// Keys > 100 AND < 500
Using Key Ranges
You pass these ranges to methods like get(), getAll(), or when opening cursors to filter results without iterating through every record.
Key Takeaway: IDBKeyRange objects let you efficiently query subsets of IndexedDB data by defining upper and lower bounds, reducing the need to filter records manually.