cancel
Showing results for 
Search instead for 
Did you mean: 

Join the community at Nodes 2022, our free virtual event on November 16 - 17.

Get directly connected nodes for multiple nodes in one query?

arielb135
Node

Hello, This is my first time playing with neo4j, I modeled a graph that looks like this:

A ---> B
A ---> C
B ----> D
B ----> E
C ----> F

now, i my input can contain several nodes, let's say i get "A and B", and i want to find the direct connections of A + the direct ones of B, meaning, to return the nodes:
"B", "C", "D","E"

how to do it in a single query?

1 REPLY 1

glilienfield
Ninja
Ninja

Try the following:

unwind ['A', 'B'] as input
match(n where n.name = input)
match (n)-[:REL]->(m)
return n.name, collect(m) as children

Replace the literal array ['A','B'] with your parameter containing your inputs. Also, replace the match condition with your unique identifier and the relationship type in the pattern match with yours. The result is a row for each of your inputs, with a list of each input's direct connected nodes.

Test Data:

Result:

3X_2_e_2ea31bfeb9795ad660e0aba9dba2d9f4b6df3a42.png

If you prefer a list instead of a collection, replace the 'return' clause with this return clause 'return n.name, m', giving the following alternative result:

3X_4_1_4169df17d02008a9826939c06eb6da17e779487c.png

If you want just a list of the child nodes, replace the return clause with this return clause 'return collect(m)', giving the following result: