Search code examples
elasticsearchelasticsearch-queryelasticsearch-nested

Matching the stored values and queries in Elastic Search


I have a field called that is inside a nested field "name" that is a "Keyword" in elastic search.

Name field contains 2 values.

  1. Jagannathan Rajagopalan
  2. Rajagopalan.

If I query "Rajagopalan", I should get only the item #2. If I query the complete Jagannathan Rajagopalan, I should get #1.

How do I achieve it?


Solution

  • You need to use the term query which is used for exact search. Added a working example according to your use-case.

    Index mapping

    {
        "mappings": {
            "properties": {
                "name": {
                    "type": "nested",
                    "properties": {
                        "keyword": {
                            "type": "keyword"
                        }
                    }
                }
            }
        }
    }
    

    Index sample docs

    {
        "name" : {
            "keyword" : "Jagannathan Rajagopalan"
        }
    }
    

    And another doc

    {
        "name" : {
            "keyword" : "Jagannathan"
        }
    }
    

    And search query

    {
        "query": {
            "nested": {
                "path": "name",
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match": {
                                    "name.keyword": "Jagannathan Rajagopalan"
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
    

    Search result

       "hits": [
                {
                    "_index": "key",
                    "_type": "_doc",
                    "_id": "2",
                    "_score": 0.6931471,
                    "_source": {
                        "name": {
                            "keyword": "Jagannathan Rajagopalan"
                        }
                    }
                }
            ]