2016-01-05 132 views
1

說我的elasticsearch索引中的每個文檔都是一個博客文章,它只包含兩個字段,標題和標籤。 標題字段只是一個字符串,而標籤是一個多值字段。如何在elasticsearch中的多值字段上進行桶聚合

如果我有三個文件是這樣的:

title  tags 
"blog1" [A,B,C] 
"blog2" [A,B] 
"blog3" [B,C] 

我想通過所有可能的標籤的唯一值鬥,但我怎樣才能得到結果如下圖所示,它包含在水桶三個項目。還是有任何有效的替代品?

{A: ["blog1", "blog2"]} 
{B: ["blog1", "blog2", "blog3"]} 
{C: ["blog1", "blog3"]} 

這將是很好,如果有人可以在elasticsearch python API中提供答案。

回答

2

您可以簡單地在tags字段和另一個嵌套的top_hits子聚合上使用terms聚合。通過以下查詢,您將獲得預期的結果。

{ 
    "size": 0, 
    "aggs": { 
     "tags": { 
      "terms": { 
       "field": "tags" 
      }, 
      "aggs": { 
       "top_titles": { 
        "top_hits": { 
         "_source": ["title"] 
        } 
       } 
      } 
     } 
    } 
} 

與Python使用這個很簡單:

from elasticsearch import Elasticsearch 
client = Elasticsearch() 

response = client.search(
    index="my-index", 
    body= { 
    "size": 0, 
    "aggs": { 
     "tags": { 
      "terms": { 
       "field": "tags" 
      }, 
      "aggs": { 
       "top_titles": { 
        "top_hits": { 
         "_source": ["title"] 
        } 
       } 
      } 
     } 
    } 
} 
) 

# parse the tags 
for tag in response['aggregations']['tags']['buckets']: 
    tag = tag['key'] # => A, B, C 
    # parse the titles for the tag 
    for hit in tag['top_titles']['hits']['hits']: 
     title = hit['_source']['title'] # => blog1, blog2, ... 
相關問題