0
votes

Suppose I have Red, Blue and Green nodes (R, B, G) and the relationships might look like this:

Graph showing R -> B <- C

As you can see, R points to B and G also points to B. I want to match all R nodes where all the B nodes they point to are also related to a specific G node. How would I do this?

You can set this up on your own database by running something like this:

CREATE 
    (R1:Test_R),
    (B1:Test_B),
    (G:Test_G),
    (R2:Test_R),
    (B2:Test_B),
    (R1)-[:TEST_LINK]->(B1),
    (R1)-[:TEST_LINK]->(B2),
    (R2)-[:TEST_LINK]->(B1),
    (G)-[:TEST_LINK]->(B1)
RETURN
    R1, R2, B1, B2, G

You can then query them by running something like this:

MATCH
    (R:Test_R)-[:TEST_LINK]->(B:Test_B)
OPTIONAL MATCH
    (B)<-[:TEST_LINK]-(G:Test_G)
RETURN
    R,B,G
1
I would be interested in cleaner, more elegant queries than the one I have used. - Jamie Twells

1 Answers

0
votes

You can do it using a query something like the following:

MATCH
    (R:Test_R)-[:TEST_LINK]->(B:Test_B)
WITH
    {R: R, B: COLLECT(B) } AS d
MATCH
    (G:Test_G)
WHERE   
    ID(G) = 5770 // Match our specific G node
    AND ALL(b IN d.B WHERE (b)<-[:TEST_LINK]-(G) )
RETURN d.R

The ALL function will return true if all items in the list return true for the predicate specified:

ALL(<variable> IN <list> WHERE <predicate)