ElasticSearch Java高级Rest客户端:建议搜索

时间:2018-12-17 21:21:05

标签: java elasticsearch

我如何进行这样的查询:

{
  "suggest": {
    "my_index_suggest": {
      "prefix": value,
      "completion": {
        "field": "suggest_field",
        "fuzzy": {
          "fuzziness" : 1
        },
        "size": 5
      }
    }
  }
}

使用Java High Level Rest Client?我不确定是否应该使用SuggestionBuilder或QueryBuilder。

在一分钟内用JS或Python完成的事情再次是Java的冒险

1 个答案:

答案 0 :(得分:0)

好的,这是我自己的解决方案:

public List<String> getSuggestion(String input) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    SuggestionBuilder termSuggestionBuilder = SuggestBuilders.completionSuggestion("my_index_suggest").text(input);

    SuggestBuilder suggestBuilder = new SuggestBuilder();
    suggestBuilder.addSuggestion("suggest_field", termSuggestionBuilder);
    searchSourceBuilder.suggest(suggestBuilder);

    SearchRequest searchRequest = new SearchRequest();
    searchRequest.source(searchSourceBuilder);

    SearchResponse searchResponse = suggestionIndexClient.search(searchRequest, RequestOptions.DEFAULT);
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(searchResponse.getSuggest().iterator(), Spliterator.ORDERED), false)
            .flatMap(suggestion -> suggestion.getEntries().get(0).getOptions().stream())
            .map((Suggest.Suggestion.Entry.Option option) -> option.getText().toString())
            .collect(Collectors.toList());
}

如果您不喜欢Streams,请随时使用“建议”的通用怪物性以及没有人要求的while循环:

    Iterator<Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>> iterator = searchResponse.getSuggest().iterator();
    Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestion;

    List<String> resultList = null;
    while (iterator.hasNext()) {
        suggestion = iterator.next();
        resultList = fn.getEntries().get(0).getOptions().stream()
            .map((Suggest.Suggestion.Entry.Option option) -> option.getText().toString())
            .collect(Collectors.toList());
    }

    return resultList;