Search code examples
graphneo4jcypheramazon-neptunegraphdb

Cypher query - Combine 2 queries by pipe result of one to other


I am a beginner on cypher and want to create a query that find all nodes that connect to specific nodes that other node connect to them, see the example

I need to get all the brown nodes that connect to the red nodes that the blue node connect to it.

for this example I want to get the brown nodes Ids: 2, 3 and 1 (because no red nodes needs to get it)

For now I did it on 2 different queries and use python to find it, but now I need to do this in 1 query.

Match (r:R)-[]-(a:A) return collect(a.Id)

and the second query:

Match (b:B) Optional Match (b)-[]-(a:A) return b.Id, collect(a.Id)

and in my script check if every record from the second query is a subset of the first list of all a.Id that connect to R

can I do it in 1 query? Thank!


Solution

  • Improved answer: Start with :B nodes and check if all their :A neighbours are have a link to :R the ALL() function also returns true if :B does not have any neighbours

    MATCH (b:B)
    WHERE ALL(n IN [(b)--(a:A) | a] WHERE EXISTS ((n)--(:R))  ) 
    RETURN b
    

    enter image description here