Channels ▼
RSS

JVM Languages

Exploring IndexedDB


Retrieving a Single Data Item from an Object Store

Retriving data is similar syntactically to inserting and deleting data. We can retrieve only a single JavaScript object that is uniquely identified by the key passed to the get() method of the object.


//retrieve the sample object with id(unique key) having some value (say 2)

var id =2;

transaction = myDAO.db.transaction(["BookList"],IDBTransaction.READ_WRITE);

request = transaction.objectStore("BookList").get(id);

request.onsuccess = function(event)

{

    var resObj = request.result; //request.result represents the retrieved object.

    alert(resObj.author); 

};

request.onerror = function(e)

{

};

Retrieving Multiple Data Items from an Object Store

To retrieve multiple objects from an object store, we need the help of cursors. Using a range cursor, we can retrieve all the objects within the specified range. To create a range cursor, there is a special predefined object to be used: webkitIDBKeyRange in Chrome and IDBKeyRange in Mozilla Firefox. We pass this KeyRange object to the method openCursor(). For displaying all the data (Objects), we need to create a simple cursor, by invoking the method openCursor() of the object store without arguments.


window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;

keyRange = new IDBKeyRange.bound(1, new Date().getTime());

transaction = myDAO.db.transaction(["BookList"], IDBTransaction.READ_WRITE);

//myDAO.objectStore = transaction.objectStore("BookList");

request = transaction.objectStore("BookList").openCursor(keyRange);

request.onsuccess = function(event)

{

    myDAO.cursor = request.result;

    if (!myDAO.cursor)

    {

         return;

    }

    DAO.cursor.continue();

};

Request.onerror = function()

{. . .}

Creating Indexes on an Object Store

In a normal retrieve operation, we can search for objects only by the unique key. In the event we want to search using other fields, we need to create indexes on those fields. And just like object stores, indexes must be created inside a setVersion() method. An index is created using the createIndex() method.


request = myDAO.db.setVersion(parseInt(Math.random() * 100));

request.onsuccess = function(e)

{

var transaction = request.transaction;

    var objectStore = transaction.objectStore("BookList");

   myDAO.index = objectStore.createIndex("priceIndex", "price");

   divObj.innerHTML+="<br/>Index created "+ DAO.index;

};

request.onerror = function(e)

{

. . . . . . . 

};

Getting an Index

To perform any operation using the index we have created, we need to have a reference to the index object. And once we have the reference, we can perform the operations by using the methods provided by IndexedDB on the index object.


transaction = myDAO.db.transaction(["BookList"], IDBTransaction.READ_WRITE);

myDAO.objectStore = transaction.objectStore("BookList");

myDAO.index = myDAO.objectStore.index("priceIndex");

Iteration Using an Index

We use a cursor to iterate through all items using the index, similar to the way we iterate for multiple rows via a cursor obtained from object store. We can pass ranged data for the indexed field as an argument to openKeyCursor() to fetch entries based on the index value being between a given range. And we can search on the index for particular value of the field by calling index.get(fldValue).


var cursorRequest = myDAO.index.openKeyCursor();

cursorRequest.onsuccess = function(event)

{

    var objectCursor = cursorRequest.result;

    if (!objectCursor) 

    {

         return;

    }

    //write into a sample DIV tag for testing purposes

    Document.getElementById("myDiv").innerHTML += "Indexed on price: " +objectCursor.key+ 

    " Object id- "+objectCursor.primaryKey;

    objectCursor["continue"]();

};

Conclusion

As you can see from this brief tour, IndexedDB is really a simple client-side storage API that provides basic database-like functionality for in-browser apps. As HTML5 is adopted by all browsers, the IndexedDB interface is likely to grow in importance. To explore it further, here are some useful links:


Kausar Munshi works as a developer in Java and Web Technologies. Basavaraju graduated from IIT Madras and has approximately 15 years of experience in IT.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video