Reputation: 22171
Let's suppose Person
and Car
nodes.
I want in the same cypher query to delete all relationships APerson-[:OWNS]-SomeCar
and inserts new ones.
Basically I had tried this query:
MATCH (p:Person {_id: {personId}})
WITH p
MATCH (c:Car)
WITH p, c
MATCH p-[r:OWNS]->c
DELETE r //deleting all "old" relationships
WITH c //a with is expected here by cypher syntax => dummy value that shouldn't impact the remaining of the query
MATCH (p:Person {_id: {personId}}), (c:Car)
WHERE c._id IN {cars}
WITH p, c
MERGE p-[:OWNS]->c //merge new ones
Parameters passed to the query: cars
and personId
.
However, it results with no new relationships added. As if the delete occurs after the merge, and therefore removing ALL relationships completely.
Any way to do it in the same query?
Upvotes: 3
Views: 1735
Reputation: 66989
[UPDATED]
Does this query do what you want?
MATCH (p:Person {_id: {personId}})
OPTIONAL MATCH (p)-[r:OWNS]->(:Car)
DELETE r
WITH p
MATCH (c:Car)
WHERE c._id IN {cars}
MERGE p-[:OWNS]->c;
This query uses OPTIONAL MATCH
to allow the entire query to be processed even if there is no existing OWNS
relationship. (A non-optional MATCH
clause would abort the entire query if it failed to find a match.)
It also re-uses the matched Person
node to avoid a second match attempt.
In addition, my query specifies the only required WITH
clause. A write clause (like DELETE
) cannot be followed by a read clause (like MATCH
) unless there is a WITH
clause between them.
Upvotes: 6