panipsilos
panipsilos

Reputation: 2209

How to enable elasticsearch auto-complete return only matching word

I need to implement auto-complete but I m not sure about the exact strategy. For example I have the following product :

Highsound Smart Phone Watch for Android (Gray)

So I need when the user starts typing: "s", "sm", "smar" , the word "smart" or "smart watch" to come out rather than the whole phrase: Highsound Smart Phone Watch for Android (Gray)

I looked around how google, amazon etc. do it and they dont display the whole matching record, but rather they display either only the word ("smart") or a phrase ("smart watch").

Right now I enable the automcomplete in elasticsearch according to the following link, but it returns the whole name of the matching record.

https://www.elastic.co/guide/en/elasticsearch/guide/current/_index_time_search_as_you_type.html

Any suggestions?

Upvotes: 2

Views: 321

Answers (1)

ChintanShah25
ChintanShah25

Reputation: 12672

This is expected. You get back what is inside _source field. You can use highlighting to get back only the word that was matched.

{
  "query": {
    "match_phrase": {
      "name": "sm"
    }
  },
  "highlight": {
    "fields": {
      "name": {
        "fragment_size": 1,
        "number_of_fragments": 2
      }
    }
  }
}

I have used number_of_fragments : 2 in case there are more than one word starting with sm. You can also change fragment size according to your needs. More on that.You will get something like this, then you can use highlight part for the frontend.

"hits": {
    "total": 1,
    "max_score": 0.6349302,
    "hits": [
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "5",
        "_score": 0.6349302,
        "_source": {
          "name": "Highsound Smart Phone Watch for Android (Gray)"
        },
        "highlight": {
          "name": [
            " <em>Smart</em>"
          ]
        }
      }
    ]
  }

Upvotes: 1

Related Questions