Showing posts with label Index. Show all posts
Showing posts with label Index. Show all posts

Friday, September 21, 2012

IndexedDB: MultiEntry explained

For a long time I was not sure what the purpose of the multiEntry attribute was. Since non of the browsers supported it yet, but since sometime Firefox and even the latest builds of Chrome support it, it all came clear to me. The multiEntry attribute enables you to filter on the individual values of an array.For this reason, the multiEntry attribute is only useful when the index is put on a property that contains an array as value.

When the multiEntry attribute is on true, there will be a record added for every value in the array. The key of this record will be the value of the array and the value will be the object keeping the array. Because the values in the array are used as key, means that the values inside the array need to be valid keys. This means they can only be of the following types:

  • Array
  • DOMString
  • float
  • Date

So far for the theory, an example will make everything clear.

In the example below I will use an object Blog. A blog contains out of the following properties:

   1: var blog = { Id: 1
   2:            , Title: "Blog post"
   3:            , content: "content"
   4:            , tags: ["html5", "indexeddb", "linq2indexeddb"]};


In the indexeddb we have an object store called blog which has an index on the tags property. The index has the multiEntry attribute turned on. If we would insert the object above, we would see the following records in the index:















keyvalue
“"html5”{ Id:1, Title: “Blogpost”, content:”content”, tags: [“html5”, “indexeddb”, “linq2indexeddb”]}
“indexeddb”{ Id:1, Title: “Blogpost”, content:”content”, tags: [“html5”, “indexeddb”, “linq2indexeddb”]}
“linq2indexeddb”{ Id:1, Title: “Blogpost”, content:”content”, tags: [“html5”, “indexeddb”, “linq2indexeddb”]}

So for every value in the array of the tags attribute, a record is added in the index. This means when you start filtering, it is possible that the same object can be added to the result multiple times. For example if you would filter on all tags greater then “i”, the result would be 2 times the blog object I use in this example.

Friday, November 25, 2011

Indexed DB: Reading data

Finally we get to the part where we can see the results of our Indexed DB tutorial. For the last few moths we have been structuring our database, adding data and now I’ll show how you can read data from an Indexed DB. For this we have 2 approaches. First one is retrieving a single record and the other way is retrieving a collection of records by a cursor.

In this post I’ll handle the retrieving of a single record. A post about retrieving data with a cursor will appear in the near future.

Retrieving data from an object store

In the IObjectStore interface we have an get method to retrieve data. This method must be provided with a key we want to search on. The key parameter can be a valid key or a key range. In case you don’t provide a valid key, a DATA_ERR exception will be thrown.

In the first situation a record of the object store will be retrieved where the given key is the same as the key of the key/value pair. In the other situation, the first record will be retrieved that matches one of the keys defined in the key range. If no record gets found, the result will be undefined. If you are using the Indexed DB prototype on IE 9, you’ll get an “Object with specified key not found.” error in stead of an result.

Time for some code:

When we want to read data, we need to create a transaction. This we do on the same way as for adding data. The only difference is we can use the IDBTransaction.READ_ONLY mode. This is the type that will be used as default when we create a transaction.

   1: var txn = dbconnection.transaction([“ObjectStoreName”]);
   2: var objectStore = txn.objectStore(“ObjectStoreName”);

The result of the get method is a IDBrequest object. When this is successful, the record is added to the result.



   1: var getReq = store.get(key);
   2: getReq.onsuccess = function(event) { 
   3:     var result;
   4:     // IE 9 implementation
   5:     if(event.result){
   6:         result = event.result;
   7:     }
   8:     // IE 10, Chrome and Firefox implementation
   9:     else if (getReq.result){
  10:         result = getReq.result;
  11:     }
  12:     // Code to present the result on your screen
  13: };

Retrieving data from an Index


In a previous post I have been talking about Indexes. Indexes make it possible to look up data from the object store by fields of the value object. By example: we have an object store person. In this object store we store persons. A person object has a first name and a last name field. By creating an index with a key path “last name”, we make it possible to retrieve data from the object store by providing the last name of the person.


In the IDBIndex interface we have the get method to retrieve a record from the object store, and the GetKey method to retrieve the key of the record from the object store. In both cases a key must be provided. This key parameter can be a valid key or a key range. For the rest every thing works the same as for retrieving data from an object store.


One think you need to keep in mind. In the Indexed DB prototype on IE9 the get and getKey method work different. In this case the getKey method retrieves the data and the get method the key of the record.



   1: var txn = dbconnection.transaction([“ObjectStoreName”]);
   2: var objectStore = txn.objectStore(“ObjectStoreName”);
   3: var index = store.index(“IndexName”);
   4: var getReq = index.getKey(key);
   5:  
   6: getReq.onsuccess = function(event) { 
   7:     var result;
   8:     if(event.result){
   9:         result = event.result;
  10:     }
  11:     else{
  12:         result = getReq.result
  13:     }
  14:     // Code to present the result on your screen
  15: };

Tuesday, October 25, 2011

Indexed DB: Defining the database structure

In previous post I have been talking about the basic concepts in the Indexed DB and how you can open/create a database and a database connection. Today I will tell you how you can construct your own database structure. This includes defining the object store where we can store our objects and defining indexes. These indexes will be used when searching into the objects we store in our database.

version_change transaction

There exists only one way to define your object stores and indexes, and this is in a VERSION_CHANGE transaction. We can start this transaction by calling the setVersion method on the database connection. When a database is initially created, the version of the database is an empty string. By passing a string as version to the setVersion method, we add object stores and indexes. This we do by defining the onsuccess event. We can also provide error handeling trough the onerror event.

var dbreq = dbConnection.setVersion(version);
dbreq.onsuccess = function (event) {
      // Here we put code to create object stores or indexes
}

dbreq.onerror = function (event) {
      // Here we put code to handle an error while changing the version
}

dbreq.onabort = function (event) {
      // Here we put code to handle an abort when changing the database version
}

If we are using the IE 9 Indexed DB prototype, we need to commit the transaction. In all other browsers this is not necessary because the implementation of Indexed DB determines that every transaction is committed by default when closed. If a transaction should be aborted you have to do this explicitly.

dbreq.onsuccess = function (event) {
       var txn;
       if (event.result) {
             txn = event.result;
       }
       // Here we put code to create object stores or indexes
      
       if(typeof(txn.commit) != "undefined")
       {
            txn.commit();
       }
}

Because a database can’t have multiple versions at one time, the only way you can change the version is by closing all other connections to the database. This also means no new connections can’t be opened until the VERSION_CHANGE transaction is completed. A blocked event will be raised when a connection to the database is still open when changing the version.

dbreq.onblocked = function (event) {
// Here we put code to handle an abort when changing the database version
}

Creating an objectStore

Once we started the VERSION_CHANGE transaction, we can start adding or deleting object stores. We can do this by calling the createObjectStore method. As first parameter we need to pass the name of the object store. Optionally you can can add two extra parameters. The first one is JSON object with two fields. The first field is a keyPath, when this is provided, the key of the object store will be determined by the field that has the name given in the string of the key path. The second field determines if the object store should have a key generator.

The last parameter we pass is the same as the autoIncrement field in the second parameter. We do this to enable the object store to have a key generator in the IE9 prototype. When using Firefox, Chrome and IE 10, you don’t need to pass this parameter.

The following combinations of a KeyPath and autoIncrement are possible:

Key path Auto increment Description
Empty False This object store can hold any kind of value, even primitive values like numbers and strings. You must supply a separate key argument whenever you want to add a new value to the object store.
Provided False This object store can only hold JavaScript objects. The objects must have a property with the same name as the key path.
Empty True This object store can hold any kind of value. The key is generated for you automatically, or you can supply a separate key argument if you want to use a specific key.
Provided True This object store can only hold JavaScript objects. Usually a key is generated and the value of the generated key is stored in the object in a property with the same name as the key path. However, if such a property already exists, the value of that property is used as key rather than generating a new key.

dbConnection.createObjectStore("ObjectStoreName"
                                              , { "keyPath": "keyPath"
                                                , "autoIncrement": true }
                                              , true);

removing an object store

When we want to remove an object store, the only thing we need to pass is the name of the object store we want to remove.

dbConnection.deleteObjectStore("ObjectStoreName");

Creating an INDEX

Once we created our object store, we can add indexes to it. These indexes are object stores as well, but the key of these key/value pairs is the key path of the index. This means that in this object store that multiple keys with the same value are allowed. When we want to create an index we need to provide a name and a key path for them. Optionally we can provide a JSON object with a unique and multiplerow field.

Field Description Support
unique A boolean value indicating whether the index allows duplicate values. If this attribute is "true", duplicate values are not allowed. Duplicate values are allowed when this attribute is "false" (the default value). This means when you add an object to an object store where an index with a unique value on "true". You will get an exception when you add an object with a duplicate value in the field of the key path of the index. IE 10
FF
Chrome
multiplerow A boolean value that describes determines the results when multiple rows in the object store match individual key values. When this happens, the resulting object is an array. If this parameter is "true", the resulting array contains a single item; the key of the item contains an array of the matching values. When this parameter is "false" (the default), the result array contains one item for each item that matches the key value. IE 10

store.createIndex("IndexName"
                         , "keyPath"
                         , { unique: false });

If we want to create an index in IE 9 Indexed DB prototype, we need to pass the boolean value for the uniqueness as parameter and not as a JSON object.

store.createIndex("IndexName"
, "keyPath"
, false);

Deleting an index

The last action we can do in the VERSION_CHANGE event is deleting an existing index. We can do this by passing the name of the index we want to delete.

store.deleteIndex("IndexName");