2017-04-30 42 views
0

比方说,我的一些文件具有以下结构:Cloudant /芒果选择了深嵌套JSONs

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

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

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

即使是芒果的用例还是应该坚持观点?

回答

4

随着Cloudant查询(芒果)选择器语句,你仍然需要在查询之前定义一个适当的索引。考虑到这一点,这里是你的答案:

JSON型CQ指数对JSON型指数

{ 
    "index": { 
    "fields": [ 
     "what_i_want.is_down_here.0" 
    ] 
    }, 
    "type": "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索引类型来回答这个问题。 This article explains the differences,并有示例查询数组的有用示例。现在你知道一点关于不同的索引类型,这里是你会如何回答你的问题与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型指数是更小,更灵活的(只能索引具体要素);文本类型更大但更灵活(可以索引所有数组元素)。从这个例子中,你也可以看到投影值也带有一些折衷(投影特定值与整个阵列)。

更多的例子在这些线程:

2

如果我正确理解你的问题,也有根据docs做这两种支持方式:

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

应相当于缩写形式:

{ 
    "what_i_want.i_look_for": "this_tag" 
} 
+0

这将返回0文档:据我所知,是因为'i_look_for'不是what_i_want'的'直接财产,但阵列的成员'is_down_here' – zlr

+2

你尝试过'what_i_want.0.i_look_for'吗? – Flimzy

+2

非常酷,它的作品。我确实尝试了这个数组索引表示法,但失败了,所以谢谢!接下来的问题是我怎样才能避免位置论证,但有一个新的答案,所以我应该全部设置 – zlr