Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the results of an indexedDB query

I want to sort results obtained from indexedDB.
Each record has structure {id, text, date} where 'id' is the keyPath.

I want to sort the results by date.

My current code is as below:

  var trans = db.transaction(['msgs'], IDBTransaction.READ);
  var store = trans.objectStore('msgs');

  // Get everything in the store;
  var keyRange = IDBKeyRange.lowerBound("");
  var cursorRequest = store.openCursor(keyRange);

  cursorRequest.onsuccess = function(e) {
    var result = e.target.result;
    if(!!result == false){
        return;
    }
    console.log(result.value);
    result.continue();
  };
like image 410
vivek.m Avatar asked Jul 15 '12 12:07

vivek.m


People also ask

Is IndexedDB fast?

Not slow like a database on a cheap server, even slower! Inserting a few hundred documents can take up several seconds. Time which can be critical for a fast page load.

Is IndexedDB persistent?

Even though IndexedDB is a fully functional client-side database for the web, it is not a persistent storage by default.

Is IndexedDB relational database?

IndexedDB is not a relational database with tables representing collections of rows and columns. This important and fundamental difference affects the way you design and build your applications.


2 Answers

Actually you have to index the date field in the msgs objectStore and open an index cursor on the objectStore.

var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev 

This will get the sorted result. That is how indexes are supposed to be used.

like image 196
Kyaw Tun Avatar answered Sep 17 '22 11:09

Kyaw Tun


Here's the more efficient way suggested by Josh.

Supposing you created an index on "date":

// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated:
var trans = db.transaction(['msgs'], "readonly");
var store = trans.objectStore('msgs');
var index = store.index('date');

// Get everything in the store:
var cursorRequest = index.openCursor();
// It's the same as:
// var cursorRequest = index.openCursor(null, "next");
// Or, if you want a "descendent ordering":
// var cursorRequest = index.openCursor(null, "prev");
// Note that there's no need to define a key range if you want all the objects

var res = new Array();

cursorRequest.onsuccess = function(e) {

    var cursor = e.target.result;
    if (cursor) {
        res.push(cursor.value);
        cursor.continue();
    }
    else {
        //print res etc....
    }
};

More on cursor direction here: http://www.w3.org/TR/IndexedDB/#cursor-concept

IDBIndex API is here: http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex

like image 28
Andrei Cojocaru Avatar answered Sep 20 '22 11:09

Andrei Cojocaru