1. 程式人生 > >RestHighLevelClient 實現 select count from table group by filed

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<String, Aggregation> 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); }