lo tolmencre
lo tolmencre

Reputation: 3954

Conditionally add subgraph

I have a set of cypher clauses that I want to apply repeatedly until the graph stops changing. For that, I require that the clauses check, whether they have already run. For example, if I have a clause adding an edge (a:X) --> (b:Y), then that clause should only run, iff (a:X) --> (b:Y) does not yet exist. I tried to use MERGE like so:

Clause 1 (add root node): CREATE (root:root)

Clause 2 (add child node): MERGE (root:root)-[r:some_rel]->(b:child)

However, when running both clauses, it will produce three nodes. Is there a way, to make the (root:root) from Clause 2 be matched to the one from Clause 1?

enter image description here

Upvotes: 0

Views: 97

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

Try running them as a single query, and use the node created from the CREATE statement, like this:

CREATE (root:root)
MERGE (root)-[r:some_rel]->(b:child)

Update, to keep them independent, try this:

Query 1 - CREATE (root:root)

Query 2 -

MATCH (root:root) 
MERGE (root)-[r:some_rel]->(b:child)

Upvotes: 1

Related Questions