Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IndexedDB: Create an index, insert a record, and query by index

Create a secondary index during a database upgrade, insert without overwriting, and look up a record by its index key rather than its primary key.

Version: Current web platform; runtime support varies

Syntax

store.createIndex(name, keyPath)
store.createIndex(name, keyPath, { unique, multiEntry })
store.add(value)
store.add(value, key)
store.index(name)

IDBObjectStore.createIndex/add/index groups three instance methods: createIndex() defines an index, add() inserts a record, and index() retrieves an existing index handle. They belong to the IndexedDB Web API, not ECMAScript. IndexedDB follows the same-origin policy, and availability depends on the runtime and browser storage settings.

store.createIndex(name, keyPath, options) returns an IDBIndex immediately, but the schema change only takes effect permanently if the transaction commits. Call it in an active versionchange transaction, typically in upgradeneeded when creating a database or raising its version. The name identifies the index; the key path selects the index key from a record without adding a field. IndexedDB indexes existing records and keeps the index up to date automatically.

Both unique and multiEntry default to false. unique: true forbids duplicate index keys across records; duplicates in existing data can abort the upgrade. multiEntry: true indexes individual valid elements of an array value instead of the whole array as one key. It cannot be combined with an array of key paths for a compound key (InvalidAccessError). A duplicate index name throws ConstraintError immediately.

store.add(value[, key]) inserts a structured clone without overwriting. Use an active readwrite or versionchange transaction. Omit key for an inline primary key; supply it for out-of-line keys without a generator. The IDBRequest gets the primary key as its result on success, but only the transaction's complete event confirms the commit. A duplicate primary key or unique-index key fails the request with ConstraintError; put() can replace a record but still has to respect index uniqueness.

store.index(name) returns the existing IDBIndex bound to the same transaction. It neither creates an index nor reads a record. A missing name throws NotFoundError; names are case-sensitive. In an active transaction, index.get(key) requests the first matching record by index key, not primary key. Do not reuse the handle for reads after the transaction finishes.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IndexedDB: insert and look up a contact</title>
</head>
<body>
<script>
(async () => {
  const { indexedDB, crypto } = window;
  const name = `cktis-index-${crypto.randomUUID()}`;
  const resultOf = (request) => new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
  const committed = (tx) => new Promise((resolve, reject) => {
    tx.oncomplete = () => resolve();
    tx.onabort = () => reject(tx.error ?? new Error('Transaction aborted'));
  });

  const open = indexedDB.open(name, 1);
  open.onupgradeneeded = () => {
    const store = open.result.createObjectStore('contacts', { keyPath: 'id' });
    store.createIndex('byEmail', 'email', { unique: true });
  };
  const db = await resultOf(open);
  let contact;
  try {
    const write = db.transaction('contacts', 'readwrite');
    write.objectStore('contacts').add({ id: 7, email: 'ada@example.test' });
    await committed(write);

    const read = db.transaction('contacts', 'readonly');
    const lookup = read.objectStore('contacts').index('byEmail').get('ada@example.test');
    await committed(read);
    contact = lookup.result;
  } finally {
    db.close();
    await resultOf(indexedDB.deleteDatabase(name));
  }
  console.log(JSON.stringify(contact));
})().catch((error) => console.error(error));
</script>
</body>
</html>

Result

{"id":7,"email":"ada@example.test"}

Serve the HTML file from a trusted HTTPS origin and open it in a browser with IndexedDB and `crypto.randomUUID()` available. The example creates a separate database, looks up the record by `email` after the write commits, then closes and deletes the database before logging the result to the browser console.

Related lessons

  • JavaScript · Lesson 31 · Advanced · Version: 4

Sources