Cloudant Selector Query Cloudant Selector Query json json

Cloudant Selector Query


If you use the default Cloudant Query index (type text, index everything):

{   "index": {},   "type": "text"}

Then the following query selector should work to find e.g. all documents with a loanamount > 1000:

"loansBorrowed": { "$elemMatch": { "loanamount": { "$gt": 1000 } } }

I'm not sure that you can coax Cloudant Query to only index nested fields within an array so, if you don't need the flexibility of the "index everything" approach, you're probably better off creating a Cloudant Search index which indexes just the specific fields you need.


While Will's answer works, I wanted to let you know that you have other indexing options with Cloudant Query for handling arrays. This blog has the details on various tradeoffs (https://cloudant.com/blog/mango-json-vs-text-indexes/), but long story short, I think this might be the best indexing option for you:

{  "index": {    "fields": [      {"name": "loansBorrowed.[].loanamount", "type": "number"}    ]  },  "type": "text"}

Unlike Will's index-everything approach, here you're only indexing a specific field, and if the field contains an array, you're also indexing every element in the array. Particularly for "type": "text" indexes on large datasets, specifying a field to index will save you index-build time and storage space. Note that text indexes that specify a field must use the following form in the "fields": field: {"name": "fieldname", "type": "boolean,number, or string"}

So then the corresponding Cloudant Query "selector": statement would be this:

{  "selector": {    "loansBorrowed": {"$elemMatch": {"loanamount": {"$gt": 4000}}}  },  "fields": [    "_id",    "userprofile.name",    "loansBorrowed"  ]}

Also note that you don't have to include "fields": as part of your "selector": statement, but I did here to only project certain parts of the JSON. If you omit it from your "selector": statement, the entire document will be returned.