SpringCloud(九.2)ES 进阶 -- RestAPI实现自动补全查询
语法
备注:因是只是案例讲解对应关系, “hotelSuggestion” "title_suggest" 和上图的 “mySuggestion” 是一个东西 ,都是suggest的名称,正常开发时应该保持为一个名称。
酒店demo 单元测试案例:
@Test void testSuggest() throws IOException { // 1.准备请求 SearchRequest request = new SearchRequest("hotel"); // 2.请求参数 request.source().suggest(new SuggestBuilder() .addSuggestion( "hotelSuggest", SuggestBuilders .completionSuggestion("suggestion") .size(10) .skipDuplicates(true) .prefix("s") )); // 3.发出请求 SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 4.解析 Suggest suggest = response.getSuggest(); // 4.1.根据名称获取结果 CompletionSuggestion suggestion = suggest.getSuggestion("hotelSuggest"); // 4.2.获取options for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) { // 4.3.获取补全的结果 String str = option.getText().toString(); System.out.println(str); } }
结果展示:
酒店demo实战案例
Controller 编写接口 key为搜索的关键字
@GetMapping("suggestion") public List<String> getSuggestion(@RequestParam("key") String key) { return hotelService.getSuggestion(key); }
alt+enter 补齐IService,Service实现getSuggestion方法
Service
@Override public List<String> getSuggestion(String key) { try { // 1.准备请求 SearchRequest request = new SearchRequest("hotel"); // 2.请求参数 request.source().suggest(new SuggestBuilder() .addSuggestion( "hotelSuggest", SuggestBuilders .completionSuggestion("suggestion") .size(10) .skipDuplicates(true) .prefix(key) )); // 3.发出请求 SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT); // 4.解析 Suggest suggest = response.getSuggest(); // 4.1.根据名称获取结果 CompletionSuggestion suggestion = suggest.getSuggestion("hotelSuggest"); // 4.2.获取options List<String> list = new ArrayList<>(); for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) { // 4.3.获取补全的结果 String str = option.getText().toString(); // 4.4.放入集合 list.add(str); } return list; } catch (IOException e) { throw new RuntimeException(e); } }