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

该代码片段展示了如何使用ElasticsearchAPI对用户的文章按天进行统计,包括点赞、转发、评论数量和用户总数。它通过SearchRequest和AggregationBuilders执行查询,获取指定用户在每一天的数据汇总。
摘要由CSDN通过智能技术生成
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); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值