apoc.refactor.collapseNode

Details

Syntax

apoc.refactor.collapseNode(nodes, relType) :: (input, output, error)

Description

Collapses the given NODE and replaces it with a RELATIONSHIP of the given type.

Input arguments

Name

Type

Description

nodes

ANY

The nodes to collapse. Nodes can be of type STRING (elementId()), INTEGER (id()), NODE, or LIST<STRING | INTEGER | NODE>.

relType

STRING

The name of the resulting relationship type.

Return arguments

Name

Type

Description

input

INTEGER

The id of the given relationship.

output

RELATIONSHIP

The id of the new relationship with the updated type.

error

STRING

The message if an error occurred.

Refactoring nodes using Cypher

Node labels and relationship types can be referenced dynamically in Cypher without using APOC.

Cypher syntax for creating, matching and merging labels and types dynamically
CREATE (n1:$(label))-[r:$(type)]->(n2:$(label))
MERGE (n1:$(label))-[r:$(type)]->(n2:$(label))
MATCH (n1:$(label))-[r:$(type)]->(n2:$(label))

The dynamically calculated type must evaluate to a STRING or LIST<STRING>. For more information, see the Cypher Manual → CREATE, MERGE, MATCH.

Batching, as well as parallel execution, can be achieved in Cypher using CALL {…​} IN CONCURRENT TRANSACTIONS. For more information, see CALL subqueries in transactions → Concurrent transactions.

Usage Examples

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

CREATE (flight:Flight {number: "BA001"})
CREATE (origin:Airport {code: "LHR"})
CREATE (destination:Airport {code: "AMS"})
CREATE (flight)<-[:OUT]-(origin)
CREATE (flight)-[:IN]->(destination);

The following queries collapses the Flight node, replacing it with a CONNECTED to relationship in APOC and Cypher:

apoc.refactor.collapseNode
MATCH (flight:Flight {number: "BA001"})
CALL apoc.refactor.collapseNode([flight],'CONNECTED_TO')
YIELD input, output
RETURN input, output;
Using Cypher
MATCH (flight:Flight {number: "BA001"})
CALL (flight) {
    MATCH p=(a)-[]-(f)-[]-(b)
    WITH p, a, f, b LIMIT 1
    CREATE (a)-[r:CONNECTED_TO]->(b)
    SET r = properties(f)
    DETACH DELETE f
    RETURN r AS newRel
}
RETURN newRel
Results
input output

10

[:CONNECTED_TO {number: "BA001"}]

If we execute this query, it will result in the following graph:

apoc.refactor.collapseNode