databaseneo4jgraph-databases

neo4j how to get all the nodes eventually connected to a give node?


I am not trying to get all the connected nodes, when I run MATCH (n:Person) RETURN n LIMIT 200 I can see all my nodes and relationships are separated to three groups,

enter image description here

I am trying to find all the nodes connected to a given node (through 1 or multiple relationships), like if I give node3 which is in the center of the bottom right group, can I get back all the nodes in group three?

enter image description here

so I tried

MATCH p=(a:Person {name:'node3'})-[:KNOWS]->(b) return p

but it only returns the node immediately connected to node3, is there anyway we can get all the nodes like shown in group3?

enter image description here


Solution

  • To get all the outgoing KNOWS paths from that specific Person, you can do a variable-length relationship search:

    MATCH p=(a:Person {name: 'node3'})-[:KNOWS*]->(b)
    RETURN p
    

    However, best practice is to put a reasonable upper bound on the path length to avoid running out of memory or taking forever. For example, to set an upper bound of 7 steps from the starting node:

    MATCH p=(a:Person {name: 'node3'})-[:KNOWS*..7]->(b)
    RETURN p