IDBObjectStore: index() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2021.

IDBObjectStore インターフェイスの index() メソッドは、現在のオブジェクトストアの名前付きインデックスを開きます。開くと、たとえば、カーソルを用いてレコード群をそのインデックスでソートして取得できます。

メモ: この機能はウェブワーカー内で利用可能です。

構文

js
index(name)

引数

name

開くインデックスの名前です。

返値

指定のインデックスにアクセスするための IDBIndex オブジェクトです。

例外

InvalidStateError DOMException

元のオブジェクトストアが削除済か、オブジェクトストアのトランザクションが終了しているとき投げられます。

NotFoundError DOMException

指定の名前 (大文字と小文字を区別します) のインデックスがデータベースに存在しないとき投げられます。

以下の例では、トランザクションとオブジェクトストアを開き、シンプルな連絡先データベースからインデックス lName を取得します。そして、IDBIndex.openCursor を用いてこのインデックスで基本的なカーソルを開きます。これは、返されるレコードが主キーではなくインデックスに基づいてソートされる以外、IDBObjectStore.openCursor を用いて ObjectStore で直接カーソルを開くのと同じように動きます。

最後に、レコードを走査し、データを HTML テーブルに挿入します。動く例全体は、IndexedDB-examples デモリポジトリー内の IDBIndex 例 を参照してください。(動く例を見る)

js
function displayDataByIndex() {
  tableEntry.innerHTML = "";
  const transaction = db.transaction(["contactsList"], "readonly");
  const objectStore = transaction.objectStore("contactsList");

  const myIndex = objectStore.index("lName");
  myIndex.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.value.id}</td>` +
        `<td>${cursor.value.lName}</td>` +
        `<td>${cursor.value.fName}</td>` +
        `<td>${cursor.value.jTitle}</td>` +
        `<td>${cursor.value.company}</td>` +
        `<td>${cursor.value.eMail}</td>` +
        `<td>${cursor.value.phone}</td>` +
        `<td>${cursor.value.age}</td>`;
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("全エントリーを表示しました。");
    }
  };
}

仕様書

Specification
Indexed Database API 3.0
# dom-idbobjectstore-index

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
index

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報