2
votes

I would like to delete duplicate relationships between two nodes with Cypher where multiple relationships exist between the nodes. As an example, given:

a->r1->b
a->r2->b
a->r2->b
a->r3->b

I expect:

a->r1->b
a->r2->b
a->r3->b

I already looked into the similar questions but they assume all the relationships between two nodes are the same so you can simply keep one and delete the rest, which doesn't work in my case.

1
What is your criteria to delete or keep the relationship?Bruno Peres
I want to delete duplicate relationships (those that are exactly the same).media
For example: the relationship is the same if the type is the same or if the type and all properties are the same?Bruno Peres
Type and all properties are the same.media

1 Answers

6
votes

Assuming you have labels on your nodes, this should work:

MATCH (a:A)-[r]->(b:B)
WITH a, type(r) as type, collect(r) as rels, b
WHERE size(rels) > 1
UNWIND tail(rels) as rel
DELETE rel

We're collecting the relationships and grouping by type (as well as start and end node), so if any collection is greater than 1, then there are multiple relationships with the same type. We UNWIND all but the first relationship back into rows then delete them.

If you don't have labels to use for your query, then the query will be graph-wide, which is likely to take much longer to execute, and may encounter issues if the set of relationships to delete is too large to handle all at once.