IndexedDB indexes, ranges and cursors
Quick answer
An index lets a store be searched using a secondary key. Key ranges restrict matching keys; cursors traverse matching records without building a full result array.
How it works
Create indexes during upgrade. store.index(name) returns an IDBIndex. getAll(query) collects matching values; IDBKeyRange.only(value) matches one key. openCursor(query, direction?) returns a request whose success handler receives a cursor or null. Call cursor.continue() while the transaction is active. Prefer bounded retrieval for large collections.
Local examples
NOT RUN here. Run only on a disposable, isolated HTTP(S) test origin. The snippet deletes its dedicated fixture database; never use a production origin.
(async () => {const name="bytemind-v12-fixture";const requestValue=r=>new Promise((resolve,reject)=>{r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});const finished=tx=>new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=()=>reject(tx.error||new Error("aborted"));});await requestValue(indexedDB.deleteDatabase(name));const open=indexedDB.open(name,1);open.onupgradeneeded=()=>{const s=open.result.createObjectStore("items",{keyPath:"id"});s.createIndex("byCategory","category");};const db=await requestValue(open);try{const tx=db.transaction("items","readwrite"),done=finished(tx),s=tx.objectStore("items");s.put({id:2,category:"a"});s.put({id:1,category:"a"});s.put({id:3,category:"b"});await done;const rows=await requestValue(db.transaction("items").objectStore("items").index("byCategory").getAll(IDBKeyRange.only("a")));console.log(JSON.stringify(rows.map(x=>x.id)));}finally{db.close();await requestValue(indexedDB.deleteDatabase(name));}})()Expected console output:
[1,2]Equal index keys are ordered by primary key.
NOT RUN here. Run only on a disposable, isolated HTTP(S) test origin. The snippet deletes its dedicated fixture database; never use a production origin.
(async () => {const name="bytemind-v12-fixture";const requestValue=r=>new Promise((resolve,reject)=>{r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});const finished=tx=>new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=()=>reject(tx.error||new Error("aborted"));});await requestValue(indexedDB.deleteDatabase(name));const open=indexedDB.open(name,1);open.onupgradeneeded=()=>{const s=open.result.createObjectStore("items",{keyPath:"id"});s.createIndex("byCategory","category");};const db=await requestValue(open);try{const tx=db.transaction("items","readwrite"),done=finished(tx),s=tx.objectStore("items");s.put({id:2});s.put({id:1});await done;const ids=[];await new Promise((resolve,reject)=>{const r=db.transaction("items").objectStore("items").openCursor();r.onerror=()=>reject(r.error);r.onsuccess=()=>{const c=r.result;if(!c){resolve();return;}ids.push(c.key);c.continue();};});console.log(JSON.stringify(ids));}finally{db.close();await requestValue(indexedDB.deleteDatabase(name));}})()Expected console output:
[1,2]The default store cursor traverses increasing keys.
Common mistakes
An index is not automatically unique. Its ordering is by index key and then primary key, not arbitrary insertion order.
Guided practice
Query two items in one category and compare getAll with a cursor walk.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
IndexedDB indexes, ranges and cursors — Knowledge Check
Apply the concept and reason about the example output.
When is an index created?
What does IDBKeyRange.only select?
What signals cursor exhaustion?
What is the expected console output of IndexedDB indexes, ranges and cursors example 1?
(async () => {const name="bytemind-v12-fixture";const requestValue=r=>new Promise((resolve,reject)=>{r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});const finished=tx=>new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=()=>reject(tx.error||new Error("aborted"));});await requestValue(indexedDB.deleteDatabase(name));const open=indexedDB.open(name,1);open.onupgradeneeded=()=>{const s=open.result.createObjectStore("items",{keyPath:"id"});s.createIndex("byCategory","category");};const db=await requestValue(open);try{const tx=db.transaction("items","readwrite"),done=finished(tx),s=tx.objectStore("items");s.put({id:2,category:"a"});s.put({id:1,category:"a"});s.put({id:3,category:"b"});await done;const rows=await requestValue(db.transaction("items").objectStore("items").index("byCategory").getAll(IDBKeyRange.only("a")));console.log(JSON.stringify(rows.map(x=>x.id)));}finally{db.close();await requestValue(indexedDB.deleteDatabase(name));}})()What is the expected console output of IndexedDB indexes, ranges and cursors example 2?
(async () => {const name="bytemind-v12-fixture";const requestValue=r=>new Promise((resolve,reject)=>{r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);});const finished=tx=>new Promise((resolve,reject)=>{tx.oncomplete=resolve;tx.onabort=()=>reject(tx.error||new Error("aborted"));});await requestValue(indexedDB.deleteDatabase(name));const open=indexedDB.open(name,1);open.onupgradeneeded=()=>{const s=open.result.createObjectStore("items",{keyPath:"id"});s.createIndex("byCategory","category");};const db=await requestValue(open);try{const tx=db.transaction("items","readwrite"),done=finished(tx),s=tx.objectStore("items");s.put({id:2});s.put({id:1});await done;const ids=[];await new Promise((resolve,reject)=>{const r=db.transaction("items").objectStore("items").openCursor();r.onerror=()=>reject(r.error);r.onsuccess=()=>{const c=r.result;if(!c){resolve();return;}ids.push(c.key);c.continue();};});console.log(JSON.stringify(ids));}finally{db.close();await requestValue(indexedDB.deleteDatabase(name));}})()