1

I want to write a simple query in ElasticSearch, that in pseudocode looks like this: WHERE X==A and (Y in (Y1, Y2) or Y is undefined). This is the query that I can come up with that works:

GET sales-staging/_search?filter_path=hits.hits._source
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "A": "X"
          }
        }
      ],
      "should": [
        {
          "terms": {
            "B": [
              "Y1", 
              "Y2"
            ]
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "C"
                }
              }
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

I expect these documents to match:

{
    "A": "X",
    "B": "Y1"
},
{
    "A": "X"
}

and these ones to not match:

{
    "A": "X",
    "B": "Y3"
},
{
    "A": "Z",
    "B": "Y1"
},
{
    "A": "Z"
}

However, this is a quite hefty multiline query for such a simple query, and I have the feeling I am misusing the minimum_should_match parameter to write a simple OR query. Am I overlooking a simpler way?

I looked at SO:

And on the documentation pages:

But couldn't find the answer there either.

physicalattraction
  • 6,485
  • 10
  • 63
  • 122
  • The query looks correct to me (kudos). Now can you show a sample document that you expect to match? – Val May 02 '18 at 10:59
  • I added them in the question. The query is indeed behaving as expecting, the thing is that I find it hard to believe that this is the easiest way. – physicalattraction May 02 '18 at 12:38
  • Well, you've correctly translated AND/OR using bool/must/should. Not sure how easier it can get. The Search DSL is a bit more verbose than SQL for sure, but you've pretty much nailed it. – Val May 02 '18 at 12:40

0 Answers0