Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

建议查询功能实现 #1040

Open
tianxia0079 opened this issue Jan 14, 2024 · 0 comments
Open

建议查询功能实现 #1040

tianxia0079 opened this issue Jan 14, 2024 · 0 comments

Comments

@tianxia0079
Copy link

以下是7版本的代码,可是换成8网上找不到最新版本的教程。麻烦实现参考以下。谢谢

public class ElasticsearchClient {

    private static final String INDEX_NAME = "my_index";
    private static final String FIELD_NAME = "suggestion_field";
    private RestHighLevelClient client;

    public ElasticsearchClient(String hostname, int port) {
        client = new RestHighLevelClient(
            RestClient.builder(new HttpHost(hostname, port, "http")));
    }

    public List<String> getSuggestions(String input) throws IOException {
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder(FIELD_NAME);
        completionSuggestionBuilder.prefix(input);
        completionSuggestionBuilder.size(5); // Limit the number of suggestions

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

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

        Suggest suggest = searchResponse.getSuggest();
        CompletionSuggestion suggestion = suggest.getSuggestion("suggest");

        List<String> suggestions = suggestion
            .getEntries()
            .stream()
            .flatMap(e -> e.getOptions().stream())
            .map(option -> option.getText().string())
            .collect(Collectors.toList());

        return suggestions;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant