0
votes

I'm struggling with writing an elastic search query with multiple AND/OR conditions.

It basically comes to the following logic: cond1 && (cond2 || cond3 || cond4)

As mentioned in the docs, a document is considered a match if it satisfies only the must clause. The should clauses in this case act as a boost i.e. if a document matches one or more of the should clauses in addition to the must clause, then it will have a higher relevancy score, assuming that cond2, cond3 and cond4 are queries that calculate a relevancy score.

The problem is that I only want documents that also match at least one of the OR conditions.

Note that I'm running ES6.3. I've also tried Multiword queries but these results are also wrong.

Adding boost doesn't seem to affect the results, I have results that only match the first condition.

{
    "query": {
        "bool": {
            "must": [
              {
                    "term": {
                        "event.keyword": {
                            "value": "webhook.trigger"
                        }
                    }
                }
            ],
            "should": [
                {
                    "match": {
                        "metaData.webhook.title": "My Example Title 1"
                    }
                },
                {
                    "match": {
                        "metaData.webhook.title": "Testing"
                    }
                },
{
                    "match": {
                        "metaData.webhook.url": "myurl.com"
                    }
                }
            ]
        }
    }
}
1

1 Answers

2
votes

A should query works like a OR only if there is not a must query. In your case you should wrap the should query in another bool query.

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "event.keyword": {
                            "value": "webhook.trigger"
                        }
                    }
                },
                {
                    "bool": {
                        "should": [
                            {
                                "match": {
                                    "metaData.webhook.title": "My Example Title 1"
                                }
                            },
                            {
                                "match": {
                                    "metaData.webhook.title": "Testing"
                                }
                            },
                            {
                                "match": {
                                    "metaData.webhook.url": "myurl.com"
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}```