HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 233 posts at DZone. You can read more from them at their website. View Full User Profile

Adding "Filter as you type" Support to IndexedDB

05.22.2012
| 2350 views |
  • submit to reddit

One truly disappointing aspect of IndexedDB is that there is no (simple) support for search across your data. It is very much based on the idea of knowing your keys and fetching data based on those keys. You can easily retrieve the "Ray" user object, but you can't search for user objects that have an age within a certain range and a skill property of so and so. That's not to imply you can't do some sorting and filtering though.

IndexedDB supports the idea of key range objects. As you can probably guess, these allow you return objects based on a range of values that match with a particular index. Remember that IndexedDB objects can have any number of properties, but you have to specify which are indexed. And now you know a good reason why - it gives you a chance to filter later on.

Ranges can go in either direction and can be inclusive or exclusive. By that I mean, you can say "Anything object with a name 'above' and including Barry" or "Anything object with a name 'below' Zelda but not including that name." You can also combine both and get a single object too.

For my use-case, I wanted to use a range filter so that I could support 'filter as you type'. My data consists of notes that include a title, body, and created property. I'm not going to go through the steps of setting that up as my previous blog entries (linked at the bottom) went over most of the detail there. Instead, let's focus on how I built in the 'filter as you type' metaphor.

To begin with, I had a function that handled "get all" and displaying the data. It worked by opening a cursor and looping while data existed. Here's how that version looked:

 function displayNotes() {
        var transaction = db.transaction(["note"], IDBTransaction.READ);
        var content="<ul>";
        transaction.oncomplete = function(event) {
            console.log("All done!");
            $("#noteList").html(content);
        };
        transaction.onerror = function(event) {
          // Don't forget to handle errors!
          console.dir(event);
        };
        var objectStore = transaction.objectStore("note");
        objectStore.openCursor().onsuccess = function(event) {
          var cursor = event.target.result;
          if (cursor) {
            content += "<li data-key=\""+cursor.key+"\"><span class=\"label\">"+cursor.value.title+"</span>";
            content += " <a class=\"delete\">[Delete]</a>";
            content +="</li>";
            cursor.continue();
          }
          else {
            content += "</ul>";
            console.log("Done with cursor");
          }
        };
    }
view raw gistfile1.js This Gist brought to you by GitHub.

In order to support a bound range, you have to change how you open your object store (remember, think of this like a database table). When we just get everything, we run openCursor on the objectStore (line 18 above). When we want a bound list of data, we get an index first (this is the property we said we wanted to be able to filter on), create the range, and then open a cursor on that. So with a small amount of work, we can update our displayNotes function to take an optional filter. (Note that I also switched to a table display. The change in HTML isn't terribly important here so I won't cover it.)

function displayNotes(filter) {

        var transaction = db.transaction(["note"], IDBTransaction.READ);
        var content="<table class='table table-bordered'><thead><tr><th>Title</th><th>Created</th><th> </td></thead><tbody>";

        transaction.oncomplete = function(event) {
            $("#noteList").html(content);
        };

        transaction.onerror = function(event) {
          // Don't forget to handle errors!
          console.dir(event);
        };

        var handleResult = function(event) {
          var cursor = event.target.result;
          if (cursor) {
            content += "<tr data-key=\""+cursor.key+"\"><td class=\"notetitle\">"+cursor.value.title+"</td>";
            content += "<td>"+dtFormat(cursor.value.created)+"</td><td><a class=\"btn btn-danger delete\">Delete</a></td>";
            content +="</tr>";
            cursor.continue();
          }
          else {
            content += "</tbody></table>";
            console.log("Done with cursor");
          }
        };

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

        if(filter) {
            console.log("need to make a range on "+filter);
            //Credit: http://stackoverflow.com/a/8961462/52160
            var range = IDBKeyRange.bound(filter, filter + "z");
            var index = objectStore.index("title");
            index.openCursor(range).onsuccess = handleResult;
        } else {
            console.log("Not making a range");
            objectStore.openCursor().onsuccess = handleResult;
        }
        
            
    }

Focus on lines 31 to 40. You can see the different ways to open the cursor. Note specifically we do our binding based on an input string, like "ra" and append "z" to give an end to the range. So typing in "ra" means we want all notes with a title from "raa" to "raz".

Outside of that - the code is identical. I moved the success portion into a new inner function (handleResult), but it works the same no matter how I get the cursor itself.

You can demo this yourself by hitting the demo button below, but as before, this is Firefox only due to - what I believe - is a bad implementation in Chrome. (I think it could be made to work in Chrome, but as I'm building these examples to help me learn more about IndexedDB, I'm fine supporting the most compatible browser.)

You can find the complete source by .... viewing source. ;)

Published at DZone with permission of Raymond Camden, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)