Java-通过多个属性过滤JSON对象数组

时间:2019-02-25 11:51:30

标签: java json cloudant

我有一个这样的对象存储在Cloudant中:

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

我想按代码/国家/地区做一个过滤条件,所以输出将只是“对象”列表的一个对象。

有没有办法从Cloudant方面做到这一点?还是要在Java端完成的有效方法?

1 个答案:

答案 0 :(得分:1)

您可以使用Cloudant中的map-reduce视图来实现。尝试以下方法:

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

这会将Objects列表中的所有项目发出,并带有向量值键[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"}}
]}

例如,您只能使用{}通配符标记通过代码查询

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"}}
]}