ElasticSearch_聚合分析_平均、最大、最小值

需求

根据颜色进行聚合,分别求最大、最小、平均值及总和;

DSL 实现

GET /tvs/sales/_search
{
  "size": 0,
  "aggs": {
    "colors": {
      "terms": {
        "field": "color"
      },
      "aggs": {
        "min_price": { "min": {"field": "price"}},
        "max_price": { "max": {"field": "price"}},
        "avg_price": { "avg": {"field": "price"}},
        "sum_price": { "sum": {"field": "price"}}
      }
    }
  }
}

返回结果如下:

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 8,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "colors": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "红色",
          "doc_count": 5,
          "max_price": {
            "value": 4000
          },
          "min_price": {
            "value": 1000
          },
          "avg_price": {
            "value": 2200
          },
          "sum_price": {
            "value": 11000
          }
        },
        {
          "key": "绿色",
          "doc_count": 3,
          "max_price": {
            "value": 4000
          },
          "min_price": {
            "value": 2000
          },
          "avg_price": {
            "value": 3000
          },
          "sum_price": {
            "value": 9000
          }
        }
      ]
    }
  }
}

High Rest API 实现

package com.elasticsearch.aggregation;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.List;

public class aggregation02 {

    /**
     * 根据颜色进行聚合,分别求最大、最小、平均值及总和;
     *
     * */
    public static void main(String[] args) {

        RestHighLevelClient client = getClient();

        SearchRequest searchRequest = new SearchRequest("tvs").types("sales");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());

        TermsAggregationBuilder aggregationColor = AggregationBuilders
                .terms("groupby_colors")  //聚合名称
                .field("color");   //分组属性

        //最小值
        aggregationColor.subAggregation(
                AggregationBuilders.min("min_price")
                        .field("price")
        );

        //最大值
        aggregationColor.subAggregation(
                AggregationBuilders.max("max_price")
                        .field("price")
        );

        //平均值
        aggregationColor.subAggregation(
                AggregationBuilders.avg("avg_price")
                        .field("price")
        );

        //求和
        aggregationColor.subAggregation(
                AggregationBuilders.sum("sum_price")
                        .field("price")
        );

        searchSourceBuilder.aggregation(aggregationColor);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = null;

        try{
            searchResponse = client.search(searchRequest);
        }catch (IOException e){
            e.printStackTrace();
        }

        Aggregations aggregations = searchResponse.getAggregations();
        Terms groupby_colors = aggregations.get("groupby_colors");
        List colorsBuckets = groupby_colors.getBuckets();
        for(Terms.Bucket colorsbucket : colorsBuckets){
            String color = (String)colorsbucket.getKey();
            Min min_price = colorsbucket.getAggregations().get("min_price");
            Max max_price = colorsbucket.getAggregations().get("max_price");
            Avg avg_price = colorsbucket.getAggregations().get("avg_price");
            Sum sum_price = colorsbucket.getAggregations().get("sum_price");

            System.out.println("color : " + color
                    + ", min : " + min_price.getValue()
                    + ", max : " + max_price.getValue()
                    + ", avg : " + avg_price.getValue()
                    + ", sum : " + sum_price.getValue());

        }

    }

    public static RestHighLevelClient getClient()
    {
        HttpHost httpHost = new HttpHost("localhost", 9200, "http");
        HttpHost[] httpHostsArray = new HttpHost[1];
        httpHostsArray[0] = httpHost;
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestClient build = builder.build();
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(build);
        return restHighLevelClient;
    }
}

你可能感兴趣的:(ElasticSearch)