24

I have this in my view function:

emit([doc.address.country,doc.address.state, doc.address.city], doc);

When I query the search, I need to have all 3 elements of the array filled in, for example:

?key=["US","NY","New York"]

that will produce my records, but lets say for example, I just want to return everything in the US for example:

?key=["US"]   

or in the US and State...

?key=["US","NY"] 

OR... lets say perhaps I want just all records from NY... (i know the below doesn't work)

?key=["","NY"]

I don't really get how to search if you want to leave one of the elements of the array empty?

Matt
  • 1,811
  • 1
  • 19
  • 30

1 Answers1

45

First:

key=["US"] will not work on an Array Key ["US","NY"], cause you're looking for a key that is EXACT ["US"]. Instead, you have to use

startkey=["US"]&endkey=["US",{}] 

then those Keys are in the resultset:

["DE","Bavaria","Munich"]   <---- NO ! "DE" is out of Range of startkey
["US","FL","Miami"]         <---- YES, starts with "US"
["US","NY","New York"]      <---- YES, starts with "US"
["VE","XX","Vencuela City"] <---- NO ! "VE" is out of Range of endkey

Also Working:

startkey=["US","FL"]&endkey=["US","FL",{}] 

result:

["DE","Bavaria","Munich"]   <---- NO ! "DE" is out of Range of startkey
["US","FL","Miami"]         <---- YES, starts with "US","FL"
["US","NY","New York"]      <---- NO, "US","NY" is out of Range of endkey
["VE","XX","Vencuela City"] <---- NO ! "VE" is out of Range of endkey

Second: You cannot have blanks on left side.. so you have to write some more emits: ( you do not have to emit the second and third array-item, if you do not need to query it)

view "byStateCityCountry":

emit([doc.address.state, doc.address.city,address.country], doc);

view "byCityStateCountry":

emit([address.city,doc.address.state, doc.address.country], doc);

of just put a flag in the first place to determine the type of query, so you can do all in one View:

emit([1,address.country,doc.address.state, doc.address.city], doc);
emit([2,doc.address.state, doc.address.city,address.country], doc);
emit([3,address.city,doc.address.state, doc.address.country], doc);

Usage:

?startkey=[1,"US"]&endkey=[1,"US",{}]
?startkey=[2,"FL"]&endkey=[2,"FL",{}]
?startkey=[3,"Miami"]&endkey=[3,"Miami",{}]
okurow
  • 969
  • 10
  • 6
  • Note: "You cannot have blanks on left side..." - I believe the opposite is true if you have descending = true – Matt Jan 26 '14 at 16:49
  • 2
    I know this is old, but it should also be noted that if your key array has a lot of elements it gets more complex. assuming the following data in your view with these keys: `startkey == [a, 11] and endkey == [c, 11]:` `[a, 10], [a, 11] <-- startkey, [a, 12], [b, 10], [b, 11], [b, 12], [c, 10], [c, 11] <-- endkey, [c, 12]` (Everything in-between the startkey and end key will be returned. ). – AdriVelaz Apr 14 '14 at 18:50