RestHighLevelClient 实现 select count from table group by filed

String id = null;
try {SearchRequest request = new SearchRequest(IndexAndTypeConstant.PROPERTY_SQL);
            request.types(IndexAndTypeConstant.PROPERTY_SQL_TYPE);

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.size(0);
            request.source(searchSourceBuilder);

            TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("estateIdAgg").field(PropertyIndexMappingConstant.ESTATE_ID);
            aggregationBuilder.order(BucketOrder.count(false));
            aggregationBuilder.size(Integer.MAX_VALUE);//todo
            searchSourceBuilder.aggregation(aggregationBuilder);
            SearchResponse searchResponse = client.search(request);
            Map aggMap = searchResponse.getAggregations().getAsMap();
            ParsedStringTerms gradeTerms = (ParsedStringTerms) aggMap.get("estateIdAgg");
            List list = gradeTerms.getBuckets();
            for (Object object : list) {
                ParsedStringTerms.ParsedBucket obj = (ParsedStringTerms.ParsedBucket) object;
                String key = obj.getKeyAsString();
                long count = obj.getDocCount();
                id = key;
                UpdateRequest updateRequest = new UpdateRequest(IndexAndTypeConstant.SEARCH_INDEX,
                        IndexAndTypeConstant.SEARCH_TYPE, key)
                        .doc(jsonBuilder()
                                .startObject()
                                .field("count", count)
                                .endObject());
                client.update(updateRequest);
            }
        } catch (Exception e) {
           System.err.println("本条数据插入失败 id: " + id);
        }

你可能感兴趣的:(elasticsearch)