2

假设我的一些文档具有以下结构:

{  
   "something":{  
      "a":"b"
   },
   "some_other_thing":{  
      "c":"d"
   },
   "what_i_want":{  
      "is_down_here":[  
         {  
            "some":{  
               "not_needed":"object"
            },
            "another":{  
               "also_not_needed":"object"
            },
            "i_look_for":"this_tag",
            "tag_properties":{  
               "this":"that"
            }
         },
         {  
            "but_not":{  
               "down":"here"
            }
         }
      ]
   }
}

是否有一个 Mango JSON 选择器可以在"i_look_for"具有值时成功选择"this_tag"?它在一个数组中(我知道它在数组中的位置)。我也对过滤结果感兴趣,所以我只得到 "tag_properties"结果。

我已经尝试了很多东西,包括 $elemMatch,但大部分都返回“无效的 json”。

这甚至是 Mango 的用例还是我应该坚持观点?

4

2 回答 2

9

使用 Cloudant Query (Mango) 选择器语句,您仍然需要在查询之前定义适当的索引。考虑到这一点,这是你的答案:

json类型的CQ索引

{
  "index": {
    "fields": [
      "what_i_want.is_down_here.0"
    ]
  },
  "type": "json"
}

针对 json 类型索引的选择器

{
  "selector": {
    "what_i_want.is_down_here.0": {
      "i_look_for": "this_tag"
    },
    "what_i_want.is_down_here.0.tag_properties": {
      "$exists": true
    }
  },
  "fields": [
    "_id",
    "what_i_want.is_down_here.0.tag_properties"
  ]
}

上面的解决方案假设您始终知道/可以保证您想要的字段在is_down_here数组的第 0 个元素内。

还有另一种方法可以用不同的 CQ 索引类型来回答这个问题。本文解释了差异,并提供了有用的示例来显示查询数组。现在您对不同的索引类型有了更多的了解,下面是您如何使用 Lucene 搜索/“文本”类型的 CQ 索引来回答您的问题:

文本型CQ索引

{
  "index": {
    "fields": [
      {"name": "what_i_want.is_down_here.[]", "type": "string"}
    ]
  },
  "type": "text"
}

针对文本类型索引的选择器

{
  "selector": {
    "what_i_want.is_down_here": {
      "$and": [
        {"$elemMatch": {"i_look_for": "this_tag"}},
        {"$elemMatch": {"tag_properties": {"$exists": true}}}
      ]
    }
  },
  "fields": [
    "_id",
    "what_i_want.is_down_here"
  ]
}

阅读文章,您将了解到每种方法都有其权衡:json 类型的索引更小且灵活性较差(只能索引特定元素);text-type 更大但更灵活(可以索引所有数组元素)。从这个示例中,您还可以看到投影值也带有一些权衡(投影特定值与整个数组)。

这些线程中的更多示例:

于 2017-05-01T18:13:07.020 回答
2

如果我正确理解您的问题,根据文档有两种支持的方法:

{
    "what_i_want": {
        "i_look_for": "this_tag"
    }
}

应该等同于缩写形式:

{
    "what_i_want.i_look_for": "this_tag"
}
于 2017-05-01T08:01:26.730 回答