Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / JavaScript

IDBIndex — poizvedovanje po indeksu IndexedDB

IDBIndex omogoča dostop do zapisov shrambe objektov prek sekundarnega ključa. Primerjajte pridobivanje polja z getAll() z iteracijo kazalca prek openCursor() ter razlikujte med ključi indeksa in primarnimi ključi.

Različica: 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 sklic na sekundarni indeks shrambe objektov IndexedDB in ne konstruktor za neposredno uporabo. Indeks ustvarite z createIndex() med dogodkom upgradeneeded; pozneje ga v transakciji pridobite z store.index(name). Indeks se samodejno posodablja skupaj s shrambo.

IDBIndex.getAll(query, count) vrne IDBRequest, ne Promise. Rezultat je polje vrednosti shrambe ali [], če ni zadetkov. query sprejme ključ indeksa ali IDBKeyRange; če ga izpustite, se ujemajo vsi vnosi. Izbirni parameter count omeji število rezultatov. Če je njegova vrednost 0 ali ga izpustite, se vrnejo vsi zadetki. Vrstni red je naraščajoč po ključu indeksa, nato po primarnem ključu.

Tudi IDBIndex.openCursor(query, direction) vrne IDBRequest. V success preberite kazalec ali null, kadar ni več rezultatov; continue() začne naslednji korak. cursor.key je ključ indeksa, cursor.primaryKey je ključ shrambe, cursor.value pa zapis. Privzeta smer je "next"; na voljo so tudi "prev", "nextunique" in "prevunique".

Kazalec omogoča postopno obdelavo; getAll() ustvari celotno polje rezultatov. Zahteve pošljite, dokler je transakcija aktivna; mednje ne vstavljajte nepovezanega await. Primer uporablja sintakso IndexedDB 2.0 brez novejše oblike možnosti getAll(). Preverite ciljni brskalnik: prisotnost Node 24 ne dokazuje podpore za ta spletni API.

Primeri

<!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

Prikazana koda in navedeni rezultat sta bila preverjena v izoliranem okolju z metodo, zapisano v dokazilu o preverjanju te natančne različice.

Viri