0
votes

What if I use query in filter clausses in elasticsearch? Will ES calculate score? For example, case 1:

{
    "query": {
        "bool": {
            "filter": {
                "bool":{
                    "should":{
                        
                    }
                }
            }
        }
    }
}

case 2:

{
    "query": {
        "bool": {
            "should": {
                "bool":{
                    "filte":{
                        
                    }
                }
            }
        }
    }
}

Will ES calculate scores in these two case?

2

2 Answers

0
votes

in Elasticsearch each query under the filter section would not be involved in score calculation. It means that in both of your queries if you add your logic inside of the filter, Elasticsearch won't calculate the score. But if you add some part of your logic in the must, should or must_not section, Elasticsearch will calculate the score.

0
votes

The filter clause (query) must appear in matching documents. However, unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

Refer to this elasticsearch documentation on bool queries, to know more about this

Adding a working example with index data, search query, and search result

Index data:

{
  "name": "milk",
  "cost": 40
}
{
  "name": "bread",
  "cost": 55
}

Search Query 1:

In this, the inner bool query is wrapped in the outer filter clause, so the scoring of the should clause is ignored

{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "should": {
            "match": {
              "name": "bread"
            }
          }
        }
      }
    }
  }
}

Search Result 1:

"hits": [
      {
        "_index": "64505740",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.0,
        "_source": {
          "name": "bread",
          "cost": 55
        }
      }
    ]

Search Query 2:

In this, the inner bool query is wrapped in the filter clause, so the outer bool should clause, will not make any difference to the score

{
  "query": {
    "bool": {
      "should": {
        "bool": {
          "filter": {
            "term": {
              "name": "bread"
            }
          }
        }
      }
    }
  }
}

Search Result 2:

"hits": [
      {
        "_index": "64505740",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.0,
        "_source": {
          "name": "bread",
          "cost": 55
        }
      }
    ]

So both of your search queries will return a 0.0 score, meaning that the scoring is ignored due to the filter clause