IndexedDB

PHPz
풀어 주다: 2024-09-06 21:01:10
원래의
752명이 탐색했습니다.

IndexedDB는 어떤 질문을 해결합니까?


IndexedDB는 대량의 정형 데이터를 오프라인에서도 저장할 수 있는 솔루션입니다. 이는 웹 애플리케이션을 위한 효율적인 로컬 스토리지 문제를 해결하여 클라이언트 측에서 직접 대규모 데이터 세트에 액세스, 업데이트 및 쿼리할 수 있도록 합니다.


IndexedDB가 해결하는 주요 문제:

  • 구조화된 데이터의 지속적인 로컬 저장.
  • 대규모 데이터세트를 효율적으로 저장하고 검색합니다.
  • 오프라인과 온라인 모드를 넘나드는 기능.
  • 데이터에 대한 비동기 액세스로 메인 스레드 차단을 방지합니다.

코드 예:

// Open an IndexedDB 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 사용방법

데이터베이스 열기: indexedDB.open() 함수를 사용하여 IndexedDB 데이터베이스를 엽니다.
객체 저장소 생성: 객체 저장소는 관계형 데이터베이스의 테이블과 유사합니다.
트랜잭션 수행: 트랜잭션을 사용하여 데이터를 추가, 검색, 업데이트 또는 삭제합니다.
인덱스 생성: 인덱스는 객체 저장소 내에서 데이터를 검색하는 데 사용됩니다.
오류 처리: 이벤트 리스너를 사용하여 비동기 작업을 처리합니다.

// Adding data to IndexedDB
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 IndexedDB!");
  };
};

// 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);
  };
};
로그인 후 복사

IndexedDB의 장점
IndexedDB는 최신 웹 애플리케이션에 이상적인 몇 가지 주요 이점을 제공합니다

  • 큰 저장 용량: IndexedDB는 localStorage나 sessionStorage에 비해 더 많은 데이터를 저장할 수 있습니다

IndexedDB

  • 비동기 액세스: 비차단 I/O 작업을 사용하여 UI 차단을 방지합니다.

  • 복잡한 데이터 처리: 배열, 객체, Blob을 포함한 구조화된 데이터를 지원합니다.

  • 오프라인 지원: 온라인과 오프라인 모두에서 작동하므로 PWA(프로그레시브 웹 앱) 사용 사례가 가능합니다.

  • 색인 검색: 색인을 통해 데이터를 효율적으로 검색할 수 있습니다.
    IndexedDB

IndexedDB

// 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);
};

로그인 후 복사

IndexedDB

*IndexedDB 인덱스 이해
*

IndexedDB 인덱스란 무엇인가요?
IndexedDB 인덱스는 특정 속성을 기반으로 데이터를 효율적으로 검색할 수 있는 객체 저장소 내의 추가 데이터 구조입니다. 인덱스는 키 경로(하나 이상의 속성)와 고유성과 정렬 순서를 정의하는 옵션으로 구성됩니다. 인덱스를 생성하면 데이터 쿼리 및 필터링 작업을 최적화하여 성능을 향상시킬 수 있습니다.

IndexedDB에서 인덱스의 중요성
인덱스는 IndexedDB에서 데이터 검색 성능을 향상시키는 데 중요한 역할을 합니다. 인덱스가 없으면 특정 속성을 기반으로 데이터를 쿼리하려면 모든 레코드를 반복해야 하므로 데이터 검색 속도가 느리고 효율성이 떨어집니다. 인덱스를 사용하면 인덱스된 속성을 기반으로 데이터에 직접 액세스할 수 있으므로 전체 테이블 검색의 필요성이 줄어들고 쿼리 실행 속도가 크게 향상됩니다.

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();
  }
};
로그인 후 복사

범위 쿼리 IndexedDB로 데이터 필터링
또한 인덱스를 사용하면 범위 쿼리가 가능하므로 값 범위를 기준으로 데이터를 필터링할 수 있습니다. 특정 연령 범위 내의 기록을 검색하는 예는 다음과 같습니다.

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();
  }
};

로그인 후 복사

인덱스로 데이터 정렬

인덱스는 IndexedDB에서 데이터를 정렬하는 데에도 활용될 수 있습니다. 인덱스에 커서를 열고 원하는 정렬 순서를 지정하면 원하는 순서로 레코드를 검색할 수 있습니다.

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"라는 새 인덱스를 추가합니다.


성능 고려 사항 및 모범 사례
올바른 IndexedDB 인덱스 선택
인덱스를 생성할 때 애플리케이션의 데이터 액세스 패턴에 따라 인덱스할 속성을 신중하게 선택하는 것이 중요합니다. 필터링, 정렬 또는 검색에 일반적으로 사용되는 속성에 대해 인덱스를 생성하여 이점을 극대화해야 합니다.

인덱스 크기 제한 및 성능 영향
큰 인덱스는 상당한 저장 공간을 소비하고 성능에 영향을 줄 수 있습니다. 효율적인 데이터 검색을 위해 인덱스 수를 제한하고 필요한 키 경로를 선택하는 것이 좋습니다. 최적의 성능을 유지하려면 과도한 색인 생성을 피하세요.

Monitoring Index Performance
Regularly monitor the performance of your IndexedDB 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 IndexedDB

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>IndexedDB 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 IndexedDB 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 IndexedDB 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="IndexedDB"></p>


<hr>

<p><strong>Conclusion</strong><br>
IndexedDB represents a paradigm shift in browser-based storage, empowering developers to build powerful web applications with offline capabilities and efficient data management. By embracing IndexedDB 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, IndexedDB stands as a testament to the innovative solutions driving the next generation of web applications.</p>


<hr>


          

            
        
로그인 후 복사

위 내용은 IndexedDB의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!