How to search starting and ending of a sentence in elasticsearch

守給你的承諾、 提交于 2019-12-24 22:18:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!