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