2015-05-05 142 views
1

我的文檔結構看起來像這樣:彈性搜索聚合組值

{ 
"title" : "A title", 
"ExtraFields": [ 
    { 
     "value": "print", 
     "fieldID": "5535627631efa0843554b0ea" 
    } 
    , 
    { 
     "value": "POLYE", 
     "fieldID": "5535627631efa0843554b0ec" 
    } 
    , 
    { 
     "value": "30", 
     "fieldID": "5535627631efa0843554b0ed" 
    } 
    , 
    { 
     "value": "0", 
     "fieldID": "5535627631efa0843554b0ee" 
    } 
    , 
    { 
     "value": "0", 
     "fieldID": "5535627731efa0843554b0ef" 
    } 
    , 
    { 
     "value": "0.42", 
     "fieldID": "5535627831efa0843554b0f0" 
    } 
    , 
    { 
     "value": "40", 
     "fieldID": "5535627831efa0843554b0f1" 
    } 
    , 
    { 
     "value": "30", 
     "fieldID": "5535627831efa0843554b0f2" 
    } 
    , 
    { 
     "value": "18", 
     "fieldID": "5535627831efa0843554b0f3" 
    } 
    , 
    { 
     "value": "24", 
     "fieldID": "5535627831efa0843554b0f4" 
    } 
] 
} 

理想的輸出是(最好的情況下):

[ 
{ 
    "field" : "5535627831efa0843554b0f4", 
    "values" : [ 
     { 
      "label" : "24", 
      "count" : 2 
     }, 
     { 
      "label" : "18", 
      "count" : 5 
     } 
    ] 
}, 
{ 
    "field" : "5535627831efa0843554b0f3", 
    "values" : [ 
     { 
      "label" : "cott", 
      "count" : 20 
     }, 
     { 
      "label" : "polye", 
      "count" : 12 
     } 
    ] 
} 
] 

但我也可以做一個更簡單的一個喜歡(這是我如何得到它在MongoDB現在):

[ 
{ 
    "field" : "5535627831efa0843554b0f4", 
    "value" : "24", 
    "count" : 2 
}, 
{ 
    "field" : "5535627831efa0843554b0f4", 
    "value" : "18", 
    "count" : 5 
}, 
{ 
    "field" : "5535627831efa0843554b0f3", 
    "value" : "cott", 
    "count" : 20 
}, 
{ 
    "field" : "5535627831efa0843554b0f3", 
    "value" : "polye", 
    "count" : 12 
} 
] 

聚合查詢將如何看起來像?這個結構有什麼特殊的映射?

回答

1

爲了得到你想要的,你需要nested映射爲ExtraFields子結構。您的文檔映射是這樣的(doctype是我選擇來命名您的文檔類型的術語,但它可以是你現在有什麼):

PUT /test/_mapping/doctype 
{ 
    "doctype": { 
    "properties": { 
     "title": { 
     "type": "string" 
     }, 
     "ExtraFields": { 
     "type": "nested", 
     "properties": { 
      "value": { 
      "type": "string", 
      "index": "not_analyzed" 
      }, 
      "fieldID": { 
      "type": "string", 
      "index": "not_analyzed" 
      } 
     } 
     } 
    } 
    } 
} 

然後,你可以索引文檔

PUT /test/doctype/123 
{ 
    "title" : "A title", 
    "ExtraFields": [ 
     ... 
    ] 
} 

併發送以下聚集查詢:

POST /test/doctype/_search 
{ 
    "size": 0, 
    "aggs": { 
    "fields": { 
     "nested": { 
     "path": "ExtraFields" 
     }, 
     "aggs": { 
     "fields": { 
      "terms": { 
      "field": "ExtraFields.fieldID" 
      }, 
      "aggs": { 
      "values": { 
       "terms": { 
       "field": "ExtraFields.value" 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
} 

這將產生你在最好的情況下突顯的結果,雖然在respons的JSON字段名e被命名有點不同,但我想沒關係。

試一試,讓我們知道。

+0

謝謝,我會設置它並讓你知道 – mbouclas

+0

它似乎有點工作。我說的是因爲聚合不包含所有的結果。看起來它只能持有10每場或類似 – mbouclas

+0

好吧,明白了,每個聚合有一個大小參數。實際上意義...這工作得很好,非常感謝 – mbouclas