How to perform filter with condition?

In SQL:

select * from my_index where type in ('a', 'b') and (type <> 'a' or value_field = 'sth')

Filter by field value_field when type is 'a'. Using script:

{
    "query": {
        "bool": {
            "filter": [
                {
                  "terms": {
                    "type": [
                      "a",
                      "b"
                    ]
                  }
                },
                {
                  "script": {
                    "script": {
                      "source": "return doc['type'].value != 'a' || doc['value_field'].value == params['val']",
                      "params": {
                        "val": "sth"
                      }
                    }
                  }
                }
            ]
    }
}

Any other way to do this without script?

Hi @_Zhang

Try this:

{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "type": ["a", "b"]
          }
        }
      ],
      "should": [
        {
          "bool": {
            "must_not": {
              "term": {
                "type": "a"
              }
            }
          },
          {
            "term": {
              "value_field": "sth"
            }
          }
        ],
      "minimum_should_match": 1
    }
  }
}
1 Like

Hello, @RabBit_BR . Should I put the should clause into filter as there are other should clauses? A nested bool query like this: { query: { bool: { filter: { bool: [ { filter: {...} }, should: {...} ] } } } }