Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / JavaScript

IDBIndex — upiti nad indeksom IndexedDB

IDBIndex omogućuje pristup zapisima spremišta objekata putem sekundarnog ključa. Usporedite dohvaćanje polja pomoću getAll() s iteracijom pokazivača pomoću openCursor() i razlikujte ključeve indeksa od primarnih ključeva.

Verzija: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Sintaksa

const index = transaction.objectStore(storeName).index(indexName);
const valuesRequest = index.getAll(query, count);
const cursorRequest = index.openCursor(query, "next");

IDBIndex je referenca na sekundarni indeks spremišta objekata IndexedDB, a ne konstruktor za izravnu upotrebu. Indeks izradite pomoću createIndex() tijekom upgradeneeded; kasnije ga dohvatite pomoću store.index(name) unutar transakcije. Indeks se automatski ažurira zajedno sa spremištem.

IDBIndex.getAll(query, count) vraća IDBRequest, a ne Promise. Rezultat je polje vrijednosti spremišta ili [] ako nema podudaranja. query prihvaća ključ indeksa ili IDBKeyRange; ako ga izostavite, podudaraju se svi unosi. Neobavezni parametar count ograničava broj rezultata. Ako je njegova vrijednost 0 ili ga izostavite, vraćaju se svi podudarni unosi. Redoslijed je uzlazni prema ključu indeksa, a zatim prema primarnom ključu.

IDBIndex.openCursor(query, direction) također vraća IDBRequest. U success pročitajte pokazivač ili null ako više nema rezultata; continue() pokreće sljedeći korak. cursor.key je ključ indeksa, cursor.primaryKey ključ spremišta, a cursor.value zapis. Zadani je smjer "next"; dostupni su i "prev", "nextunique" i "prevunique".

Pokazivač omogućuje postupnu obradu; getAll() materijalizira cijelo polje rezultata. Zahtjeve šaljite dok je transakcija aktivna; nemojte između njih umetati nepovezani await. Primjer upotrebljava sintaksu IndexedDB 2.0, bez novijeg oblika opcija za getAll(). Provjerite ciljni preglednik: sama prisutnost Node 24 ne dokazuje podršku za ovaj Web API.

Primjeri

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IDBIndex: querying a secondary key</title>
</head>
<body>
  <h1>Querying an IndexedDB index</h1>
  <script>
    (() => {
      const name = 'cktis-index-' + crypto.getRandomValues(new Uint32Array(4)).join('-');
      const report = error => console.log(error.name === 'SecurityError'
        ? 'IndexedDB unavailable: SecurityError' : `IndexedDB error: ${error.name}`);
      let factory, opening;
      try {
        factory = window.indexedDB;
        if (!factory) {
          console.log('IndexedDB unavailable: API missing');
          return;
        }
        opening = factory.open(name, 1);
      } catch (error) {
        report(error);
        return;
      }
      let created = false;
      opening.onerror = () => report(opening.error);
      opening.onupgradeneeded = () => {
        created = true;
        const store = opening.result.createObjectStore('tokens', { keyPath: 'id' });
        store.createIndex('byColor', 'color');
        store.add({ id: 2, color: 'blue', token: 'square' });
        store.add({ id: 1, color: 'blue', token: 'circle' });
        store.add({ id: 3, color: 'red', token: 'triangle' });
      };
      opening.onsuccess = () => {
        const db = opening.result;
        if (!created) {
          db.close();
          console.log('Fixture name already in use');
          return;
        }
        const tx = db.transaction('tokens', 'readonly');
        const index = tx.objectStore('tokens').index('byColor');
        const all = index.getAll('blue');
        const scan = index.openCursor('blue');
        const rows = [];
        scan.onsuccess = () => {
          const cursor = scan.result;
          if (cursor) {
            rows.push([cursor.key, cursor.primaryKey, cursor.value.token]);
            cursor.continue();
          }
        };
        const cleanup = () => {
          db.close();
          factory.deleteDatabase(name);
        };
        tx.oncomplete = () => {
          console.log(JSON.stringify(all.result.map(record => record.token)));
          console.log(JSON.stringify(rows));
          cleanup();
        };
        tx.onabort = () => {
          report(tx.error);
          cleanup();
        };
      };
    })();
  </script>
</body>
</html>

Rezultat

When IndexedDB access is allowed and the query succeeds, both lines show matches for the index key "blue" in ascending primary-key order:
["circle","square"]
[["blue",1,"circle"],["blue",2,"square"]]

If the browser denies IndexedDB access with a SecurityError, the example logs instead:
IndexedDB unavailable: SecurityError

Prikazani kôd i navedeni rezultat provjereni su u izoliranom okruženju metodom zabilježenom u dokazu provjere za ovu točnu verziju.

Izvori