Search code examples
neo4jcypher

Check if two nodes are directly connected in Cypher


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 wrote the following but it just finds all the neighbors.

MATCH (n WHERE ID(n)=1000)
CALL apoc.path.subgraphNodes(n, {maxLevel: 1}) YIELD node
RETURN node 

What is the solution to this?


Solution

  • You are saying that you have two specific nodes, so I assume that you also know the other node. I would solve this without APOC. Getting the Cypher basics without additional libraries first and find out later what you are missing, is -in my opinion- a better way to learn it.

    Using the CASE expression might already do the job for you.

    MATCH (a:A) RETURN CASE WHEN exists((a)-[:RELATIONSHIP_TYPE]-(:B)) THEN 1 ELSE 0 END AS result
    

    If you need to fetch both nodes more specific in the beginning:

    MATCH (a:A{name:'abc'}) 
    MATCH (b:B{name:'xyz'})
    RETURN CASE WHEN exists((a)-[:RELATIONSHIP_TYPE]-(:b)) THEN 1 ELSE 0 END AS result
    

    also what fbiville said in his comment.