suggest字段并没有像其他字段那样展示出来,说明它和其他字段是不一样的。现在我们如果只输入一个“天”字,看看搜索建议能不能给出提示,如下:
POST /my_suggester/_search { "suggest": { "s-test": { "prefix": "天", "completion": { "field": "suggest" } } } }在请求体中,suggest就是“搜索建议”的标识,s-test是自定义的一个名称,prefix是前缀,也就是我们输入的“天”字,completion指定搜索建议的字段,我们看看查询的结果,
…… "suggest": { "s-test": [ { "text": "天", "offset": 0, "length": 1, "options": [{ "text": "天气", "_index": "my_suggester", "_type": "_doc", "_id": "QtgAWnIBOZNtuLQtJgpt", "_score": 1, "_source": { "title": "天气","desc": "今天天气不错","suggest": { "input": "天气"}} } , { "text": "天空", "_index": "my_suggester", "_type": "_doc", "_id": "T9gAWnIBOZNtuLQtWQoX", "_score": 1, "_source": { "title": "天空","desc": "蓝蓝的天空,白白的云","suggest": { "input": "天空"}} } ] } ] }在s-test.options里,包含了两条记录,text字段就是我们写的建议字段,后面_source里还包含对应的数据,下面我们再看看程序里怎么使用“搜索建议”,
public void searchSuggest(String prefix) throws IOException { SearchRequest searchRequest = new SearchRequest("my_suggester"); SearchSourceBuilder ssb = new SearchSourceBuilder(); CompletionSuggestionBuilder suggest = SuggestBuilders .completionSuggestion("suggest") .prefix(prefix); SuggestBuilder suggestBuilder = new SuggestBuilder(); suggestBuilder.addSuggestion("s-test",suggest); ssb.suggest(suggestBuilder); searchRequest.source(ssb); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); CompletionSuggestion suggestion = response.getSuggest().getSuggestion("s-test"); for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) { System.out.println(option.getText().string()); } } @Test public void searchSuggest() throws IOException { eService.searchSuggest("天"); }我们创建了CompletionSuggestionBuilder,通过方法completionSuggestion指定“搜索建议”字段suggest,并且指定前缀为方法传入的prefix,我们在测试的时候传入"天"字。然后,我们自定义“搜索建议”的名字为s-test,传入前面构造好的suggest。
发送请求后,在响应中获取前面自定义的s-test,然后循环options,取出text字段,这就是搜索建议的字段,我们运行一下,看看结果,
天气 天空完全符合预期,这样用户在搜索的时候,就会给出提示信息了。
好了,今天这两个ES的知识点就全部OK了~ 大家有问题在评论区留言。