Spring Boot Elasticsearch搜索建议查询

概述

在使用Elasticsearch中,我们需要在客户输入的时候,自动提示输入建议(搜索补全),类型百度搜索选择。

本文示例介绍通过Spring Boot来实现Elasticsearch

es实例类

需要在实例类中,增加Completion属性,用于存储关键词。

1
2
@CompletionField(maxInputLength = 100)
private Completion suggest;

存储到es时处理

把需要的属性关键字,存储到suggest

1
2
3
List<String> suggestlist =  new ArrayList<>();

esPojo.setSuggest(new Completion(suggestlist.toArray(new String[suggestlist.size()])));

调用代码

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
35
36
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;


@org.junit.Test
public void suggestion() {
try {
String keyword = "en_Sili";

//构造搜索建议语句,搜索条件字段
CompletionSuggestionBuilder completionSuggestionBuilder = SuggestBuilders.completionSuggestion("suggest");
//搜索关键字
completionSuggestionBuilder.prefix(keyword);
//去除重复
completionSuggestionBuilder.skipDuplicates(true);
//匹配数量
completionSuggestionBuilder.size(20);

SearchRequestBuilder searchRequestBuilder =elasticsearchTemplate.getClient().prepareSearch("item_index").setTypes("item");

//根据
SearchResponse suggestResponse = searchRequestBuilder.suggest(new SuggestBuilder().addSuggestion("my-suggest",completionSuggestionBuilder)).get();
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("my-suggest");

List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();

List<String> suggestList = new ArrayList<>();
options.forEach(item ->{ suggestList.add(item.getText().string()); });

for (String string : suggestList) {
System.err.println(string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
FallSea wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!