Cloudant选择器查询

vin*_*San 10 json cloudant

我想使用cloudant db使用选择器进行查询,例如如下所示:用户希望借入其数量超过数字的借阅,如何在cloudant选择器中访问数组以查找特定记录

{
       "_id": "65c5e4c917781f7365f4d814f6e1665f",
      "_rev": "2-73615006996721fef9507c2d1dacd184",
      "userprofile": {


     "name": "tom",
        "age": 30,
        "employer": "Microsoft"

      },
      "loansBorrowed": [
        {
          "loanamount": 5000,
          "loandate": "01/01/2001",
          "repaymentdate": "01/01/2001",
          "rateofinterest": 5.6,
          "activeStatus": true,
          "penalty": {
            "penalty-amount": 500,
            "reasonforPenalty": "Exceeded the date by 10 days"
          }
        },
        {
          "loanamount": 3000,
          "loandate": "01/01/2001",
          "repaymentdate": "01/01/2001",
          "rateofinterest": 5.6,
          "activeStatus": true,
          "penalty": {
            "penalty-amount": 400,
            "reasonforPenalty": "Exceeded the date by 10 days"
          }
        },
        {
          "loanamount": 2000,
          "loandate": "01/01/2001",
          "repaymentdate": "01/01/2001",
          "rateofinterest": 5.6,
          "activeStatus": true,
          "penalty": {
            "penalty-amount": 500,
            "reasonforPenalty": "Exceeded the date by 10 days"
          }
        }
      ]
    }
Run Code Online (Sandbox Code Playgroud)

Wil*_*ley 12

如果您使用默认的Cloudant查询索引(键入文本,索引所有内容):

{
   "index": {},
   "type": "text"
}
Run Code Online (Sandbox Code Playgroud)

然后,以下查询选择器应该可以查找例如贷款额> 1000的所有文档:

"loansBorrowed": { "$elemMatch": { "loanamount": { "$gt": 1000 } } }
Run Code Online (Sandbox Code Playgroud)

我不确定你是否可以哄骗Cloudant Query来只索引数组中的嵌套字段,这样,如果你不需要"索引所有"方法的灵活性,你可能最好创建一个Cloudant Search索引来编制索引只是您需要的特定字段.


bro*_*bes 10

虽然Will的答案有效,但我想告诉您,您还有其他使用Cloudant Query的索引选项来处理数组.此博客上的各种权衡(详细https://cloudant.com/blog/mango-json-vs-text-indexes/),但长话短说,我认为这可能是您的最佳选择索引:

{
  "index": {
    "fields": [
      {"name": "loansBorrowed.[].loanamount", "type": "number"}
    ]
  },
  "type": "text"
}
Run Code Online (Sandbox Code Playgroud)

与Will的索引 - 所有方法不同,这里只是索引特定字段,如果字段包含数组,那么您还要索引数组中的每个元素.特别是对于"type": "text"大型数据集的索引,指定要索引的字段将为您节省索引构建时间和存储空间.请注意,指定字段的文本索引必须在字段中使用以下表单"fields"::{"name": "fieldname", "type": "boolean,number, or string"}

那么相应的Cloudant Query "selector":语句将是这样的:

{
  "selector": {
    "loansBorrowed": {"$elemMatch": {"loanamount": {"$gt": 4000}}}
  },
  "fields": [
    "_id",
    "userprofile.name",
    "loansBorrowed"
  ]
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您不必"fields":"selector":声明作为声明的一部分包含在内,但我在此处仅对JSON的某些部分进行了投影.如果从"selector":语句中省略它,将返回整个文档.