首頁 > web前端 > js教程 > 主體

索引資料庫

PHPz
發布: 2024-09-06 21:01:10
原創
752 人瀏覽過

索引資料庫解決什麼問題?


索引資料庫 是一種儲存大量結構化資料(甚至離線)的解決方案。它解決了 Web 應用程式的高效本地儲存問題,使它們能夠直接在客戶端存取、更新和查詢大型資料集。


索引資料庫 解決的關鍵問題:

  • 結構化資料的持久性本地儲存。
  • 大型資料集的高效儲存和檢索。
  • 跨離線和線上模式的功能。
  • 非同步存取數據,防止主執行緒阻塞。

程式碼範例:

// Open an 索引資料庫 database
let request = indexedDB.open("MyDatabase", 1);

request.onupgradeneeded = function(event) {
  let db = event.target.result;
  // Create an object store
  let objectStore = db.createObjectStore("users", { keyPath: "id" });
  objectStore.createIndex("name", "name", { unique: false });
};

request.onsuccess = function(event) {
  let db = event.target.result;
  console.log("Database opened successfully");
};
登入後複製

如何使用 索引資料庫

開啟資料庫:使用indexedDB.open()函數開啟索引資料庫資料庫。
建立物件儲存:物件儲存類似於關聯式資料庫中的表格。
執行事務:使用交易來新增、檢索、更新或刪除資料。
索引建立:索引用於在物件儲存中搜尋資料。
錯誤處理:使用事件監聽器處理非同步操作。

// Adding data to 索引資料庫
let addData = function(db) {
  let transaction = db.transaction(["users"], "readwrite");
  let objectStore = transaction.objectStore("users");

  let user = { id: 1, name: "Alice", email: "alice@example.com" };
  let request = objectStore.add(user);

  request.onsuccess = function() {
    console.log("User added to 索引資料庫!");
  };
};

// Retrieve data
let getData = function(db) {
  let transaction = db.transaction(["users"], "readonly");
  let objectStore = transaction.objectStore("users");

  let request = objectStore.get(1);
  request.onsuccess = function(event) {
    console.log("User:", event.target.result);
  };
};
登入後複製

索引資料庫 的優點
索引資料庫 提供了幾個關鍵優勢,使其成為現代 Web 應用程式的理想選擇

  • 儲存容量大:索引資料庫 相較於 localStorage 或 sessionStorage 可以儲存更多資料

索引資料庫

  • 非同步存取:透過使用非阻塞 I/O 操作來防止阻塞 UI。

  • 複雜資料處理:支援結構化數據,包括陣列、物件和 blob。

  • 離線支援:線上和離線工作,允許漸進式 Web 應用程式 (PWA) 用例。

  • 索引搜尋:可以透過索引有效率地搜尋資料。
    索引資料庫

索引資料庫

// Create an index to improve search performance
objectStore.createIndex("email", "email", { unique: true });

let emailIndex = objectStore.index("email");
let request = emailIndex.get("alice@example.com");

request.onsuccess = function(event) {
  console.log("User found by email:", event.target.result);
};

登入後複製

索引資料庫

*了解 索引資料庫 索引
*

什麼是 索引資料庫 索引?
索引資料庫 索引是物件儲存中的附加資料結構,允許根據特定屬性高效檢索資料。索引由關鍵路徑(一個或多個屬性)和定義唯一性和排序順序的選項組成。透過建立索引,您可以優化資料查詢和過濾操作,從而提高效能。

索引資料庫 中索引的重要性
索引在增強 索引資料庫 的資料檢索效能方面發揮著至關重要的作用。如果沒有索引,根據特定屬性查詢資料將需要迭代所有記錄,從而導致資料檢索速度變慢且效率低下。索引可以根據索引屬性直接存取數據,減少全表掃描的需要並顯著提高查詢執行速度。

let transaction = db.transaction("MyObjectStore", "readonly");
let objectStore = transaction.objectStore("MyObjectStore");
let index = objectStore.index("nameIndex");

let cursorRequest = index.openCursor();

cursorRequest.onsuccess = function(event) {
  let cursor = event.target.result;
  if (cursor) {
    // Access the current record
    console.log(cursor.value);

    // Move to the next record
    cursor.continue();
  }
};
登入後複製

使用範圍查詢過濾資料 索引資料庫
索引還支援範圍查詢,可讓您根據一系列值過濾資料。以下是檢索特定年齡範圍內的記錄的範例:

let transaction = db.transaction("MyObjectStore", "readonly");
let objectStore = transaction.objectStore("MyObjectStore");
let index = objectStore.index("ageIndex");

let range = IDBKeyRange.bound(18, 30); // Records with age between 18 and 30

let cursorRequest = index.openCursor(range);

cursorRequest.onsuccess = function(event) {
  let cursor = event.target.result;
  if (cursor) {
    // Process the record within the desired age range
    console.log(cursor.value);

    // Move to the next record
    cursor.continue();
  }
};

登入後複製

使用索引對資料進行排序

索引也可以用於對 索引資料庫 中的資料進行排序。透過在索引上開啟遊標並指定所需的排序順序,您可以按所需的順序擷取記錄。

let transaction = db.transaction("MyObjectStore", "readonly");
let objectStore = transaction.objectStore("MyObjectStore");
let index = objectStore.index("nameIndex");

let cursorRequest = index.openCursor(null, "next"); // Sorted in ascending order

cursorRequest.onsuccess = function(event) {
  let cursor = event.target.result;
  if (cursor) {
    // Process the record
    console.log(cursor.value);

    // Move to the next record
    cursor.continue();
  }
};
登入後複製

索引維護與架構升級

為現有物件儲存新增索引
若要將新索引新增至現有物件儲存中,您需要處理資料庫升級程序。這是在資料庫升級期間新增索引的範例。

let request = indexedDB.open("MyDatabase", 2);

request.onupgradeneeded = function(event) {
  let db = event.target.result;
  let objectStore = db.createObjectStore("MyObjectStore", { keyPath: "id" });

  // Add a new index during upgrade
  objectStore.createIndex("newIndex", "newProperty", { unique: false });
};
登入後複製

在這個範例中,我們將資料庫版本從 1 升級到 2,並在「newProperty」屬性上新增名為「newIndex」的新索引。


效能注意事項與最佳實務
選出正確的 索引資料庫 索引
在建立索引時,根據應用程式的資料存取模式仔細選擇要建立索引的屬性非常重要。應在常用於過濾、排序或搜尋的屬性上建立索引,以最大限度地發揮其優勢。

限制索引大小和效能影響
大型索引會消耗大量儲存空間並影響效能。建議限制索引的數量並選擇高效資料檢索所需的關鍵路徑。避免過多的索引以保持最佳效能。

Monitoring Index Performance
Regularly monitor the performance of your 索引資料庫 indexes using browser developer tools and profiling techniques. Identify any slow queries or bottlenecks and optimize your indexes accordingly. It may involve modifying the index structure or adding additional indexes to improve query execution speed.


Cursor in 索引資料庫

let request = indexedDB.open("MyDatabase", 1);

request.onsuccess = function(event) {
  let db = event.target.result;
  let transaction = db.transaction(["users"], "readonly");
  let objectStore = transaction.objectStore("users");

  let cursorRequest = objectStore.openCursor();
  let batchSize = 10;
  let count = 0;

  cursorRequest.onsuccess = function(event) {
    let cursor = event.target.result;
    if (cursor) {
      console.log("Key:", cursor.key, "Value:", cursor.value);
      count++;

      // If batch size is reached, stop processing
      if (count 




<hr>

<p><strong>索引資料庫 Sharding</strong></p>

<p>Sharding is a technique, normally used in server side databases, where the database is partitioned horizontally. Instead of storing all documents at one table/collection, the documents are split into so called shards and each shard is stored on one table/collection. This is done in server side architectures to spread the load between multiple physical servers which increases scalability.</p>

<p>When you use 索引資料庫 in a browser, there is of course no way to split the load between the client and other servers. But you can still benefit from sharding. Partitioning the documents horizontally into multiple 索引資料庫 stores, has shown to have a big performance improvement in write- and read operations while only increasing initial pageload slightly.</p>

<p><img src="https://img.php.cn/upload/article/000/000/000/172562768663567.jpg" alt="索引資料庫"></p>


<hr>

<p><strong>Conclusion</strong><br>
索引資料庫 represents a paradigm shift in browser-based storage, empowering developers to build powerful web applications with offline capabilities and efficient data management. By embracing 索引資料庫 and adhering to best practices, developers can unlock new possibilities in web development, delivering richer and more responsive user experiences across a variety of platforms and devices. As the web continues to evolve, 索引資料庫 stands as a testament to the innovative solutions driving the next generation of web applications.</p>


<hr>


          

            
        
登入後複製

以上是索引資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!