Search code examples
elasticsearchelasticsearch-dsl

Return which field got matched in Elastic Search


I am trying to find out what actually got matched for a search in a specific for which the doc is returned.

Ex. I have a table index where there are fields called table_name and column_name... My search query is finding both those fields, now If I fire a search query and any one of them gets matched ,but I want to know what got matched .. whether its column_name or the table_name.

I am aware of the Explain API but that will require me to call another API...


Solution

  • You don't need to call the explain API. The search API supports the explain flag

    GET stackoverflow/_search?explain=true
    

    This will return the _explanation section along with the _source section.

    Update

    Another solution would be to use highlight. I've used this before, for manually evaluating queries. It's an easy way to get some feedback on what matched

    GET stackoverflow/_search
    {
      "query": {
        "match": {
          "FIELD": "TEXT"
        }
      },
      "highlight": {
        "fields": {
          "*": {}
        }
      }
    }
    

    Of course, you can have the explain flag set as well