elasticsearchelasticsearch-6

Elasticsearch: How to write an 'OR' clause in filter context?


I'm looking for syntax/example compatible with ES version is 6.7. I have seen the docs, I don't see any examples for this and the explanation isn't clear enough to me. I have tried writing query according to that, but I keep on getting syntax error. I have seen below questions on SO already but they don't help me:

Filter context for should in bool query (Elasticsearch)

It doesn't have any example.

Multiple OR filter in Elasticsearch

I get a syntax error

"type": "parsing_exception",
"reason": "no [query] registered for [filtered]",
"line": 1,
"col": 31

Maybe it's for a different version of ES.

All I need is a simple example with two 'or'ed conditions (mine is one range and one term but I guess that shouldn't matter much), both I would like to have in filter context (I don't care about scores, nor text search).

If you really need it, I can show my attempts (need to remove some 'sensitive'(duh) parts from it before posting), but they give parsing/syntax errors so I don't think there is any sense in them. I am aware that questions which don't show any efforts are considered bad for SO but I don't see any logic in showing attempts that aren't even parsed successfully, and any example would help me understand the syntax.


Solution

  • I had a similar scenario (even the range and match filter), with one more nested level, two conditions to be 'or'ed (as in your case) and another condition to be logically 'and'ed with its result. As @Pierre-Nicolas Mougel suggested in another answer I had nested bool clauses with one more level around the should clause.

    {
      "_source": [
        "my_field"
      ],
      "query": {
        "bool": {
          "filter": {
            "bool": {
              "must": [
                {
                  "bool": {
                    "should": [
                      {
                        "range": {
                          "start": {
                            "gt": "1558878457851",
                            "lt": "1557998559147"
                          }
                        }
                      },
                      {
                        "range": {
                          "stop": {
                            "gt": "1558898457851",
                            "lt": "1558899559147"
                          }
                        }
                      }
                    ]
                  }
                },
                {
                  "match": {
                    "my_id": "<My_Id>"
                  }
                }
              ],
              "must_not": []
            }
          }
        }
      },
      "from": 0,
      "size": -1,
      "sort": [],
      "aggs": {}
    }
    

    I read in the docs that minimum_should_match can be used too for forcing filter context. This might help you if this query doesn't work.