elasticsearchelasticsearch-queryterm-query

why does elasticsearch calculates score for term queries?


I want to make a simple query based on knowing a unique field value using a term query. For instance:

{
  "query": {
    "term": {
      "products.product_id": {
        "value": "Ubsdf-234kjasdf"
      }
    }
  }
}

Regarding term queries, Elasticsearch documentation states:

Returns documents that contain an exact term in a provided field. You can use the term query to find documents based on a precise value such as a price, a product ID, or a username.

On the other hand, documentation also suggests that the _score is calculated for queries where relevancy matters (and is not the case for filter context which involves exact match).

I find it a bit confusing. Why does Elasticsearch calculates _score for term queries which are supposed to be concerned with exact match and not relevancy?


Solution

  • term queries are not analyzed, hence they would not go with the analysis phase, hence used for an exact match, but their score is still calculated when used in query context.

    When you use term queries in filter context, then it means you are not searching on them, and rather doing filtering on them, hence there is no score calculated for them.

    More info on query and filter context in official ES doc.

    Both the example of term query in filter and query context shown in my below example

    Term query in query context

    {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "title": "c"
                        }
                    }
                ]
            }
        },
        "size": 10
    }
    

    And result with a score

    "hits": [
                {
                    "_index": "cpp",
                    "_type": "_doc",
                    "_id": "4",
                    "_score": 0.2876821, --> notice score is calculated
                    "_source": {
                        "title": "c"
                    }
                }
            ]
    

    Term query in filter context

    {
        "query": {
            "bool": {
                "filter": [ --> prev cluase replaced by `filter`
                    {
                        "term": {
                            "title": "c"
                        }
                    }
                ]
            }
        },
        "size": 10
    }
    

    And search result with filter context

     "hits": [
                {
                    "_index": "cpp",
                    "_type": "_doc",
                    "_id": "4",
                    "_score": 0.0, --> notice score is 0.
                    "_source": {
                        "title": "c"
                    }
                }
            ]