Search code examples
neo4jcypher

Neo4j query for getting multiple connected nodes


In my graph, I want to get the first-degree, second-degree, and third-degree neighbors of a certain node. If my graph is A -> B -> C -> D -> E, then

  • first-degree neighbor of C is B
  • second-degree neighbor of C is A
  • third-degree neighbor of C is none

When checking neighbors, I go in the reverse direction of the edge. To get these nodes, I wrote the following query.

MATCH (changedNode: Function) WHERE changedNode.signature IN [...]
MATCH (neig1: Function)-[:CALLS]->(changedNode)
MATCH (neig2: Function)-[:CALLS]->(neig1)
MATCH (neig3: Function)-[:CALLS]->(neig2)
RETURN DISTINCT neig1.functionName, neig2.functionName,  neig3.functionName

I realized that this code does not return B as the first-degree neighbor of C since A does not have any neighbors(neig3 is empty). In other words, this query requires a node to have a third-degree neighbor. I understood this but could not update my code. How should I revise my query?


Solution

  • You can use OPTIONAL MATCH since A may not have a neighbor. Then the query will return a null value for neigh3.

    MATCH (changedNode: Function) WHERE changedNode.signature IN [...]
    MATCH (neig1: Function)-[:CALLS]->(changedNode)
    OPTIONAL MATCH (neig2: Function)-[:CALLS]->(neig1)
    OPTIONAL MATCH (neig3: Function)-[:CALLS]->(neig2)
    RETURN DISTINCT neig1.functionName, neig2.functionName,  neig3.functionName