统计索引中某个字段的个数
public class ESTest_Doc_Query { ? ? public static void main(String[] args) throws Exception { ? ? ? ? //创建ES客户端 ? ? ? ? RestHighLevelClient esClient = new RestHighLevelClient( ? ? ? ? ? ? ? ? RestClient.builder(new HttpHost("localhost",9200,"http")) ? ? ? ? );
? ? ? ? //12、统计个数 ? ? ? ? SearchRequest request = new SearchRequest(); ? ? ? ? request.indices("user");
? ? ? ? SearchSourceBuilder builder = new SearchSourceBuilder(); ? ? ? ? //统计年龄在30-40之间的有多少 ? ? ? ? AggregationBuilder ?aggregationBuilder = AggregationBuilders.count("ageCount").field("age"); ? ? ? ? RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").from(30,true).to(40,true); ? ? ? ? builder.aggregation(aggregationBuilder); ? ? ? ? builder.query(rangeQueryBuilder); ? ? ? ? request.source(builder); ? ? ? ? SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
? ? ? ? System.out.println("s:"+response.toString());
? ? ? ? SearchHits hits = response.getHits(); ? ? ? ? System.out.println(hits.getTotalHits()); ? ? ? ? System.out.println(response.getTook());
? ? ? ? for(SearchHit hit : hits){ ? ? ? ? ? ? System.out.println(hit.getSourceAsString()); ? ? ? ? } ? ? ? ?? ? ? ? ? //关闭ES客户端 ? ? ? ? esClient.close(); ? ? } }
年龄在30-40之间的有4个:
?
|