0

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.

Raviteja Gannoju
  • 117
  • 3
  • 16
  • I once asked a similar question, majestically answered by our good Elastic friend @AndreiStefan. You can find it [here](https://stackoverflow.com/questions/30666371/how-to-wisely-combine-shingles-and-edgengram-to-provide-flexible-full-text-searc) – Val Feb 22 '18 at 13:11

2 Answers2

0

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

IanGabes
  • 2,652
  • 1
  • 19
  • 27
Adam Bremen
  • 685
  • 1
  • 7
  • 18
0

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());
  }
manuna
  • 729
  • 14
  • 37