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;
    }
}
相关推荐
敲代码娶不了六花35 分钟前
jsp | servlet | spring forEach读取不了对象List
java·spring·servlet·tomcat·list·jsp
Yhame.35 分钟前
深入理解 Java 中的 ArrayList 和 List:泛型与动态数组
java·开发语言
是小崔啊2 小时前
开源轮子 - EasyExcel02(深入实践)
java·开源·excel
myNameGL3 小时前
linux安装idea
java·ide·intellij-idea
青春男大3 小时前
java栈--数据结构
java·开发语言·数据结构·学习·eclipse
HaiFan.3 小时前
SpringBoot 事务
java·数据库·spring boot·sql·mysql
我要学编程(ಥ_ಥ)3 小时前
一文详解“二叉树中的深搜“在算法中的应用
java·数据结构·算法·leetcode·深度优先
music0ant3 小时前
Idea 添加tomcat 并发布到tomcat
java·tomcat·intellij-idea
计算机徐师兄4 小时前
Java基于SSM框架的无中介租房系统小程序【附源码、文档】
java·微信小程序·小程序·无中介租房系统小程序·java无中介租房系统小程序·无中介租房微信小程序
源码哥_博纳软云4 小时前
JAVA智慧养老养老护理帮忙代办陪诊陪护小程序APP源码
java·开发语言·微信小程序·小程序·微信公众平台