Indexdb of html5 (nosql storage)

Source: Internet
Author: User
Tags createindex

Indexdb of html5 (nosql storage)

IndexedDB is an important part of HTML5-WebStorage and a lightweight NOSQL database. It is more efficient than web SQL (sqlite), including indexing, transaction processing, and robust query functions. IndexedDB features:

 

A website may have one or more IndexedDB databases. Each database must have a unique name. A database can contain one or more object storage services. An object storage service (uniquely identified by a name) is a set of records. Each record has a key and a value. This value is an object that can have one or more attributes. A key may be derived from a key path or explicitly set based on a key generator. A key generator automatically generates a unique continuous positive integer. The Key Path defines the key value path. It can be a single JavaScript identifier or multiple identifiers separated by periods. (A bit like a column database) in IndexedDB, almost all operations use the command-> request-> result method. For example, to query a record, return a request and obtain the query result in the result of the request. Another example is to open the database, return a request, and get the Returned Database reference in the result of the request. IndexedDB can be run only when it is placed on the web server.

 

1. Common indexedDB methods:

1) Get the indexedDB object: (this step is equivalent to creating a database in a traditional database)

 

if (!window.indexedDB) {      window.indexedDB = window.mozIndexedDB || window.webkitIndexedDB;  }  request.onupgradeneeded = function(event) {  alert(event.oldVersion);  db = request.result;  if (db.objectStoreNames.contains('books')) {  db.deleteObjectStore('books');  }  var store = db.createObjectStore(books, {keyPath: isbn});  var titleIndex = store.createIndex(by_title, title, {unique: true});  var authorIndex = store.createIndex(by_author, author);  // Populate with initial data.  store.put({title: Quarry Memories, author: Fred, isbn: 123456,other:..ceshi....});  store.put({title: Water Buffaloes, author: Fred, isbn: 234567});  store.put({title: Bedrock Nights, author: Barney, isbn: 3456780000000000000});};var request = indexedDB.open(MyTestDatabase);  request.onsuccess = function(e) {      var db = request.result;  } 

 

Note: We recommend that you create a table during initialization. Each time you open the browser, you only need to check the version number and do not need to create it again. (The onupgradeneeded method is called only when the version is changed or the first time)

2) initialize objectStore: (equivalent to a table in a traditional database)
request.onupgradeneeded = function(event) {  alert(event.oldVersion);  db = request.result;  if (db.objectStoreNames.contains('books')) {  db.deleteObjectStore('books');  }  var store = db.createObjectStore(books, {keyPath: isbn});  var titleIndex = store.createIndex(by_title, title, {unique: true});  var authorIndex = store.createIndex(by_author, author);  // Populate with initial data.  store.put({title: Quarry Memories, author: Fred, isbn: 123456,other:..ceshi....});  store.put({title: Water Buffaloes, author: Fred, isbn: 234567});  store.put({title: Bedrock Nights, author: Barney, isbn: 3456780000000000000});};
Note:

1. In indexedDB, similar to a column database, there is no column concept, and json objects without hierarchical restrictions are stored.

2. You can create an index through index.

3) transactions and cursors

1. In indexedDB, transactions are automatically committed or rolled back. Therefore, you do not need to manually commit or rollback.
Transactions are divided into three types:
IDBTransaction. READ_ONLY read-only
IDBTransaction. READ_WRITE readable and writable
IDBTransaction. VERSION_CHANGE Version Upgrade
We use the first two most. If the transaction level is not set, the default value is READ_ONLY.

2. A cursor is the only way to traverse object store. If the cursor is not set when it is opened, IDBCursor. NEXT is used by default. After you call cursor. continue, cursor re-calls the method on the onsuccess handle.

 

// Obtain IDBTransaction var transaction = db through IDBDatabase. transaction ([MERs]); // obtain IDBObjectStore var objectStore = transaction Through IDBTransaction. objectStore (MERS mers); // open the cursor to traverse all data in customers. openCursor (). onsuccess = function (event) {var cursor = event.tar get. result; if (cursor) {var key = cursor. key; var rowData = cursor. value; alert (rowData. name); cursor. continue ();}}

 

 

4) index query:
In the above example, objectStore. openCursor is queried Based on keyPath. If you want to query through an index, you can use objectStore. index (index name). openCursor to query
1) The first parameter of openCursor is the query condition. It needs to input an IDBKeyRange object.
There are four methods for creating IDBKeyRange, all of which call the static method of IDBKeyRange. It represents four different types of conditions.
// Only obtain the IDBKeyRange of the Data whose current index value is Bill. only (Bill); // only obtains the value of the current index greater than Bill, and does not include the IDBKeyRange of Bill data. lowerBound (Bill, true); // only get the value of the current index less than Bill, and include the IDBKeyRange of Bill data. upperBound (Bill, false); // the value of the current index obtained is between Bill and Jack, and includes Bill, but does not include Jack's data IDBKeyRange. bound (Bill, Jack, false, true );
2) The second parameter of openCursor is the cursor direction. There are four types
IDBCursor. NEXT sequential Loop
IDBCursor. NEXT_NO_DUPLICATE sequence loops are not repeated.
IDBCursor. PREV reverse Loop
IDBCursor. PREV_NO_DUPLICATE the reverse loop is not repeated.

 

var boundKeyRange = IDBKeyRange.upperBound(Jack, false);  objectStore.index(name).openCursor(boundKeyRange, IDBCursor.PREV_NO_DUPLICATE).onsuccess = function(event) {          var cursor = event.target.result;                    if (!cursor) {              return;          }                    var rowData = cursor.value;                    alert(rowData.name);          cursor.continue();      }; 


 

2. instance:

 

<Script type = text/javascript src = http://www.jeasyuicn.com/cron/jquery.min.js > </Script> <script type = text/javascript> var db = null; if (! Window. indexedDB) {window. indexedDB = window. optional indexeddb | window. webkitIndexedDB;} var request = indexedDB. open (test, 3); request. onupgradeneeded = function (event) {alert (event. oldVersion); db = request. result; if (db. objectStoreNames. contains ('books ') {db. deleteObjectStore ('books ');} var store = db. createObjectStore (books, {keyPath: isbn}); var titleIndex = store. createIndex (by_title, title, {Unique: true}); var authorIndex = store. createIndex (by_author, author); // Populate with initial data. store. put ({title: Quarry Memories, author: Fred, isbn: 123456, other :.. ceshi ....}); store. put ({title: Water Buffaloes, author: Fred, isbn: 234567}); store. put ({title: Bedrock Nights, author: Barney, isbn: 3456780000000000000}) ;}; request. onsuccess = function () {db = request. result ;}; // obtained through transactions and Indexes Data function getDatas () {var tx = db. transaction (books, readonly); var store = tx. objectStore (books); var index = store. index (by_title); var request = index. get (Bedrock Nights); request. onsuccess = function () {var matching = request. result; if (matching! = Undefined) {// A match was found.((domaind1).html (matching. isbn ++ matching. title +; + matching. author);} else {// No match was found.((mongod1).html (123) ;};}// function getDatas1 () {var tx = db for obtaining data through transactions, cursors, and indexes. transaction (books, readonly); var store = tx. objectStore (books); var index = store. index (by_author); var request = index. openCursor (IDBKeyRange. only (Fred); var tmp =; request. onsuccess = function (event) {var cursor = request. result; // You can also write var cursor = event.tar get. result; if (cursor) {tmp + = cursor. value. isbn +; + cursor. value. title +; + cursor. value. author; cursor. continue ();} else Upload Failed (mongod1).html ('error... ') ;}((mongod1).html (tmp) ;};} function deleteDb () {var deleteDbRequest = indexedDB. deleteDatabase ('test'); deleteDbRequest. onsuccess = function (event) {alert ('success... ');}; deleteDbRequest. onerror = function (e) {alert ('error... ') ;}}</script> indexdb demo... 

Get Data
Get data 1
Delete Database
 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.