Case Statement For Null relationship

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.

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
1 Like

Thanks will give it a shot and report back.

Worked like a charm, thank you.