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

java 复制代码
 // 设置查询条件
        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<String, Aggregation> aggMap = sr.getAggregations().asMap();
        DateHistogram classTerms = (DateHistogram)aggMap.get("agg_pubtime");
        Iterator<org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram.Bucket> classBucketIt = (Iterator<Bucket>) classTerms.getBuckets().iterator();
        List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
        List<String[]> result = new ArrayList();
        while(classBucketIt.hasNext()){
            Map<String,Object> res = new HashMap<String, Object>();
            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<Terms.Bucket> buckets = (List<Terms.Bucket>) agg_type.getBuckets();
            List<String[]> list = new ArrayList<String[]>();
            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

java 复制代码
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;
    }
}
相关推荐
JienDa1 小时前
JienDa聊PHP:CSDN博客仿站实战中PHP框架的协同架构方略
java·架构·php
大迪吃小迪1 小时前
每秒 400 请求场景下,线程池如何合理配置?
java·开发语言
雨中飘荡的记忆2 小时前
财务对账系统设计与实现
java
0***h9422 小时前
使用 java -jar 命令启动 Spring Boot 应用时,指定特定的配置文件的几种实现方式
java·spring boot·jar
雨中飘荡的记忆2 小时前
布式事务详解:从理论到实践(RocketMQ + Seata)
java·rocketmq
i***48613 小时前
微服务生态组件之Spring Cloud LoadBalancer详解和源码分析
java·spring cloud·微服务
zzlyx993 小时前
用C#采用Avalonia+Mapsui在离线地图上插入图片画信号扩散图
java·开发语言·c#
Aevget3 小时前
MyEclipse全新发布v2025.2——AI + Java 24 +更快的调试
java·ide·人工智能·eclipse·myeclipse
一 乐3 小时前
购物|明星周边商城|基于springboot的明星周边商城系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·spring
笃行客从不躺平3 小时前
线程池监控是什么
java·开发语言