2
votes

lets say, I have two nodes with the same label and same attribute values:

Create (n:A {foo: 'bar'});
Create (m:A {foo: 'bar'});

I have also some other nodes:

Create(o:B {test: 'test'});
Create(p:C {other: 'other'});

And I have relationships from the first nodes to the other nodes:

Match (n:A {foo: 'bar'}), (o:B {test: 'test'}) MERGE (n)-[:r]-(o);
Match (m:A {foo: 'bar'}), (p:C {other: 'other'}) MERGE (m)-[:s]-(p);

So I get a graph shown in the picture:

example graph

Now I want to combine the two nodes of type A to one node and keep both relationships. So I want to get a graph similar as shown in the picture:

new, combined example graph

Is there a cypher query to do this? Especially to do this with all nodes of one type which have the same attribute properties?

1

1 Answers

1
votes

We have a procedure in APOC to do that : apoc.refactor.mergeNodes

This is the link to the documentation : https://neo4j-contrib.github.io/neo4j-apoc-procedures/#merge-nodes

ANd the solution for your example :

MATCH (n:A {foo: 'bar'})
WITH collect(n) AS nodes
  CALL apoc.refactor.mergeNodes(nodes, {properties:"override", mergeRels:true}) yield node
  RETURN node