Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
07-20-2022 02:17 AM
Hi everyone,
I'm currently starting to learn how Cypher works and I got stuck trying to find if 2 specific nodes are connected directly. I want to get 1 if the nodes are connected and 0 if they are not.
I write the following but this just find all the neigbors .
MATCH (n where ID(n)=1000)
CALL apoc.path.subgraphNodes(n, {maxLevel: 1}) YIELD node
RETURN node
Could anyone help me find a solution how to do this?
Thank you very much.
07-20-2022 03:12 AM - edited 07-20-2022 03:25 AM
If you want to find out if two specific nodes are connected directly (one hop), then you need to find both nodes and test for the existence of a relationships between them. The following query does that. It uses the 'exists' method to determine if a direct connection exists between nodes 'm' and 'n'. The result is either 'true' or 'false'.
match (n where ID(n)=1000)
match (m where ID(m)=1001)
return exists( (n)--(m) )
If you really want '0' or '1' instead, you can use a 'case' statement to map true/false to 1/0.
match (n where ID(n)=1000)
match (m where ID(m)=1001)
return case exists( (n)--(m) ) when true then 1 when false then 0 end
Or, a slightly different syntax:
match (n where ID(n)=1000)
match (m where ID(m)=1001)
with exists( (n)--(m) ) as isConnected
return case isConnected when true then 1 when false then 0 end
BTW, (n)--(m) is shorthand notation of (n)-[]-(m), which represents a direct connection between 'n' and 'm'.
07-20-2022 04:07 AM
Thank you this works perfect for me
07-20-2022 07:30 AM - edited 07-20-2022 07:30 AM
Hello @mixalisnikolaou 😊
If the nodes are densely connected, you should use apoc.nodes.connected() function from the APOC plugin:
MATCH (n WHERE id(n) = 1000)
MATCH (m WHERE id(m) = 1001)
RETURN apoc.nodes.connected(n, m) AS output;
Regards,
Cobra
All the sessions of the conference are now available online