Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
05-07-2019 04:12 AM
I'm trying to perform an operation that will check to see if a relationship exists on a node and if not create one. If a relationship does exist, I want to delete the relationship and then create a new one. What I have so far is:
Match (w:Well {id: "0099"})<-[r:OPERATES]-()
return r
CASE r
WHEN r is null THEN with w as free_well match (o:Operator {id: "cdf90d9e-6d07-11e9-b13d-00e04c680cd0"}) merge (free_well)<-[:OPERATES]-(o) return o
ELSE delete r with w as free_well match (o:Operator {id: "cdf90d9e-6d07-11e9-b13d-00e04c680cd0"})
merge (free_well)<-[:OPERATES]-(o)
return o
END
which does not work. I realize that that I may not be able to test against just the relationship but I'm not sure what else to check for. The following statement does what I want to do as long as a relationship exists but if one doens't the statement doesn't do anything.
Match (w:Well {id: $wellId})<-[r:OPERATES]-()
delete r
with w as free_well
match (o:Operator {id: $operatorId})
merge (free_well)<-[:OPERATES]-(o)
return o
So I'm trying to make one that will do it regardless of the relationship state.
05-07-2019 04:55 AM
You'll need to mix MATCH and OPTIONAL MATCH here, using MATCH on the node itself and OPTIONAL MATCH on the pattern including the might-not-exist relationship:
Match (w:Well {id: $wellId})
OPTIONAL MATCH (w)<-[r:OPERATES]-()
delete r
with DISTINCT w as free_well
match (o:Operator {id: $operatorId})
merge (free_well)<-[:OPERATES]-(o)
return o
Alternately you could use a FOREACH, and use a pattern comprehension as the list source of the :OPERATES relationships on w
:
Match (w:Well {id: $wellId})
FOREACH (rel in [(w)<-[r:OPERATES]-() | r] | DELETE rel)
with w as free_well
match (o:Operator {id: $operatorId})
merge (free_well)<-[:OPERATES]-(o)
return o
05-07-2019 05:01 AM
Thanks will give it a shot and report back.
05-07-2019 06:38 AM
Worked like a charm, thank you.
All the sessions of the conference are now available online