RestAPI实现自动补全 & 案例实现(搜索框输入进行自动补全)

一、RestAPI实现自动补全查询(代码讲解)

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    @Autowired
private RestHighLevelClient client;


@Test
void testSuggestion() throws IOException {
//1.准备Request
SearchRequest request = new SearchRequest("hotel");
//2.准备DSL
request.source().suggest(new SuggestBuilder().addSuggestion(
"suggestions",
SuggestBuilders.completionSuggestion("suggestion")
.prefix("hm")
.skipDuplicates(true)
.size(10)
));
//3.发起请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);

//4.解析结果
Suggest suggest = response.getSuggest();
//4.1 根据补全查询名称,获取更全的结果
CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
//4,2 获取options
List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
//4.3 遍历
for( CompletionSuggestion.Entry.Option option : options){
String text = option.getText().toString();
System.out.println(text);
}

// System.out.println(response);
}

其中:

@Autowired
private RestHighLevelClient client;

要在项目启动方法里面注入到bean里

二、以下进行黑马旅游网的案例实现自动补全功能:

开始时,输入x,不能自动补全

RestAPI实现自动补全:

(1)在controller层写好接口

1
2
3
4
@GetMapping("suggestion")
public List<String> getSuggestions(@RequestParam("key") String predix){
return hotelService.getSuggestions(predix);
}

(2)在service层写好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Override
public List<String> getSuggestions(String predix) {
try {
//1.准备Request
SearchRequest request = new SearchRequest("hotel");
//2.准备DSL
request.source().suggest(new SuggestBuilder().addSuggestion(
"suggestions",
SuggestBuilders.completionSuggestion("suggestion")
.prefix(predix)
.skipDuplicates(true)
.size(10)
));
//3.发起请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);

//4.解析结果
Suggest suggest = response.getSuggest();
//4.1 根据补全查询名称,获取更全的结果
CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
//4,2 获取options
List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
//4.3 遍历
List<String> list = new ArrayList<String>(options.size());
for( CompletionSuggestion.Entry.Option option : options){
String text = option.getText().toString();
System.out.println(text);
list.add(text);
}
return list;
} catch (IOException e) {
throw new RuntimeException();
}
}

(3)重新启动项目

便可以进行自动补全了