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.
3X_b_3_b34a07b194eb9f245538bd926a9ed5a1930d98aa.png

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!

Every time you run this query, you will create a new relationship with the 'create' statement. I suggest you use 'merge' instead. You can them eliminate the 'match' too.

MATCH(n) WHERE ID(n) = {fromNodeId}
MATCH(l) WHERE ID(l) = {toNodeId} 
MERGE (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

I am not familiar with the syntax on line 3 that specifies the relationship type. Node labels and relationship types can not be parameterized.

To check the if the relationship already exists between two nodes and if it already exists then it should merge the relationship not the Nodes.

I have faced same issue of duplicate relationships getting created between two nodes in Knowledge Graph.

Here is my simple approach for same..

MATCH (n) WHERE ID(n) = {$fromNodeId},
MATCH (l) WHERE ID(l) = {$toNodeId}
WHERE NOT EXISTS ((n)-[:$relationType]->(l))
MERGE (n)-[:$relationType]->(l)

Thank you.

Same problema with apoc.refactor.mergeNodes([n1,n2])