EasyEs复杂聚合使用 案例

EasyEs 聚合简单使用 案例,这里面有几个注意点:
1.wrapper 条件必须前置,后获取聚合构造器
2.COUNT 聚合 必须在某个聚合的子聚合
3.每个聚合结果映射均不一样,
4.分组的概念:就是父子聚合的概念,父就是分组

/**
* 构建聚合查询
*/
public CashOrderReport sumByDate(Long storeId, LocalDate startTime, LocalDate endTime) {
        if (endTime == null) {
            endTime = startTime;
        }
        LambdaEsQueryWrapper<CashOrder> wrapper = new LambdaEsQueryWrapper<>();
        //查询条件  必须在前
        wrapper.eq(CashOrder::getStoreId, storeId);
        wrapper.ge(CashOrder::getCreateTime, startTime);
        wrapper.le(CashOrder::getCreateTime, endTime);

        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("cash_order");
		//terms 查询条件
        TermQueryBuilder orderNumFilter = QueryBuilders.termQuery("orderStatus", "settled");
        //filter + COUNT 聚合
        AggregationBuilder orderNumAggr = AggregationBuilders.filter("orderNum", orderNumFilter)
                .subAggregation(AggregationBuilders.count("orderNum").field("orderStatus"));
		//获取构造器 注意:这里入参是 wrapper,(条件续前置,后置条件无效)
        SearchSourceBuilder builder = getEsMapper().getSearchSourceBuilder(wrapper);
        //SUM 聚合
        builder.aggregation(AggregationBuilders.sum("total").field("total"));
        //AVG 聚合
        builder.aggregation(AggregationBuilders.avg("aveTotal").field("total"));
        //COUNT 聚合
        builder.aggregation(orderNumAggr);
        searchRequest.source(builder);
		//聚合请求
        wrapper.setSearchSourceBuilder(builder);
        SearchResponse response = getEsMapper().search(wrapper);
        System.out.println("response = " + response);
        return convertResponse(response);
    }
/**
* 聚合查询结果转化
*/

    /**
     * 将返回结果转换为对象
     */
    private List<CashOrderReport> convertResponseToList(SearchResponse response) {
        List<CashOrderReport> orderReports = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        aggregations.asList().forEach(value -> {
            ParsedDateHistogram histogram = (ParsedDateHistogram) value;
            histogram.getBuckets().forEach(bucket -> {
                orderReports.add(covertBucket(bucket));
            });
        });
        return orderReports;
    }

    private CashOrderReport covertBucket(Histogram.Bucket bucket) {
        CashOrderReport orderReport = new CashOrderReport();
        orderReport.setIncome(new BigDecimal("0"));
        orderReport.setTurnover(new BigDecimal("0"));
        orderReport.setAcCoupon(new BigDecimal("0"));
        orderReport.setRealPay(new BigDecimal("0"));
        orderReport.setValidOrderNum(0);
        orderReport.setAveOrderAmount(new BigDecimal("0"));
        orderReport.setReportDate(LocalDate.parse(bucket.getKeyAsString()));
        Map<String, Aggregation> aggregationMap = bucket.getAggregations().asMap();
        return covertReport(orderReport, aggregationMap);
    }

    CashOrderReport covertReport(CashOrderReport orderReport, Map<String, Aggregation> aggregationMap) {
        ParsedSum total = (ParsedSum) aggregationMap.get("total");
        ParsedSum totalPrice = (ParsedSum) aggregationMap.get("totalPrice");
        ParsedSum discountPrice = (ParsedSum) aggregationMap.get("discountPrice");
        ParsedAvg aveTotal = (ParsedAvg) aggregationMap.get("aveTotal");
        ParsedFilter orderNum = (ParsedFilter) aggregationMap.get("orderNum");
        orderReport.setRealPay(BigDecimal.valueOf(total.getValue()).setScale(2, RoundingMode.HALF_UP));
        orderReport.setTurnover(BigDecimal.valueOf(totalPrice.getValue()).setScale(2, RoundingMode.HALF_UP));
        orderReport.setAcCoupon(BigDecimal.valueOf(discountPrice.getValue()).setScale(2, RoundingMode.HALF_UP));
        orderReport.setIncome(orderReport.getTurnover().subtract(orderReport.getAcCoupon()));
        orderReport.setAveOrderAmount(BigDecimal.valueOf(aveTotal.getValue()).setScale(2, RoundingMode.HALF_UP));
        orderNum.getAggregations().asList().forEach(e -> {
            ParsedValueCount count = (ParsedValueCount) e;
            orderReport.setValidOrderNum((int) count.getValue());
        });
        return orderReport;
    }

    /**
     * 将返回结果转换为对象
     */
    private CashOrderReport convertResponse(SearchResponse response) {
        CashOrderReport orderReport = new CashOrderReport();
        orderReport.setIncome(new BigDecimal("0"));
        orderReport.setTurnover(new BigDecimal("0"));
        orderReport.setAcCoupon(new BigDecimal("0"));
        orderReport.setRealPay(new BigDecimal("0"));
        orderReport.setValidOrderNum(0);
        orderReport.setAveOrderAmount(new BigDecimal("0"));

        Map<String, Aggregation> aggregationMap = response.getAggregations().asMap();
        return covertReport(orderReport, aggregationMap);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值