简体   繁体   中英

How does Neo4J cypher OPTIONAL MATCH works?

I ran into a problem today understanding OPTIONAL MATCH clause in cypher. Let's consider this simple case:

CREATE (:a {type:"group"})-[:a_rel]->(:a {type: "app"})-[:b_rel]->(:b);

This creates 2 "a" node with different type attribute, plus one "b" node. All of them are in a simple path a-->a-->b

Then, I'm trying to match the "a" node having "group" type, connected to the other "a" node, optionaly connected to the "b" node.

So, if I run the following query, I expect it to return nothing:

MATCH(x:a)-->(y:a) 
where x.type = "group" 
OPTIONAL MATCH (y)-->(z:b) 
where z IS NULL 
return y

but it always return the second "a" node of the path, using IS NULL or IS NOT NULL on the where clause.

Could you please explain me what I do not understand here. In my real model, the second "a" node can be connected or not to the "b" node. I would like to retrieve all the one that are not connected to any "b" node.

Thanks a lot for your help

Rémi

What OPTIONAL MATCH does is, it tries to find out patterns in the graph.If matching pattern is found that Node is returned, else it is replaced with NULL.I hope this will clear the confusion caused.

As long as the MATCH clause finds a match, the query will always return y .

This is because the OPTIONAL MATCH does not need to match anything in order for the query to proceed. That is why it is "OPTIONAL".

This is one way to do what you intended:

MATCH (x:a)-->(y:a)
WHERE x.type = "group" AND NOT (y)-->(:b)
RETURN y

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