Search code examples
javascriptcursorindexeddbcursor-position

Cursors order in query using composite index


I wonder how records are arranged in queries that use composite indices.

Let's consider this example.

let objetStore = db.createObjectStore('article',{keyPath : 'id'});
objectStore.createIndex('userid-date',['userid','date_created']);

db.transaction('article').objectStore('article').index('userid-date').openCursor(IDBKeyRange.bound([1,new Date(new Date() - 365*86400*1000)],[100,new Date()])).onsuccess = function(e){

};

Are the records in the above query ordered by userid or date_created? Why?


Solution

  • See In IndexedDB, is there a way to make a sorted compound query?. Basically, the index is sorted first by user id and then by date created, because that is the order of the properties in the array you passed to the createIndex method.

    The sorting function is indexedDB.cmp. This is a customized sorting function specific to indexedDB. You need to read a large part of the indexedDB specification to understand it. It is partially summarized in the linked question.