2

I've got a mock up indexedDB holds items like:

{
 id:1002, 
 name:"Frank", 
 company: "dg",
 age:30 
}

And I've created the index ['name','age','company'] , just want to get the result I need like websql do.

getMultipleDataByRange function defined to get items, I set ['0',24,'ef'] as lowerBound and ['z',24,'ef'] as upperBound, I thought it should show me the result match the items who's 24 years old plus whose company is "ef". But the result shows that all the items meet the range I set. How can I set the range to get the correct result.

Code can also be checked by JSBIN link I generated:

http://jsbin.com/sinuxa/edit?js,console

Jin
  • 134
  • 8

1 Answers1

4

It'll work if you change the order of your index so that the part that varies (name) is at the end. If you want to know why, see In IndexedDB, is there a way to make a sorted compound query? for an explanation of how compound indexes work in IndexedDB.

Community
  • 1
  • 1
dumbmatter
  • 9,351
  • 7
  • 41
  • 80
  • Thanks, I've see the Q&A you mentioned before. I just wondered if there's a way to get the final result without changing the order of my index for avoiding create more different ordered index to meet different condition. – Jin May 19 '16 at 01:28
  • What's more, I also check the "N-dimensional way" through this link (https://gist.github.com/inexorabletash/704e9688f99ac12dd336), but I think it won't work if strings mixed in because that it's hard to set the range of strings. Also, I've checked some ugly ways like saving the result for each condition in different Arrays, and then get the intersection. That's not elegant and inefficiency when the db get bigger. – Jin May 19 '16 at 01:36
  • That gist (I'm the author) should work for your case. Agreed that setting string ranges is subtle. For "any string" you can use '' to [] (empty string is first, array is higher than any string. For string prefixes you can use e.g. 'a' to 'a\uFFFF' for any string beginning with a (unless \uFFFF is valid, then you need to use the successor trick from https://gist.github.com/inexorabletash/5462871) – Joshua Bell May 19 '16 at 16:44
  • Would the gist sample be easier with an API where you pass in an array of key ranges (or null), e.g. in your case: [null, IDBKeyRange.only(24), IDBKeyRange.only('ef')] ? – Joshua Bell May 19 '16 at 16:46
  • It would be a bit easier, at least I'd love to see it. – Josh May 25 '16 at 15:58