问题
I am using the Completition suggester for an auto complete App in Java, I was able to extract the suggest text from the Search response using the JAVA api. While checking the raw response I saw that suggest response contain the _source data (complete document instead of just the Suggest string). How to extract the source data from the Suggest Search response ?
Please find below the Code I have used to get the suggested text -
SearchRequest searchRequest = new SearchRequest("my_entitiy");
CompletionSuggestionBuilder suggestionBuilder = new CompletionSuggestionBuilder("nameSuggest");
suggestionBuilder.size(10).prefix(input).skipDuplicates(true);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.suggest(
new SuggestBuilder().addSuggestion(SUGGESTION_NAME, suggestionBuilder));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = elasticClient.search(searchRequest, RequestOptions.DEFAULT);
Suggest suggest = searchResponse.getSuggest();
Suggest.Suggestion<Suggest.Suggestion.Entry<Suggest.Suggestion.Entry.Option>> suggesition =
suggest.getSuggestion(SUGGESTION_NAME);
List<String> suggestionList = new ArrayList<>();
for (Suggest.Suggestion.Entry<Suggest.Suggestion.Entry.Option> entry : suggesition.getEntries()) {
for(Suggest.Suggestion.Entry.Option option:entry.getOptions()){
suggestionList.add(option.getText().toString());
}
}
In the Option few methods are available to extract the score, text and highlighted. Is it possible to get the _source data from the option ? I saw a toXContent function is it possible to use that to get the source data ?
Above snippet is saving the Suggested string to a list I was wondering whether it's possible to get the complete Doc JSON.
回答1:
You can always make use of source filtering to filter the fields to be returned in search results. In elastic you can do so adding includes
, excludes
or both in _source
context. For e.g. you want only to get field1
and field2
, the you can set the _source
as below along with query:
{
"query":{
// your query goes here
},
"_source":{
"includes":["field1", "field2"]
}
}
Using high level rest client the same can be achieved as below:
String[] includes = {"field1", "field2"};
searchSourceBuilder.fetchSource(new FetchSourceContext(true, includes, null));
回答2:
You can use the fetch source API of JHLRC (java high level rest client) which is the official java client of Elasticsearch.
As per the link
This API helps to get only the _source field of a document.
You can get the id from your previous response and then use to get the source of those documents.
GetSourceRequest getSourceRequest = new GetSourceRequest(
"posts",
"1");
Above the sample from Elastic and , where posts
is the index name and 1
is the doc id.
来源:https://stackoverflow.com/questions/62192624/extract-the-source-data-from-elastic-search-suggest-search-response-using-java-a