apoc.nodes.collapse

Procedure APOC Core

apoc.nodes.collapse([nodes…​],[{properties:'overwrite' or 'discard' or 'combine'}]) yield from, rel, to merge nodes onto first in list

Signature

apoc.nodes.collapse(nodes :: LIST? OF NODE?, config = {} :: MAP?) :: (from :: NODE?, rel :: RELATIONSHIP?, to :: NODE?)

Input parameters

Name Type Default

nodes

LIST? OF NODE?

null

config

MAP?

{}

Config parameters

The procedure support the following config parameters:

Table 1. Config parameters
name type default description

properties

String

"discard"

how to handle properties on the nodes being collapse. The following values are supported:

  • overwrite - if there is the same property in more node, in the new one will have the last relationship’s/node’s property value

  • discard - if there is the same property in more node, the new one will have the first relationship’s/node’s property value

  • combine - if there is the same property in more node, the new one a value’s array with all relationship’s/node’s values

mergeVirtualRels

Boolean

true

give the possibility to merge relationships with same type and direction.

selfRel

Boolean

false

give the possibility to create the self relationship.

countMerge

Boolean

true

give the possibility count all the Nodes/Relationships merged.

collapsedLabel

Boolean

false

give the possibility to add the label :Collapsed to the virtualNode.

Output parameters

Name Type

from

NODE?

rel

RELATIONSHIP?

to

NODE?

Usage Examples

The examples in this section are based on the following sample graph:

MERGE (david:Person {name: "David"})
MERGE (john:Person {name: "John"})
MERGE (jennifer:Person {name: "Jennifer"})
MERGE (adam:Person {name: "Adam"})
MERGE (mark:Person {name: "Mark"})

MERGE (unitedStates:Country {name: "United States"})
MERGE (uk:Country {name: "United Kingdom"})

MERGE (david)-[:LIVES_IN]->(unitedStates)
MERGE (john)-[:LIVES_IN]->(unitedStates)
MERGE (jennifer)-[:LIVES_IN]->(unitedStates)

MERGE (adam)-[:LIVES_IN]->(uk)
MERGE (mark)-[:LIVES_IN]->(uk);

We can collapse the people living in the city to a single node, by running the following query:

MATCH (p:Person)-[:LIVES_IN]->(c:Country)
WITH c, collect(p) as subgraph
CALL apoc.nodes.collapse(subgraph,{properties:'combine'})
YIELD from, rel, to
RETURN from, rel, to;
Table 2. Results
from rel to

(:Person {name: ["David", "John", "Jennifer"], count: 3})

[:LIVES_IN {count: 2}]

(:Country {name: "United States"})

(:Person {name: ["Adam", "Mark"], count: 2})

[:LIVES_IN {count: 1}]

(:Country {name: "United Kingdom"})