cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Merge nodes with same property and same relation-type to same other node


the red node has five yellow nodes with relationtype:'Mark'. All five yellow nodes have the same value.
i want to merge these, without merging last yellow node with same value. They should only merge those connected to the specific red node, known by its id or the path (red)-->(yellow)

The result should look like this

What Cyper-query should I use?

4 REPLIES 4

I have been applying APOC Merge with this Query:

MATCH (m:YellowNode) WHERE m.name = 'This' AND m.range = [0,4] WITH collect(m) AS marks CALL apoc.refactor.mergeNodes(marks, {{ properties:'override', mergeRels: false}}) YIELD node RETURN node.creationTime, node.name, ID(node), labels(node)

As you can see it removes the relations called Spec as part of the merge. What happens here?

MuddyBootsCode
Graph Steward

I'm not totally sure but it looks like it's not capturing those nodes in the pattern you're trying to merge. You're also passing merge relationships as false which may be excluding them from being passed correctly to your yellow node.

Try this:

MATCH (a:Red)
MATCH (a)-[:Mark]->(c:Yellow)
WITH a, collect(c) as subgraph

CALL apoc.nodes.collapse(subgraph,{properties:'combine', collapsedLabel: true})  
YIELD from, rel, to
WITH a, from , rel, to where labels(to) in [['Green']]

//Following RETURN gives you the virtual collapsed node....
//RETURN from , rel, to
// See fig. below.....

2X_3_3759dfa4c9be5398565850c59b142b50f9572a93.png

//Create a real node same as virtual node.....
WITH a, from , rel, to, collect(to) as t1
UNWIND t1 as t12

MERGE (g:Collapsed{name: "This"})
MERGE (g)-[:Spec]->(t12)
MERGE (a)-[:Mark]->(g)

// This returns the merged node...
RETURN from, rel, to, g, a
//See Fig. below

//Now cleaning up the yellow nodes......

MATCH (a:Red)-[r:Mark]->(b:Yellow)
DELETE r
DETACH DELETE b

//Final result...
MATCH (n) RETURN n

Fig. below

Instead of deleting yellow nodes, you can keep them and show the collapsed or the expanded version.