Variable length match under node constraint
Let's say I have a graph where the nodes are either red or green. I am starting with a red node, and I would like to get all the other red nodes that are connected to my start node, only going through the Green nodes.
For example, if I have the following graph:
(R1)
/ \
(G1) (G3)
| |
(G2) (R3)
| |
(G5) (G4)
| |
(R2) (R4)
I would like to get the following set of results:
R1, R2 R1, R3
Any ideas on how to write this query?
Thank,
EDIT: To create a 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 tried the following query but it returns node R4 to me, which is not what I want.
MATCH (r1:Red{label:'R1'})-[:foo*]->(green:Green)-->(other_red) RETURN r1, green, other_red
source to share
Here's 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 ensures that only the first red node is taken, keeping the path containing only 2 red knot ( r1
and other_red
).
source to share
Data setup:
CREATE (r1 {label: "R1"})-[:foo]->(g1 {label: "G1"})-[:foo]->(g2 {label: "G2"})-[:foo]->(r2 {label: "R2"}),
(r1)-[:foo]->(g3 {label: "G3"})-[:foo]->(r3 {label: "R3"})-[:foo]->(g4 {label: "G4"})-[:foo]->(r4 {label: "R4"});
Now, here's your request:
MATCH (r1 { label: "R1"})-[:foo*1..3]->(target)
WHERE target.label =~ "R.*"
RETURN r1.label, target.label;
This query uses a variable length path ( [:foo*1.3]
), which specifies that the path must be at least one step longer, no more than 3 steps. Then I filter based on the nodes with a label that starts with "R". This gives the correct result, otherwise G1, G2 and G3 will also be in the result set because they are within that number of transitions.
source to share