CKTIS / JavaScript
IDBIndex — wyszukiwanie przez indeks IndexedDB
IDBIndex udostępnia rekordy magazynu według dodatkowego klucza. Porównaj pobieranie tablicy przez getAll() z iteracją kursorem openCursor() oraz odróżnij klucz indeksu od klucza głównego.
Wersja: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Składnia
const index = transaction.objectStore(storeName).index(indexName);
const valuesRequest = index.getAll(query, count);
const cursorRequest = index.openCursor(query, "next");IDBIndex to uchwyt indeksu wtórnego magazynu IndexedDB, a nie konstruktor do bezpośredniego użycia. Utwórz indeks przez createIndex() podczas upgradeneeded; później pobierz go przez store.index(name) w transakcji. Indeks jest aktualizowany automatycznie wraz z magazynem.
IDBIndex.getAll(query, count) zwraca IDBRequest, nie Promise. Wynikiem jest tablica wartości magazynu, a przy braku dopasowań []. query przyjmuje klucz indeksu lub IDBKeyRange; pominięcie oznacza wszystkie wpisy. Opcjonalny count ogranicza liczbę wyników, ale wartość 0, tak jak pominięcie count, oznacza brak limitu: zwracane są wszystkie dopasowania. Kolejność jest rosnąca według klucza indeksu, następnie klucza głównego.
IDBIndex.openCursor(query, direction) również zwraca IDBRequest. W success odczytaj kursor lub null, gdy brak dalszych wyników; continue() uruchamia kolejny krok. cursor.key to klucz indeksu, cursor.primaryKey — klucz magazynu, a cursor.value — rekord. Kierunek domyślny to "next"; dostępne są też "prev", "nextunique" i "prevunique".
Kursor pozwala przetwarzać rekordy stopniowo; getAll() materializuje całą tablicę wynikową. Żądania zgłaszaj w aktywnej transakcji; nie wstawiaj między nie niezwiązanego await. Przykład używa składni z IndexedDB 2.0, bez nowszego wariantu opcji getAll(). Sprawdź docelową przeglądarkę: obecność Node 24 nie dowodzi obsługi tego Web API.
Przykłady
<!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>Wynik
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
Wyświetlony kod i zadeklarowany wynik zweryfikowano w odizolowanym środowisku metodą zapisaną w dowodzie weryfikacji tej dokładnej wersji.