Search code examples
python-3.xelasticsearchelasticsearch-dsl

IF condition in Elasticsearch DSL


I am new to Elasticsearch and I have an ELS index "student" with the following query. I need to execute the student.name only when the is_rep=True.

Note: is_rep field will not be available explicitly

"query": {
  "bool": {
    "must": { "term": { "subject": "maths" }} ,
    "must": { "term": { "student.name": "xyz"}}
   }
}

Can anyone please guide me to achieve this


Solution

  • I would do something like this:

    {
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "subject": "maths"
              }
            },
            {
              "bool": {
                "minimum_should_match": 1,
                "should": [
                  {
                    "term": {
                      "is_rep": false
                    }
                  },
                  {
                    "bool": {
                      "filter": [
                        {
                          "term": {
                            "student.name": "xyz"
                          }
                        },
                        {
                          "term": {
                            "is_rep": true
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }