Search code examples
javajsoncloudant

Java - Filtering an array of JSON objects by multiple properties


I have an object stored in Cloudant like this :

{
  "attr1": "value",
  "Objects": [{
      "code": "v1",
      "allowNull": "true",
      "country": "BE"
    },
    {
      "code": "v2",
      "allowNull": "false",
      "country": "EG"
    }
  ]
}

And I want to do a filter criteria by code/country, so the output would be only one object of Objects list.

Is there a way to do that from Cloudant side? Or an efficient way to be done at Java side ?


Solution

  • You can achieve this with a map-reduce view in Cloudant. Try something along the lines of this:

    function(doc) {
        if (doc && doc.Objects) {
            doc.Objects.forEach(function(obj) {
                emit([obj.code, obj.country], obj);
            });
        }
    }
    

    This emits all items in the Objects list into the index, with a vector-valued key [code, country].

    curl -s -XPOST -H "content-type:application/json" 'https://skruger.cloudant.com/demo/_design/query/_view/by_code_country?reduce=false' -d '{ "keys": [["v1","BE"]] }'
    {"total_rows":2,"offset":0,"rows":[
        {"id":"1c593a931bcd7f0052ed8f9184810fd9","key":["v1","BE"],"value": 
            {"code":"v1","allowNull":"true","country":"BE"}}
    ]}
    

    You can query by code only, using the {} wildcard marker, e.g.

    curl -g 'https://skruger.cloudant.com/demo/_design/query/_view/by_code_country?reduce=false&startkey=["v1"]&endkey=["v1",{}]'
    {"total_rows":2,"offset":0,"rows":[
        {"id":"1c593a931bcd7f0052ed8f9184810fd9","key":["v1","BE"],"value": 
        {"code":"v1","allowNull":"true","country":"BE"}}
    ]}