@Test public void testQuerySearch() { SearchRequest request = new SearchRequest(); request.indices("es_user"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("address","shenyang")); TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10); sourceBuilder.aggregation(ageAgg); AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("salary"); sourceBuilder.aggregation(balanceAvg); request.source(sourceBuilder); System.out.println(sourceBuilder.toString()); try { SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT); SearchHit[] searchHtis = response.getHits().getHits(); for (SearchHit searchHit : searchHtis) { Map<String, Object> sourceResult = searchHit.getSourceAsMap(); System.out.println(sourceResult.get("user_name")); } Aggregations aggregations = response.getAggregations(); Terms ageAgg1 = aggregations.get("ageAgg"); for (Terms.Bucket bucket : ageAgg1.getBuckets()) { String keyAsString = bucket.getKeyAsString(); System.out.println("用户年龄: " + keyAsString + " 人数:" + bucket.getDocCount()); } Avg balanceAvg1 = aggregations.get("balanceAvg"); System.out.println("平均薪资:" + balanceAvg1.getValue()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }