天天看點

ElasticSearch5.X添加度量聚合(二)

添加度量名額編輯

前面的例子(http://blog.csdn.net/wwd0501/article/details/78501842,測試資料跟上篇一樣)告訴我們每個桶裡面的文檔數量,這很有用。 但通常,我們的應用需要提供更複雜的文檔度量。 例如,每種顔色汽車的平均價格是多少?

為了擷取更多資訊,我們需要告訴 Elasticsearch 使用哪個字段,計算何種度量。 這需要将度量 嵌套 在桶内, 度量會基于桶内的文檔計算統計結果。

讓我們繼續為汽車的例子加入 

average

 平均度量:

GET /cars/transactions/_search
{
   "size" : 0,
   "aggs": {
      "colors": {
         "terms": {
            "field": "color"
         },
         "aggs": { 
        
ElasticSearch5.X添加度量聚合(二)
"avg_price": {
ElasticSearch5.X添加度量聚合(二)
"avg": { "field": "price"
ElasticSearch5.X添加度量聚合(二)
} } } } } }

拷貝為 CURL 在 SENSE 中檢視  

ElasticSearch5.X添加度量聚合(二)
為度量新增 

aggs

 層。
ElasticSearch5.X添加度量聚合(二)
為度量指定名字: 

avg_price

 。
ElasticSearch5.X添加度量聚合(二)
最後,為 

price

 字段定義 

avg

 度量。

正如所見,我們用前面的例子加入了新的 

aggs

 層。這個新的聚合層讓我們可以将 

avg

 度量嵌套置于 

terms

 桶内。實際上,這就為每個顔色生成了平均價格。

正如 

顔色

 的例子,我們需要給度量起一個名字( 

avg_price

 )這樣可以稍後根據名字擷取它的值。最後,我們指定度量本身( 

avg

 )以及我們想要計算平均值的字段( 

price

 ):

{
...
   "aggregations": {
      "colors": {
         "buckets": [
            {
               "key": "red",
               "doc_count": 4,
               "avg_price": { 
        
ElasticSearch5.X添加度量聚合(二)
"value": 32500 } }, { "key": "blue", "doc_count": 2, "avg_price": { "value": 20000 } }, { "key": "green", "doc_count": 2, "avg_price": { "value": 21000 } } ] } } ... }
ElasticSearch5.X添加度量聚合(二)
響應中的新字段 

avg_price

 。

盡管響應隻發生很小改變,實際上我們獲得的資料是增長了。之前,我們知道有四輛紅色的車,現在,紅色車的平均價格是 $32,500 美元。這個資訊可以直接顯示在報表或者圖形中。

java代碼實作:

/**
      * Description:桶聚合查詢中添加度量名額
      * 例:計算每種顔色汽車的平均價格是多少
      * 
      * @author wangweidong
      * CreateTime: 2017年11月9日 下午3:47:54
     */
    @Test
    public void bucketsMetricsAggregation() {
    	String index = "cars";
    	String type = "transactions";
    	SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type);
    	
        TermsAggregationBuilder colorsField = AggregationBuilders.terms("popular_colors").field("color.keyword");
        AvgAggregationBuilder avgPriceField = AggregationBuilders.avg("avg_price").field("price");
        colorsField.subAggregation(avgPriceField);
        
        searchRequestBuilder.addAggregation(colorsField);
        searchRequestBuilder.setSize(0);
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        
        System.out.println(searchResponse.toString());
        
        Terms genders = searchResponse.getAggregations().get("popular_colors");
	    for (Terms.Bucket entry : genders.getBuckets()) {
	    	Object key = entry.getKey();      // Term
	        Long count = entry.getDocCount(); // Doc count
	        
	        Aggregations agg = entry.getAggregations();
	        Avg avg = agg.get("avg_price");
	        Double avgPrice = avg.getValue();
	        
	        System.out.println(key + "車有" + count + "輛,平均每台車價格:" + avgPrice);
	    }
    }
           

文章參考: https://www.elastic.co/guide/cn/elasticsearch/guide/current/_adding_a_metric_to_the_mix.html

繼續閱讀