Let's say I have a graph where the nodes are either Red or Green. I'm starting at a Red node and I would like to get all the other red nodes that are connected to my starting node, going only through Green nodes.
For instance, if I have the following graph:
(R1)
/ \
(G1) (G3)
| |
(G2) (R3)
| |
(G5) (G4)
| |
(R2) (R4)
I would like to get the following result set:
R1, R2
R1, R3
Any ideas on how to write that query?
Thanks,
EDIT: To create the graph:
CREATE (r1:Red{label: "R1"})-[:foo]->(g1:Green{label: "G1"})-[:foo]->(g2:Green{label: "G2"})-[:foo]->(g5:Green{label:"G5"})-[:foo]->(r2:Red{label: "R2"}),
(r1)-[:foo]->(g3:Green{label: "G3"})-[:foo]->(r3:Red{label: "R3"})-[:foo]->(g4:Green{label: "G4"})-[:foo]->(r4:Red{label: "R4"});
I've tried the following query but it gives me back node R4, which I don't want.
MATCH (r1:Red{label:'R1'})-[:foo*]->(green:Green)-->(other_red) RETURN r1, green, other_red
Here is one solution:
MATCH p = (r1:Red {label:'R1'})-[:foo*]->(green:Green)-[:foo]->(other_red:Red)
WITH r1, green, other_red, [n IN nodes(p) WHERE 'Red' in labels(n) | n] as redNodes
WHERE length(redNodes) = 2
RETURN r1, green, other_red
It makes sure that only the first red node is taken by keeping the paths that contain only 2 red nodes (r1
and other_red
).