Neo4j cypher query language - order of operations for boolean expressions

大兔子大兔子 提交于 2020-05-30 08:00:26

问题


I am trying to write a query to pull data from my Neo4J database. Lets say there are five conditions that determine whether or not I want to pull _____ from my database: A, B, C, D, and E. The boolean expression which determines this is:

A && B && (C || D || E)

From scouring the web, I cannot find any information about an order of operations that Neo4J AND and OR queries abide by (AND usually precedes OR), but from my observations they seem like they execute sequentially. Since there is no way that I know of to explicitly define order, aka using parenthesis, how would one implement a Cypher query to satisfy the boolean expression above?


回答1:


there is no way that I know of to explicitly define order, aka using parenthesis

Don't be so sure. ;)

First of all, there's always an association or grouping, even if it is implicit in case they are executed sequentially. Let's look at a case where this matters.

MATCH (n) RETURN CASE WHEN false AND true OR true THEN 'and' ELSE 'or' END

(This will work as long as there is at least one node in your database.)

This must be equivalent either to ((false and true) or true) or (false and (true or true)), but these have different outcomes.

(false and true) or true => false or true => true
false and (true or true) => false and true => false

The query above will return "and" in the first case and "or" in the second, to show you which was executed first. It returns "and", because they are grouped sequentially.

MATCH (n) RETURN CASE WHEN ((false AND true) OR true) THEN 'and' ELSE 'or' END

This also returns "and", because this is the implied grouping you get when you execute the boolean operators sequentially.

MATCH (n) RETURN CASE WHEN (false AND (true OR true)) THEN 'and' ELSE 'or' END

But this returns "or".

That was a really long-winded way to say that adding parentheses is indeed the answer.


Just for fun, I tried to determine precedence, and it appears that Neo does have and-precedence:

MATCH (n) RETURN CASE WHEN true or true and false THEN 'and' ELSE 'or' END

If the or is grouped first:

(true or true) and false => true and false => false

If the and is grouped first:

true or (true and false) => true or false => true

The query above returns 'and', indicating the implicitly grouped construct evaluated to true overall (thus and was grouped first despite appearing last sequentially).



来源:https://stackoverflow.com/questions/39239723/neo4j-cypher-query-language-order-of-operations-for-boolean-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!