@Test
void searchTest() throws IOException {
SearchRequest searchRequest = new SearchRequest();
//1、指定索引
searchRequest.indices("bank");
//2.1、指定检索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("address", "mill"));
//2.2、按照年龄分布进行聚合
TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age");
sourceBuilder.aggregation(ageAgg);
//2.3、计算平均薪资
AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
sourceBuilder.aggregation(balanceAvg);
//3、添加检索条件
searchRequest.source(sourceBuilder);
//4、执行检索
SearchResponse searchResponse = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
//5、打印检索结果
System.out.println(searchResponse.toString());
//6、分析检索结果
SearchHits hits = searchResponse.getHits();
SearchHit[] hits1 = hits.getHits();
for (SearchHit hit : hits1) {
String sourceAsString = hit.getSourceAsString();
bankEntity bankEntity = JSON.parseObject(sourceAsString, bankEntity.class);//通过json工具类讲过json字符串转为对象
System.out.println(bankEntity);
}
//7、打印聚合结果
Aggregations aggregations = searchResponse.getAggregations();
Terms ageAgg1 = aggregations.get("ageAgg");//这个是term聚合
for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
System.out.println("年龄:" + bucket.getKey());
}
Avg balanceAvg1 = aggregations.get("balanceAvg");//这个是avg聚合
System.out.println("平均薪资:" + balanceAvg1.getValue());
}
@Data
static class bankEntity {
private int account_number;
private int balance;
private String firstname;
private String lastname;
private int age;
private String gender;
private String address;
private String employer;
private String email;
private String city;
private String state;
}
标签:检索,bankEntity,Springboot,42,sourceBuilder,private,HignLevelClient,balanceAvg,Str
From: https://www.cnblogs.com/morehair/p/17062279.html