marhg
marhg

Reputation: 687

cypher find which nodes have relation with a set of nodes

From a previous query I retrieved a list of nodes, e.g. nodes 9,10,18,12,20 that indicate a car position. Note that the list can be dynamic, i may get more or less nodes

From the list of nodes i would like to know and retrieve which node is related to whom. (or who is friend of who) (node)-[:TO]-(node) From the given list

E.g. from the model, we can see that nodes 9 and 10 are (friends) related, 18 and 12 too and 20 has no friends from the list.

enter image description here

So at the end i would like to get this:

enter image description here

And in the Row result (in neo4j) should display

[9, 10], 
[18, 12], 
[20]

Each friend relation in a different row.

Any suggestions?

Thank you in advance

Upvotes: 1

Views: 177

Answers (1)

Martin Preusse
Martin Preusse

Reputation: 9369

You can collect the nodes in your previous query and then UNWIND them and MATCH them onto themselves.

MATCH (n:Label)
// your filter here
WHERE ... 
WITH collect(DISTINCT n) AS my_nodes
// unwind twice to match nodes onto themselves
UNWIND my_nodes AS x
UNWIND my_nodes AS y
MATCH (x)-[:TO]->(y)
WHERE x <> y
RETURN x.value, y.value

But maybe you can also include this in you previous query somehow by including another relationship to the nodes? That depends how your previous query looks like.

Upvotes: 1

Related Questions