apoc.refactor.from

Details

Syntax

apoc.refactor.from(rel, newNode, config) :: (input, output, error)

Description

Redirects the given RELATIONSHIP to the given start NODE.

Input arguments

Name

Type

Description

rel

RELATIONSHIP

The relationship to redirect.

newNode

NODE

The node to redirect the given relationship to.

config

MAP

{ failOnErrors = false :: BOOLEAN }. Note that while { failOnErrors = true } is recommended to ensure transactional consistency and prevent a partial application of changes, it is not the default since this would risk breaking existing implementations. Introduced in APOC 2025.01

Return arguments

Name

Type

Description

input

INTEGER

The internal id of the original entity.

output

RELATIONSHIP

The copied entity.

error

STRING

Any error that occurred during the copy process.

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.

Usage Examples

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

CREATE (mark:Person {name: "Mark", city: "London"})
CREATE (jennifer:Person {name: "Jennifer", city: "St Louis"})
CREATE (michael:Person {name: "Michael", city: "Dresden"})
CREATE (mark)-[:FOLLOWS]->(jennifer);

The following makes Michael the start node in the FOLLOWS relationship using APOC and Cypher:

apoc.refactor.from
MATCH (michael:Person {name: "Michael"})
MATCH ()-[rel:FOLLOWS]->()
CALL apoc.refactor.from(rel, michael, { failOnErrors: true })
YIELD input, output
RETURN input, output;
Using Cypher
MATCH (michael:Person {name: "Michael"})
MATCH ()-[rel:FOLLOWS]->()
CALL (rel, michael) {
    WITH id(rel) AS oldId, properties(rel) AS relProps, type(rel) AS relType, endNode(rel) AS endNode
    DELETE rel
    MERGE (michael)-[newRel:$(relType)]->(endNode)
    SET newRel = relProps
    RETURN oldId AS oldId, newRel AS newRel
}
RETURN oldId, newRel
Results
input output

14

[:FOLLOWS]

We can list all the Person nodes by running the following query:

MATCH path = ()-[rel:FOLLOWS]->()
RETURN path;
Results
path

(:Person {name: "Michael", city: "Dresden"})-[:FOLLOWS]→(:Person {name: "Jennifer", city: "St Louis"})