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?

1 Like

I believe this APOC procedure you're looking for


I have been applying APOC Merge with this Query:

MATCH (m:YellowNode) WHERE = '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,, ID(node), labels(node)

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

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.....

Screen Shot 2020-09-09 at 4.24.26 PM

//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)

//Final result...

Fig. below

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