Search code examples
elasticsearchelasticsearch-querydismax

Elasticsearch dis_max query, return exact matching query


Lets assume i want to perform this query

GET /_search
{
"query": {
    "dis_max" : {
        "queries" : [
            { "term" : { "title" : "Quick pets" }},
            { "term" : { "body" : "Quick pets" }}
        ],
        "tie_breaker" : 0.7
    }
}

}

According to the documentation of elasticsearch, this query returns a list of documents with the highest relevance score from any matching clause.

But how can i determine which underlying query caused the document to appear in the result list? How can i determine if a result appears due to query 1 or query 2 in the list of queries? Can i somehow return this for each result document?


Solution

  • You can use named queries

    Query:

    {
      "query": {
        "dis_max": {
          "queries": [
            {
              "term": {
                "title.keyword": {
                  "value": "Quick pets",
                  "_name": "title" --> give name for each query
                }
              }
            },
            {
              "term": {
                "body.keyword": {
                  "value": "Quick pets",
                  "_name": "body"
                }
              }
            }
          ],
          "tie_breaker": 0.7
        }
      }
    }
    

    Result:

    "hits" : [
          {
            "_index" : "index55",
            "_type" : "_doc",
            "_id" : "mAGWNXIBrjSHR7JVvY4C",
            "_score" : 0.6931471,
            "_source" : {
              "title" : "Quick pets"
            },
            "matched_queries" : [
              "title"
            ]
          },
          {
            "_index" : "index55",
            "_type" : "_doc",
            "_id" : "mQGXNXIBrjSHR7JVGI4E",
            "_score" : 0.2876821,
            "_source" : {
              "title" : "ddd",
              "body" : "Quick pets"
            },
            "matched_queries" : [
              "body"
            ]
          }
        ]