cancel
Showing results for 
Search instead for 
Did you mean: 

Check if two nodes are directly connected in cypher

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.

 

3 REPLIES 3

glilienfield
Ninja
Ninja

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'. 

Thank you this works perfect for me

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