ES7.6先分组,在求多个字段的sum和count

public void statByUserIdByDay(String userId){
        try {
            SearchRequest searchRequest = new SearchRequest("article_info");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);

            searchSourceBuilder.query(QueryBuilders.termQuery("user_id", userId));
            DateHistogramAggregationBuilder dateAggregation = AggregationBuilders
                    .dateHistogram("agg_pubtime")
                    .field("pubtime")
                    .fixedInterval(DateHistogramInterval.DAY)
                    .format("yyyy-MM-dd")
                    .minDocCount(0);

            SumAggregationBuilder likesAggregation = AggregationBuilders.sum("likes_sum").field("like_count");
            SumAggregationBuilder retweetsAggregation = AggregationBuilders.sum("rtt_sum").field("rtt_count");
            SumAggregationBuilder commentsAggregation = AggregationBuilders.sum("comments_sum").field("comment_count");
            ValueCountAggregationBuilder countAggregation = AggregationBuilders.count("count").field("user_id");

            dateAggregation.subAggregation(likesAggregation)
                    .subAggregation(retweetsAggregation)
                    .subAggregation(commentsAggregation)
                    .subAggregation(countAggregation);

            searchSourceBuilder.aggregation(dateAggregation);

            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            Histogram agg_pubtime = searchResponse.getAggregations().get("agg_pubtime");

            for (Histogram.Bucket bucket : agg_pubtime.getBuckets()) {
                String pubtime = bucket.getKeyAsString();

                Aggregations aggregations = bucket.getAggregations();
                Sum likesSum = aggregations.get("likes_sum");
                Sum forwardsSum = aggregations.get("rtt_sum");
                Sum commentsSum = aggregations.get("comments_sum");
                ValueCount count = aggregations.get("count");

                System.out.println("userId="+userId +"  pubtime="+pubtime+" likesSum ="+likesSum.getValue() +"  forwardsSum="+forwardsSum.getValue() +"    commentsSum="+commentsSum.getValue() + "   count ="+count.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
select pubtime, sum(field1), sum(field2),sum(field3), count(userId) from table where userId = xxxx group by 按天(pubtime); 

你可能感兴趣的:(java,es)