cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Get all nodes connected

I have nodes like the above image, now can I get all nodes from A1 to A7 by querying A1 or getting all nodes from B1 to B5 by querying B1. Here we don't know the number of nodes connected, as you can see A1 has 6 nodes, B2 has nodes through it's path. All the nodes are having the same label, so we can't fetch them with the label.

Thanks in advance.

3 REPLIES 3

You would use a pattern that matches your desired result. You can add as many constrains to the pattern to restrict your result to exactly what you need. In your cases, you basically have an anchor node you can explicitly identify (A1, B1, or C1) and a path consisting of a variable number of hops. Assuming you don't care about the relationship type, the following should work. I have just identified the anchor node by its id. Substitute your current criteria for selecting the anchor node. I also left off specific node labels. Add those as needed as well.

match (n where id(n) = 1)
match p = (n)-[*]->()
return p

'p' is a path. it consists of a collection of nodes and a collection of relationships that comprise the path. You can return them instead with the following query:

match (n where id(n) = 1)
match p = (n)-[*]->()
return nodes(p) as nodes, relationships(p) as relationships

nodes and relationships will be lists of those entities. Each relationship consists of its starting node, ending node, and relationship properties. For a given relationship r, its starting node is startNode(r), its ending node is endNode(r), and its properties is properties(r).

ameyasoft
Graph Maven
Try this:

MATCH (a:Test) where a.name = "A1"  
CALL apoc.path.spanningTree(a,{}) YIELD path  

with nodes(path) as n1
 unwind n1 as a1
 with a1

 MATCH (a1:Test) where a1.name = "B1"  
CALL apoc.path.spanningTree(a1,{}) YIELD path  

with a1, nodes(path) as n2
 unwind n2 as b1
 with a1, b1 

MATCH (a2:Test) where a1.name = "C1"  
CALL apoc.path.spanningTree(a2,{}) YIELD path  

with a1, b1, nodes(path) as n3
unwind n3 as c1
with a1, b1, c1 

return a1, b1, c1