Search code examples
javascriptclient-sideindexeddbclient-side-data

IDBKeyRange querying by key, where key is String


The key of an object stored in IndexedDB is an Array of the format:

[int, String]

e.g. [1, "Foo"], [9, "Bar"]

How do I query the database using the string part of the key? For example I want to fetch all records with key [:any, "Some key"].

Looks like IDBKeyRange is used for integer ranges, but I couldn't find a method to build arbitrary queries on keys.


Solution

  • When you create your index, ensure you set multiEntry to true, ie:

    objectStore.createIndex("tags","tags", {unique:false,multiEntry:true});
    

    You can then get a range using the only operator - assume 'tag' is what you are looking for:

    var rangeTest = IDBKeyRange.only(tag);
    

    And that should do it for you. I've got a full blog entry on this here: http://www.raymondcamden.com/index.cfm/2012/8/10/Searching-for-array-elements-in-IndexedDB