How to use filter using constant_score with another query bool


(Bakhtiyor Homidov) #1

for example i've the query, and want to re-write the query using constant_score for filter.

{
  "query": {
    "bool": {
      "must": [{ "term": { "slug": "awe2ome" } }],
      "must_not": [{ "term": { "slug": "not_awe2ome" } }],
      "should": [{ "term": { "title": "title" } }],
      "filter": [{ "term": { "is_deleted": false } }],
      "minimum_should_match": 1
    }
  }
}

i know the below example is wrong format.
how to re-write the example with right format?

{
  "query": {
    "bool": {
      "must": [{ "term": { "slug": "awe2ome" } }],
      "must_not": [{ "term": { "slug": "not_awe2ome" } }],
      "should": [{ "term": { "title": "title" } }],
      "minimum_should_match": 1
    },
    "constant_score": {
      "filter": {
        "bool": {
          "must": [{ "term": { "is_deleted": false } }]
        }
      }
    }
  }
}

(Gautam Vanani) #2

I'm not elastic search expert but example-1 constant_score query behaves in exactly the same way as the second example. The constant_score query assigns a score of 1.0 to all documents matched by the filter here.

example-1

{
    "query": {
     "constant_score": {
       "filter": {
         "term": {
           "status": "active"
         }}
       }
   }
}

example-2

{
  "query": {
      "bool": {
        "filter": {
           "term": {
               "status": "active"
            }
        }
      }
  }
}

so You can use it like,

{
  "query": {
    "bool": {
     "must": [{ "term": { "slug": "awe2ome" } }],
      "must_not": [{ "term": { "slug": "not_awe2ome" } }],
      "should": [{ "term": { "title": "title" } }],
      "minimum_should_match": 1,
      "filter": {
        "bool": {
          "must": [{ "term": { "is_deleted": false } }]
        }
      }
    }
  }
}

(system) #3