es1.7.2 按照_type先聚合,再按照时间二次聚合

 // 设置查询条件
        if (this.query != null) {
            this.searchbuilder.setQuery(this.query);
        }
        TermsBuilder typeAggregation = AggregationBuilders.terms("agg_type").field("_type");

        DateHistogramBuilder dateTermsBuilder = AggregationBuilders.dateHistogram("agg_pubtime").field("pubtime");
        dateTermsBuilder.format("yyyy-MM-dd");
        dateTermsBuilder.interval(DateHistogram.Interval.days(1));

        dateTermsBuilder.subAggregation(typeAggregation);
        searchbuilder.addAggregation(dateTermsBuilder);


        SearchResponse sr = searchbuilder.execute().actionGet();
        Map aggMap = sr.getAggregations().asMap();
        DateHistogram classTerms = (DateHistogram)aggMap.get("agg_pubtime");
        Iterator classBucketIt = (Iterator) classTerms.getBuckets().iterator();
        List> dataList = new ArrayList>();
        List result = new ArrayList();
        while(classBucketIt.hasNext()){
            Map res = new HashMap();
            org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram.Bucket classBucket = classBucketIt.next();
            //System.out.println("时间"+classBucket.getKey());
            StringTerms agg_type = (StringTerms) classBucket.getAggregations().asMap().get("agg_type");
            List buckets = (List) agg_type.getBuckets();
            List list = new ArrayList();
            for (Terms.Bucket bucket : buckets) {
                String[] str = new String[2];
                str[0] = bucket.getKey().trim();//日期
                str[1] = String.valueOf(bucket.getDocCount());//数量
//                list.add(str);
                //System.out.println( str[0]  +"======"   + str[1] );

               
            }

        }

参考:gpt

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.common.unit.TimeValue;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AggregationExample {
    public static void main(String[] args) throws IOException {
        // 创建 Elasticsearch 客户端
        RestHighLevelClient client = createClient();

        // 创建聚合请求
        SearchRequest searchRequest = new SearchRequest("your_index_name");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 设置查询条件
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());

        // 设置第一级聚合,按照 _type 字段进行聚合
        Terms.AggregationBuilder typeAggregation = AggregationBuilders.terms("by_type").field("_type");

        // 设置第二级聚合,按照时间进行聚合,这里使用日期直方图(Histogram)聚合
        Terms.BucketOrder termsOrder = Terms.BucketOrder.key(true);
        typeAggregation.subAggregation(
                AggregationBuilders.dateHistogram("by_time")
                        .field("your_time_field")
                        .dateHistogramInterval(DateHistogramInterval.DAY)
                        .subAggregation(AggregationBuilders.terms("top_hits").size(10).order(termsOrder))
        );

        // 添加聚合请求到搜索源中
        searchSourceBuilder.aggregation(typeAggregation);

        // 设置分页和超时时间
        searchSourceBuilder.size(0);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 发起搜索请求并获取响应
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        // 解析聚合结果
        Terms byTypeAggregation = searchResponse.getAggregations().get("by_type");
        for (Terms.Bucket typeBucket : byTypeAggregation.getBuckets()) {
            System.out.println("Type: " + typeBucket.getKeyAsString());

            Terms byTimeAggregation = typeBucket.getAggregations().get("by_time");
            for (Terms.Bucket timeBucket : byTimeAggregation.getBuckets()) {
                System.out.println("Time: " + timeBucket.getKeyAsString());
                
                Terms topHitsAggregation = timeBucket.getAggregations().get("top_hits");
                for (Terms.Bucket hitBucket : topHitsAggregation.getBuckets()) {
                    System.out.println("Hit: " + hitBucket.getKeyAsString());
                }
            }
        }

        // 关闭 Elasticsearch 客户端
        client.close();
    }

    private static RestHighLevelClient createClient() {
        // 创建和配置 Elasticsearch 客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        return client;
    }
}

你可能感兴趣的:(java)