Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I delete duplicate relationships between two nodes with cypher?

Tags:

neo4j

cypher

When I run this query:

START n1=node(7727), n2=node(7730)
MATCH n1-[r:SKILL]->n2 RETURN r

it gives me a list of duplicate relationships that I have between the two nodes. what do I add to the cypher query to iterate over the relationship to keep one relationship and delete the rest?

like image 401
priyolahiri Avatar asked Aug 13 '13 06:08

priyolahiri


People also ask

How do you delete a relationship in Cypher?

One option is to delete all relationships, then delete the node. Another option is to use the DETACH DELETE clause. The DETACH DELETE clause lets you delete a node and all relationships connected to it.

How do I get rid of duplicate nodes in neo4j?

To delete all but one of the duplicate nodes, you could do this: MATCH (b:BusinessBranch) WITH b. address AS address, COLLECT(b) AS branches WHERE SIZE(branches) > 1 FOREACH (n IN TAIL(branches) | DETACH DELETE n); However, in this case you should first take a look at the APOC procedure apoc.


2 Answers

To do this for two known nodes:

start n=node(1), m=node(2) match (n)-[r]->(m) 
with n,m,type(r) as t, tail(collect(r)) as coll 
foreach(x in coll | delete x)

To do this globally for all relationships (be warned this operation might be very expensive depending on the size of your graph):

start r=relationship(*) 
match (s)-[r]->(e)
with s,e,type(r) as typ, tail(collect(r)) as coll 
foreach(x in coll | delete x)
like image 56
Stefan Armbruster Avatar answered Sep 16 '22 19:09

Stefan Armbruster


With Neo4J 4.x and to globally remove duplicate relationships, you'll want to use the following instead. The syntax has changed slightly and the start prefix mentioned in the other reply no longer works.

match ()-[r]->() 
match (s)-[r]->(e) 
with s,e,type(r) as typ, tail(collect(r)) as coll 
foreach(x in coll | delete x)
like image 30
chris_g Avatar answered Sep 20 '22 19:09

chris_g