media
media

Reputation: 453

Delete duplicate relationships between two nodes with Cypher where multiple relationships exist between two nodes

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.

Upvotes: 2

Views: 2055

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30397

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.

Upvotes: 7

Related Questions