Cloudant选择器查询

11
我想使用Cloudant数据库的选择器进行查询,例如下面的示例:用户想要贷款金额超过某个数额的贷款记录,如何在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"
          }
        }
      ]
    }
2个回答

13

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

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

那么以下查询选择器应该可以找到所有贷款金额大于1000的文档:

Then the following query selector should work to find e.g. all documents with a loanamount > 1000:
"loansBorrowed": { "$elemMatch": { "loanamount": { "$gt": 1000 } } }

我不确定你是否可以诱使Cloudant Query仅在数组中索引嵌套字段,因此,如果您不需要“索引所有内容”方法的灵活性,则最好创建一个Cloudant Search索引,该索引仅索引您所需的特定字段。


10

虽然 Will 的答案可行,但我想让您知道 Cloudant 查询处理数组时有其他索引选项。这篇博客详细介绍了各种权衡(https://cloudant.com/blog/mango-json-vs-text-indexes/),但长话短说,我认为这可能是最好的索引选项:

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

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

因此,相应的Cloudant查询"selector":语句将是:

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

请注意,您不必将"fields":包括在您的"selector":语句中,但我在这里这样做只是为了仅显示JSON的某些部分。如果您从"selector":语句中省略它,则会返回整个文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接