简体   繁体   中英

cypher: merge two nodes with same attributes and different relationships

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:

示例图

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:

新的组合示例图

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM