Cloudant Selector Query

后端 未结 2 1224
耶瑟儿~
耶瑟儿~ 2020-12-03 11:36

I would like to query using cloudant db using selector, for example that is shown below: user would like to have loanborrowed whose amount exceeds a number, how to access th

相关标签:
2条回答
  • 2020-12-03 12:17

    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.

    0 讨论(0)
  • 2020-12-03 12:25

    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.

    0 讨论(0)
提交回复
热议问题