概述
在使用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(); } }
|