Operator precedence


#1

I’ve searched the site and specifically the logical operators section (http://dev.datasift.com/docs/operators/logical-operators) but I haven’t found what is the precedence for boolean operators. For instance, what is the following rule equivalent to:

(twitter.text contains “A”) OR (twitter.text contains “B”) AND (twitter.text contains “C”) OR (twitter.text contains “D”)

  1. twitter.text contains "A" OR (twitter.text contains "B" AND twitter.text contains "C") OR twitter.text contains "D" - AND has a higher precedence than OR
  2. (twitter.text contains "A" OR twitter.text contains "B") AND (twitter.text contains "C" OR twitter.text contains "D") - OR has a higher precedence than AND- a bit unusual
  3. (((twitter.text contains "A" OR twitter.text contains "B") AND twitter.text contains "C") OR twitter.text contains "D") - both AND and OR have equal precedence, processed left to right

For instance, in Wolfram Alpha AND has a higher precedence (first option):


#2

The operators are processed from left to right - if you are ever in doubt about exactly how to structure CSDL queries, brackets are your friend.

Also, the example you gave could be simplified to prevent any ambiguity over the precedence of operators:

twitter.text contains_any "A, B" AND twitter.text contains_any "C, D"


#3

Thanks! Brackets are good when you write the expression, but it’s good to know what happens if a third-party creates the rules.

The “contains_any” operator is good to know. BTW your expression corresponds to option 2 in the list I provided. My example was only meant to show how it can be interpreted in 3 different ways depending on operator precedence.


#4

The operators are processed from left to right according to the precedence rules of C++.

http://en.cppreference.com/w/cpp/language/operator_precedence

This means that AND outranks OR.

If it was simply left to right, this filter would match "aaa ccc" and also "bbb ccc", for example.

twitter.text contains "aaa" or
twitter.text contains "bbb" and
twitter.text contains "ccc"

 

Instead, it behaves is if there were brackets because the AND has higher precedence than that OR:

twitter.text contains "aaa" or
(twitter.text contains "bbb" and
twitter.text contains "ccc")

Therefore, it matches "aaa" and also "bbb ccc".