2017-04-30 48 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