Java客户端分为低级客户端和高级客户端两种。低级客户端兼容所有版本的ES,但其需要提供JSON字符串,因此这种开发方式比较低效。高级客户端是基于低级客户端开发出来的,屏蔽了底层技术,使用户可以更专注于搜索业务,这是官方推荐的开发方式。本节介绍的Java客户端使用的是高级客户端。
演示RestHighLevelClient的使用,需要创建一个Spring Boot Web项目。该项目的依赖配置如下:
elasticsearch 7.10.2
<!--ES客户端依赖--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.10.2</version> <exclusions> <exclusion> <artifactId>elasticsearch-rest-client</artifactId> <groupId>org.elasticsearch.client</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.10.2</version> </dependency> <!--ES依赖--> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.10.2</version> </dependency>
在application.yml文件中配置ES的连接信息如下:
spring:
elasticsearch:
rest:
uris: 127.0.0.1:9200
username: elasticsearch
password:
Java客户端搜索文档
@Data public class Hotel { String id;//对应于文档_id String index;//对应于索引名称 Float score;//对应于文档得分 String title; //对应于索引中的title String city; //对应于索引中的city Double price; //对应于索引中的price }
@Service public class EsService { @Autowired RestHighLevelClient restHighLevelClient; public List<Hotel> getHotelFromTitle(String keyword) { SearchRequest searchRequest = new SearchRequest("hotel");//客户端请求 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("title", keyword));//构建query searchRequest.source(searchSourceBuilder); List<Hotel> resultList = new ArrayList<>(); try { SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); RestStatus status = searchResponse.status(); if (status != RestStatus.OK) { return null; } SearchHits searchHits = searchResponse.getHits(); for (SearchHit searchHit : searchHits) { Hotel hotel = new Hotel(); hotel.setId(searchHit.getId());//文档_id hotel.setIndex(searchHit.getIndex());//索引名称 hotel.setScore(searchHit.getScore());//文档得分 Map<String, Object> dataMap = searchHit.getSourceAsMap();//转换为Map hotel.setTitle((String) dataMap.get("title"));//设置标题 hotel.setCity((String) dataMap.get("city"));//设置城市 hotel.setPrice((Double) dataMap.get("price"));//设置价格 resultList.add(hotel); } return resultList; } catch (Exception e) { e.printStackTrace(); } return null; } }
@Slf4j @Api(tags = "EsHotelController") @RequestMapping("/es/hotel") @RestController public class EsHotelController { @Autowired EsService esService; @GetMapping(value = "/getHotelFromTitle") public String getHotelFromTitle(String title) { if (StringUtils.isEmpty(title)) { title = "再来"; } List<Hotel> hotelList = esService.getHotelFromTitle(title);//调用Service完成搜索 if (hotelList != null && hotelList.size() > 0) {//搜索到结果打印到前端 return hotelList.toString(); } else { return "no data."; } } }
文章参考:Elasticsearch搜索引擎构建入门与实战 --> 2.2.1 Java客户端的使用