简体   繁体   中英

Neo4j Cypher query: Parenthesis not considered in WHERE clause?

I am trying to run a query like:

MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2 in [42, 34]) OR
 (n.prop1="B" and n.prop2 in [67])     OR
 (n.prop1="C" and n.prop2 in [51, 43]) OR
 (n.prop1="D" and n.prop2 in [56, 42])) 
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

This is giving mixed results ie prop1="D" matched with prop2=51 which is clearly not in the intended condition. It is as if the parentheses have no say in the formation of conditional. The results are the same when I run the query w/o parentheses in the WHERE clause.

Although, If I query something like:

MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2=42) OR
 (n.prop1="A" and n.prop2=34) OR
 (n.prop1="B" and n.prop2=67) OR
 (n.prop1="C" and n.prop2=51) OR
 (n.prop1="C" and n.prop2=43) OR
 (n.prop1="D" and n.prop2=56) OR
 (n.prop1="D" and n.prop2=42)) 
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

Is there something I'm missing when replacing the separate conditions in example 2 with the IN in example 1 to avoid repeated string comparisons for prop1 ?

I believe that IN works as you expect.

Set up sample data.

(:Type1 {prop1:"A", prop2:34}),
(:Type1 {prop1:"B", prop2:67}),
(:Type1 {prop1:"C", prop2:51}),
(:Type1 {prop1:"C", prop2:43}),
(:Type1 {prop1:"D", prop2:56}),
(:Type1 {prop1:"D", prop2:42}),
(:Type1 {prop1:"D", prop2:51}),
(:Type1 {prop1:"B", prop2:42});

MATCH (t:Type1)
MERGE (t)-[:relation1]->(:Type1)<-[:relation2]-(:Type2);

Now run your query.

MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2 in [42, 34]) OR
 (n.prop1="B" and n.prop2 in [67])     OR
 (n.prop1="C" and n.prop2 in [51, 43]) OR
 (n.prop1="D" and n.prop2 in [56, 42])) 
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

The statement returns seven records, and the results do not include the node with prop1 = D and prop2 = 51.

See this answer for information on the precedence of Boolean operators if you leave out parenthesis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM