Springboot 整合Elasticsearch

时间:2025-04-02 13:22:34
@SpringBootTest public class SearchApplicationTests { @Autowired private RestHighLevelClient client; @Data @ToString static class Account { 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; } /** * 在new_bank中搜索address中包含mill的所有人的年龄分布以及平均薪资 */ @Test public void searchData() throws IOException { //1,创建检索请求 SearchRequest searchRequest = new SearchRequest(); //1.1,指定检索索引 searchRequest.indices("new_bank"); //1.2,构造检索条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("address", "Mill")); //1.2.1,按照年龄分布进行聚合 TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10); searchSourceBuilder.aggregation(ageAgg); //1.2.2,计算平均薪资 AvgAggregationBuilder avgBalance = AggregationBuilders.avg("avgBalance").field("balance"); searchSourceBuilder.aggregation(avgBalance); System.out.println("检索条件" + searchSourceBuilder); searchRequest.source(searchSourceBuilder); //2,执行同步检索 SearchResponse searchResponse = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS); System.out.println("执行检索结果" + searchResponse); //3,提取命中结果hits SearchHits hits = searchResponse.getHits(); SearchHit[] hitsHits = hits.getHits(); for (SearchHit hitsHit : hitsHits) { String sourceAsString = hitsHit.getSourceAsString(); Account account = JSONObject.parseObject(sourceAsString, Account.class); System.out.println(account); } //4,提取聚合信息 Aggregations aggregations = searchResponse.getAggregations(); Terms ageAggRes = aggregations.get("ageAgg"); List<? extends Terms.Bucket> aggResBuckets = ageAggRes.getBuckets(); for (Terms.Bucket aggResBucket : aggResBuckets) { System.out.println("年龄:" + aggResBucket.getKeyAsString() + "总和:" + aggResBucket.getDocCount()); } Avg balance = aggregations.get("avgBalance"); System.out.println(balance.getValue()); } /** * /guide/en/elasticsearch/client/java-rest/7.4/ */ @Test public void testEsAdd() throws IOException { //指定索引 IndexRequest indexRequest = new IndexRequest("users"); //指定id indexRequest.id("1"); //封装数据 User user = new User(); user.setUserName("张三"); user.setAge(27); user.setGender("M"); String jsonString = JSONObject.toJSONString(user); //指定数据类型为JSON indexRequest.source(jsonString, XContentType.JSON); //执行同步操作 IndexResponse index = client.index(indexRequest, ElasticsearchConfig.COMMON_OPTIONS); System.out.println(index); } @Data class User { private String userName; private String gender; private Integer age; } }