elasticsearch-dsl-py icon indicating copy to clipboard operation
elasticsearch-dsl-py copied to clipboard

Two different ways to combine queries give different results

Open oren0e opened this issue 1 year ago • 7 comments

q_complex = (Q({"range": {"num_errors": {"gte": 4}}}) & Q({"range": {"num_errors": {"lte": 6}}})) | Q({"match": {"num_errors": 2}})
q_a = Q({"range": {"num_errors": {"gte": 4}}})
q_b = Q({"range": {"num_errors": {"lte": 6}}})
q_c = Q({"match": {"num_errors": 2}})
q_complex1 = Q("bool",
               must=[q_a, q_b],
               should=[q_c],
               )

q_complex is:

{'bool': {'should': [{'bool': {'must': [{'range': {'num_errors': {'gte': 4}}}, {'range': {'num_errors': {'lte': 6}}}]}}, {'match': {'num_errors': 2}}]}}

and q_complex1 is:

{'bool': {'must': [{'range': {'num_errors': {'gte': 4}}}, {'range': {'num_errors': {'lte': 6}}}], 'should': [{'match': {'num_errors': 2}}]}}

I expect them to be equivalent since the second way of combining the queries is documented as:

If you want to have precise control over the query form, use the Q shortcut to directly construct the combined query

Basically I want to achieve the dict of q_complex with the q_complex1 way of writing queries.

I have a situation where I need to preserve the order given by an existence of parentheses but I need to be able to construct this with the second way (Q("bool", must=..., should=...) - how can I do it?

oren0e avatar Jun 29 '23 14:06 oren0e