问题
I was trying to search the following two cases
case 1:
I want to search a name that starts with particular word. For example:
name : test name
name : name test
name : test name test
if I search for "test" then it should return me only "test name" and "test name test".
case 2:
I want to search a name that ends with a particular word. For example:
name : test name
name : name test
name : test name test
if I search for "test" then it should return me only "name test" and "test name test" .
Can anyone help me find out queries in elasticsearch java API or any other way to search it.
Elastic search version 6.2.1
Any help is really appreciated.
回答1:
you need to use mapping with search_analyzer
property (analyzer_startswith or analyzer_endswith)
"mappings": {
"some_index": {
"properties": {
"title": {
"search_analyzer": "analyzer_startswith",
"index_analyzer": "analyzer_startswith",
"type": "string"
}
}
}
}
something like
回答2:
For case 1, you can use CompletionSuggester
. You need a special mapping for a field to use completion suggester, like this:
"mappings": {
"some_index": {
"properties": {
"title": {
"type": "completion"
}
}
}}
In the code, you should define the suggester, like this (term
is your searchword, "starts" is an arbitrary name):
CompletionSuggestionBuilder completionBuilder = SuggestBuilders.completionSuggestion("title").prefix(term);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("starts", completionBuilder);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.suggest(suggestBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(searchSourceBuilder);
After you get the search response, process it to retrieve the suggestions:
Suggest suggest = searchResponse.getSuggest();
if (suggest == null) {
return Collections.emptyList();
} else {
CompletionSuggestion suggestion = suggest.getSuggestion("starts");
return suggestion
.getOptions()
.stream()
.map(CompletionSuggestion.Entry.Option::getText)
.map(Text::toString)
.collect(Collectors.toList());
}
来源:https://stackoverflow.com/questions/48921481/how-to-search-starting-and-ending-of-a-sentence-in-elasticsearch