如何使用 Elasticsearch java api 进行短语建议查询?

How can I make phrase suggester query with Elasticsearch java api?

我正在使用 7.10。弹性搜索版本。我创建了一个索引并进行了设置映射。然后我使用 http 请求将查询发送到索引。我得到了我需要的结果,但我想用 Java API 做同样的事情。然而,我做不到。 你能帮我发送请求并从头开​​始得到 java 中列出的结果吗?

这是我用来获取建议的查询:

{
  "suggest": {
    "text": "some title I want to search",
    "phrase_suggester": {
      "phrase": {
        "field": "title.shingle",
                "max_errors": 2,
                "size": 5,
                "confidence": 0.0,
                "direct_generator": [{
                    "field": "title.shingle",
                    "max_edits": 2
          }
        ]
      }
    }
  }
}

如何使用 Elasticsearch 编写此查询 Java API。你能帮我解决这个问题吗?

这将是构建请求的方式:

    client.search(searchRequestBuilder -> searchRequestBuilder 
        .suggest(suggestBuilder -> suggestBuilder 
                .text("some title I want to search")
                .suggesters("phrase_suggester", fieldSuggesterBuilder -> fieldSuggesterBuilder 
                        .phrase(phraseBuilder -> phraseBuilder.field("title.shingle")
                                .maxErrors(2d) 
                                .size(5) 
                                .confidence(0.0) 
                                .directGenerator(directGeneratorBuilder -> directGeneratorBuilder 
                                        .field("title.shingle") 
                                        .maxEdits(2))))),
        YourEntity.class);

对了,新客户端是7.16的,你写的是7.14?

我终于找到了自己的答案。由于缺少有关此类特定主题的文档,因此很难找到解决方案。我正在为那些想知道的人分享我的解决方案:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

PhraseSuggestionBuilder builder = SuggestBuilders.phraseSuggestion("title.shingle")
                .addCandidateGenerator(new DirectCandidateGeneratorBuilder("title.shingle")
                        .suggestMode("always"))
                .text(query)
                .maxErrors(2f)
                .confidence(0f);

        SuggestBuilder suggestBuilder = new SuggestBuilder().addSuggestion("suggestion", builder);
        searchSourceBuilder.suggest(suggestBuilder);

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("index_name");
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);