Cannot delete node<id>, because it still has relationships. To delete this node, you must first delete its relationships

I am creating relations between nodes n and l.
Sometimes duplicate relations occur.
image

If a relation of this type already exists, it should merge.
So to be clear: only the relation should merge - not the nodes.
Unfortunately I have not found something like apoc.refactor.mergeRels, som i am using mergeNodes.

I get this exception, that i need to delete the relationships first. But how do I integrate a deletion of relationships into this query?

Here are the query that gives the exception (same as above from picture)

MATCH(n) WHERE ID(n) = {fromNodeId}
MATCH(l) WHERE ID(l) = {toNodeId} 
CREATE (n)-[r:{relationType}]->(l)
WITH n,l
MATCH (n)-[r:{relationType}]->(l) 
WITH n ORDER BY n.creationTime DESC
WITH collect(n) AS origin 
CALL apoc.refactor.mergeNodes(origin, { properties: 'discard',  mergeRels:true}) 
YIELD node 
RETURN node

Thank you!

You can use the command

MATCH (n:yourNode)..
DETACH DELETE n

Andy

1 Like

EDIT:

I have found apoc.merge.relationship
The problem of duplicate relations continues

WITH n,l
CALL apoc.merge.relationship
(
  n,'{relationType}',{},{},l,{}
) 
YIELD rel
RETURN rel 

Now even more so, as relation between nodes that are neither (n) nor (l) will be created and duplicated

I'm getting this same error message while trying to use:

CALL apoc.refactor.mergeNodes([n, n2])

to merge duplicate nodes. Did you find a solution?

Try this:

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

That's a good method