ES 两次group by,先按照每天的时间力度,在统计每天的指定字段的值出现的次数

    public void addPubtimeAgg(){

        DateHistogramBuilder dateHistogramBuilder = AggregationBuilders.dateHistogram("pubtime_histogram")
                .field("pubtime").interval(DateHistogram.Interval.days(1))
                .minDocCount(0L);
        dateHistogramBuilder.format("yyyy-MM-dd");

        TermsBuilder field = AggregationBuilders.terms("agg_tw_id").field("tw_id").size(30);
        dateHistogramBuilder.subAggregation(field);

        searchbuilder.addAggregation(dateHistogramBuilder);
        if (this.query != null) {
            this.searchbuilder.setQuery(this.query);
        }
        SearchResponse sr = searchbuilder.execute().actionGet();

        Map aggMap = sr.getAggregations().asMap();
        DateHistogram classTerms = (DateHistogram)aggMap.get("pubtime_histogram");
        Iterator classBucketIt = (Iterator) classTerms.getBuckets().iterator();
        while(classBucketIt.hasNext()){
            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_tw_id");
            List buckets = (List) agg_type.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String[] str = new String[2];
                str[0] = bucket.getKey().trim();//日期
                str[1] = String.valueOf(bucket.getDocCount());//数量
                System.out.println( str[0]  +"======"   + str[1] );
            }
        }
    }

你可能感兴趣的:(es)