Search code examples
elasticsearchsearchautocompleteluceneelk

Elasticsearch query: Fetch all the results which prefix matches the query for typeahead, autocomplete feature


query
what is my name
what is google
what is stackoverflow
how to search

So, I would like to have an Elasticsearch Index which has documents as above. I would like to fetch all the results which prefix matches the query. For example, when queried for "what is", I need {"what is my name", "what is google", "what is stackoverflow"} as results, exact prefix match.

How do I go about creating an index? and Example queries, if possible.

Thanks in advance.


Solution

  • There are multiple ways to achieve what you want, but simplest is to use the prefix query, if you just index your data directly to Elasticsearch without defining mapping, it will automatically create two fields for you, and on .keyword field you can use the prefix query as shown below.

    Index sample documents

    PUT <your-es-index>/_doc/1
    
    {
        "title" : "what is my name"
    }
    
    PUT <your-es-index>/_doc/2
    
    {
        "title" : "what is google"
    }
    
    PUT <your-es-index>/_doc/3
    
    {
        "title" : "what is stackoverflow"
    }
    
    PUT <your-es-index>/_doc/4
    
    {
        "title" : "how to search"
    }
    

    Search query

    POST /_search

    {
        "query": {
            "prefix": {
                "title.keyword": {
                    "value": "what is"
                }
            }
        }
    }
    

    Your expected search results

    "hits": [
                {
                    "_index": "72391510",
                    "_id": "1",
                    "_score": 1.0,
                    "_source": {
                        "title": "what is my name"
                    }
                },
                {
                    "_index": "72391510",
                    "_id": "2",
                    "_score": 1.0,
                    "_source": {
                        "title": "what is google"
                    }
                },
                {
                    "_index": "72391510",
                    "_id": "3",
                    "_score": 1.0,
                    "_source": {
                        "title": "what is stackoverflow"
                    }
                }