merge multiple nodes with the same relationship

Viewed 39

anybody can help me with

MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH COLLECT(n)+COLLECT(n1) as nodes
CALL apoc.refactor.mergeNodes(nodes,{mergeRels:true}) YIELD node
RETURN node

I actually want to combine n and n1 because let's say n has "name" property and n2 has "email" property. I tried the code above and it says: "Neo.ClientError.Schema.ConstraintValidationFailed" with explanation: "Cannot delete node<1397>, because it still has relationships. To delete this node, you must first delete its relationships."

I've found the solution:

//SOLUTION
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH o.order_id as i, HEAD(COLLECT([n,n1])) AS nodes
CALL apoc.refactor.mergeNodes(nodes, {mergeRels:true})
YIELD node
RETURN node

it works perfectly to all nodes referred as n and n1

1 Answers

Instead of collect(n) + collect(n1), use head(collect[n, n1])). Also, you should include combine properties in your parameter.

OLD:
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH COLLECT(n)+COLLECT(n1) as nodes
CALL apoc.refactor.mergeNodes(nodes,{mergeRels:true}) YIELD node
RETURN node

New:
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH head(collect([n,n1])) as nodes
CALL apoc.refactor.mergeNodes(nodes,{properties:"combine",mergeRels:true}) YIELD node
RETURN node

I'm using neo4j version 4.2.4 and below is my sample test data;

CREATE (c1:Customer {name: "Charlize Theron"})
CREATE (c2:Customer {email: "char@theron.com"})
CREATE (o:Order {ID: 1234})
MERGE  (c1)-[:ORDERS]->(o)
MERGE  (c2)-[:ORDERS]->(o)
MERGE  (c2)-[:LIKES]->(o)

Reference: https://neo4j.com/labs/apoc/4.2/graph-updates/graph-refactoring/merge-nodes/

Related