Home > OS >  In Elasticsearch, how do I combine multiple filters with OR without affecting the score?
In Elasticsearch, how do I combine multiple filters with OR without affecting the score?

Time:09-22

In Elasticsearch, I want to filter my results with two different clauses aggregated with OR e.g. return documents with PropertyA=true OR PropertyB=true.

I've been trying to do this using a bool query. My base query is just a text search in must. If I put both clauses in the filter occurrence type, it aggregates them with an AND. If I put both clauses in the should occurrence type with minimum_should_match set to 1, then I get the right results. But then, documents matching both conditions get a higher score because "should" runs in a query context.

How do I filter to only documents matching either of two conditions, without increasing the score of documents matching both conditions?

Thanks in advance

CodePudding user response:

You need to leverage the constant_score query, so everything runs in the filter context:

{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "minimum_should_match": 1,
          "should": [
            {
              "term": {
                "PropertyA": true
              }
            },
            {
              "term": {
                "PropertyB": true
              }
            }
          ]
        }
      }
    }
  }
}
  • Related