美文网首页
桶和指标 聚合搜索

桶和指标 聚合搜索

作者: sakura579 | 来源:发表于2021-09-16 11:30 被阅读0次
public RestResult fileChart(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders
                .terms("file_tr").field("file_time")// 桶分组
                .size(50)
                .subAggregation(AggregationBuilders.sum("file_sum").field("file_size"));// 求和
        searchSourceBuilder.aggregation(aggregationBuilder);
        // 不输出原始数据
        //searchSourceBuilder.size(0);
        // 打印dsl语句
        log.info("dsl:" + searchSourceBuilder.toString());
        // 搜索请求对象
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("file");
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("IOException:",e);
            return RestResponse.failed("");
        }
        Map<String,Object> result = new HashMap<>();
        Aggregations aggregations = searchResponse.getAggregations();
        ParsedDoubleTerms parsedDoubleTerms = aggregations.get("file_tr");
        List<? extends Terms.Bucket> buckets = parsedDoubleTerms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            //time
            String key = new BigDecimal(String.valueOf(((double) bucket.getKey()) * 1000))
                    .toPlainString().split("\\.")[0];
            String formatTime = dateFormat.format(new Date(Long.parseLong(key)));
            long docCount = bucket.getDocCount();
            //获取数据
            Aggregations bucketAggregations = bucket.getAggregations();
            ParsedSum sum = bucketAggregations.get("file_sum");
            result.put("time",formatTime);
            result.put("docCount",docCount);
            result.put("sum",sum.getValue());
            System.out.println(formatTime + ":" + docCount + "__" + sum.getValue());
        }
        return RestResponse.success(result);
    }

相关文章

网友评论

      本文标题:桶和指标 聚合搜索

      本文链接:https://www.haomeiwen.com/subject/dzdrgltx.html