ElasticSearch: Labelling documents with matching search term ElasticSearch: Labelling documents with matching search term elasticsearch elasticsearch

ElasticSearch: Labelling documents with matching search term


If you're ready to switch to using bool/should queries, you can split the match on each field and use named queries, then in the results you'll get the name of the query that matched.

It goes basically like this: in a bool/should query, you add one query_string query per field and name the query so as to identify that field (e.g. title_query for the title field, etc)

{  "query": {    "bool": {      "should": [        {          "query_string": {            "fields": [              "title^10"            ],            "query": "query_string",            "use_dis_max": false,            "_name": "title_query"          }        },        {          "query_string": {            "fields": [              "keywords^4"            ],            "query": "query_string",            "use_dis_max": false,            "_name": "keywords_query"          }        },        {          "query_string": {            "fields": [              "content"            ],            "query": "query_string",            "use_dis_max": false,            "_name": "content_query"          }        }      ]    }  }}

In the results, you'll then get below the _source another array called matched_queries which contains the name of the query that matched the returned document.

"_source": {    ...},"matched_queries": [    "title_query"],