es GroupBy 分组,按天、周、月

1、sql样例

select  max(price) as max_price,avg(price) as avg_price from product_index group by created_date_time;

2、用代码生成数据

    private static void batchCreate(TransportClient transportClient) throws IOException {
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();

        IndexRequestBuilder indexRequestBuilder1 = transportClient.prepareIndex("product_index", "product", "1")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("product_name", "飞利浦电动牙刷 HX6700-1")
                        .field("product_desc", "前 1000 名赠刷头,6 月 1 日 0 点火爆开抢,618 开门红巅峰 48 小时")
                        .field("price", 100.00)
                        .field("created_date_time", 1582786948646L)
                        .field("last_modified_date_time", new Date().getTime())
                        .field("version", 3)
                        .endObject());

        IndexRequestBuilder indexRequestBuilder2 = transportClient.prepareIndex("product_index", "product", "2")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("product_name", "飞利浦电动牙刷 HX6700-2")
                        .field("product_desc", "前 1000 名赠刷头,6 月 1 日 0 点火爆开抢,618 开门红巅峰 48 小时")
                        .field("price", 500.00)
                        .field("created_date_time", 1582786980645L)
                        .field("last_modified_date_time", new Date().getTime())
                        .field("version", 8)
                        .endObject());

        IndexRequestBuilder indexRequestBuilder3 = transportClient.prepareIndex("product_index", "product", "3")
                .setSource(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("product_name", "飞利浦电动牙刷 HX6700-3")
                        .field("product_desc", "前 1000 名赠刷头,6 月 1 日 0 点火爆开抢,618 开门红巅峰 48 小时")
                        .field("price", 600.00)
                        .field("created_date_time", 1582786523000L)
                        .field("last_modified_date_time", new Date().getTime())
                        .field("version", 9)
                        .endObject());


        bulkRequestBuilder.add(indexRequestBuilder1);
        bulkRequestBuilder.add(indexRequestBuilder2);
        bulkRequestBuilder.add(indexRequestBuilder3);

        BulkResponse bulkResponse = bulkRequestBuilder.get();
        for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) {
            log.info("--------------------------------version= " + bulkItemResponse.getVersion());
        }
    }

3、java 查询数据解析数据

    private static void aggregateAVG(TransportClient transportClient) throws IOException {
        SearchRequestBuilder sbuilder = transportClient.prepareSearch("product_index").setTypes("product");

        DateHistogramAggregationBuilder teamAgg = AggregationBuilders
                .dateHistogram("player_count")
                .field("created_date_time")
                .dateHistogramInterval(DateHistogramInterval.HOUR).format("yyyy-MM-dd HH:mm:ss");

        AvgAggregationBuilder priceAVG = AggregationBuilders.avg("avg_price").field("price");
        MaxAggregationBuilder priceMAX = AggregationBuilders.max("max_price").field("price");

        sbuilder.addAggregation(teamAgg.subAggregation(priceAVG).subAggregation(priceMAX));

        SearchResponse response = sbuilder.execute().actionGet();

        //解析数据

        Map<String, Aggregation> aggMap = response.getAggregations().asMap();
        Aggregation player_count = aggMap.get("player_count");

        Histogram teamAgg1 = (Histogram) aggMap.get("player_count");

        Iterator<? extends Histogram.Bucket> teamBucketIt = teamAgg1.getBuckets().iterator();

        while (teamBucketIt.hasNext()) {
            Histogram.Bucket buck = teamBucketIt.next();
            
            //分组时间
            String team = buck.getKey().toString();
            System.out.println("time:" + team);
            
            //记录数
            long count = buck.getDocCount();
            
            //得到所有子聚合
            Map subaggmap = buck.getAggregations().asMap();
            
            //avg值获取方法
            double avg_age = ((InternalAvg) subaggmap.get("avg_price")).getValue();
            System.out.println("avg_price:" + avg_age);
            
            //max值获取方法
            double max_price = ((InternalMax) subaggmap.get("max_price")).getValue();
            System.out.println("max_price:" + max_price);
            //...
        }
    }

4、注意:es的时间戳需要精确到毫秒值

5、参考地址
1、 https://elasticsearch.cn/article/102
2、https://github.com/judasn/Elasticsearch-Tutorial-zh-CN

你可能感兴趣的:(es GroupBy 分组,按天、周、月)