Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying an IndexedDB compound index with a shorter array

IndexedDB allows you to make indexes on multiple properties. Like if you have objects like {a: 0, b: 0} you can make an index on a and b.

The behavior of compound indexes is pretty weird, but apparently it is supposed to be possible to query with an array that is shorter than the compound index. So in my example, I should be able to query on something like [0] and get results for a==0.

But I can't seem to get that to work. Here's an example which you can run on JS Bin:

var db;

request = indexedDB.open("test", 1);
request.onerror = function (event) { console.log(event); };

request.onupgradeneeded = function (event) {
  var db = event.target.result;
  db.onerror = function (event) { console.log(event); };

  var store = db.createObjectStore("store", {keyPath: "id", autoIncrement: true});
  store.createIndex("a, b", ["a", "b"], {unique: true});

  store.add({a: 0, b: 0});
  store.add({a: 0, b: 1});
  store.add({a: 1, b: 0});
  store.add({a: 1, b: 1});
};

request.onsuccess = function (event) {
  db = request.result;
  db.onerror = function (event) { console.log(event); };

  console.log("Only [0, 0]");
  db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.only([0, 0])).onsuccess = function (event) {
    var cursor = event.target.result;
    if (cursor) {
      console.log(cursor.value);
      cursor.continue();
    } else {
      console.log("Any [0, x]");
      db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.only([0])).onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          console.log(cursor.value);
          cursor.continue();
        }
      };
    }
  };
};

Here is the JS Bin link again.

The output I see is:

Only [0, 0]
Object {a: 0, b: 0, id: 1}
Any [0, x]

But I was hoping to see:

Only [0, 0]
Object {a: 0, b: 0, id: 1}
Any [0, x]
Object {a: 0, b: 0, id: 1}
Object {a: 0, b: 1, id: 2}

Where am I going wrong?

like image 713
dumbmatter Avatar asked Oct 19 '25 06:10

dumbmatter


1 Answers

A slightly more general version of Kyaw Tun's answer: if all keys are known to be arrays with two non-array elements, and you want the ones matching [x, <any>], use IDBKeyRange.bound([x], [x, []]).

like image 95
Ivan Avatar answered Oct 20 '25 19:10

Ivan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!