用于深层嵌套JSON的Cloudant/Mango选择器

zlr*_*zlr 0 json cloudant couchdb-mango couchdb-2.0

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

{  
   "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"
            }
         }
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试了很多东西,包括$ elemMatch,但一切都回归"无效的json".

这甚至是芒果的用例还是应该坚持观点?

bro*_*bes 7

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

json型CQ指数

{
  "index": {
    "fields": [
      "what_i_want.is_down_here.0"
    ]
  },
  "type": "json"
}
Run Code Online (Sandbox Code Playgroud)

针对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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

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

文本型CQ索引

{
  "index": {
    "fields": [
      {"name": "what_i_want.is_down_here.[]", "type": "string"}
    ]
  },
  "type": "text"
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

这些主题中的更多示例: