Compound Key Usage for ranges


#1

I can find various answers for this in other languages, but not for Java for some reason.

Let’s say, hypothetically, that I have a bucket containing records that contain Country, State and City (this is a hypothetical, so let’s ignore the wisdom of that for now). My view index is an array of [“country”,“state”,“city”], and I want to be able to get all of my records in a country, in a state within a country, or in a specific city (knowing the country and state).

How exactly should I query for all records in Texas for example?

I have it working by simply picking a high range unicode character, but honestly that just feels like a bit of a hack, and nothing else that I have tried seems to return anything at all.

String lastchar = “\uF8FF”;
JsonArray startkey = JsonArray.from(“USA”,“Texas”);
JsonArray endkey = JsonArray.from(“USA”,“Texas”,lastchar);
ViewQuery q = ViewQuery.from(“MyDoc”, “Myview”).startKey(startkey).endKey(endkey).reduce(false);

Is there a “cleaner” way of doing this?


#2

The high-range unicode char is usually what we recommend in this case, but appended to the second key element (and we usually go with \u0fff IIRC):

JsonArray endKey = JsonArray.from("USA", "Texas" + "\u0fff");

Since you’ve filled the first two elements of the key, the third one is ignored and you get all cities in the Texas state, USA.