Deleting old relationships and create new ones with the same label in the same query

自古美人都是妖i 提交于 2019-12-10 20:17:13

问题


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?


回答1:


[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.



来源:https://stackoverflow.com/questions/33512230/deleting-old-relationships-and-create-new-ones-with-the-same-label-in-the-same-q

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!