# 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.

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).

1 Like
``````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

``````
1 Like

Hello @vence.andersen17 The best solution is to use GDS and the Weakly Connected Components algorithm.

Some examples:

Regards,
Cobra