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客戶端的使用