Clone nodes

The APOC library contains a procedure that can be used to clone nodes.

Procedure for cloning nodes and relationships

Qualified Name Type

apoc.refactor.cloneNodes(nodes LIST<NODE>, withRelationships BOOLEAN, skipProperties LIST<STRING>) - clones the given NODE values with their labels and properties. It is possible to skip any NODE properties using skipProperties (note: this only skips properties on NODE values and not their RELATIONSHIP values).



The examples below will explain this procedure in more detail.

Clone nodes only

The following creates a graph with two nodes, Foo and Bar:
CREATE (f:Foo{name:'Foo'}),(b:Bar{name:'Bar'})
The following creates copies of both of these nodes:
MATCH (f:Foo{name:'Foo'}),(b:Bar{name:'Bar'})
CALL apoc.refactor.cloneNodes([f,b])
YIELD input, output, error

In the above query, input is the source node id, output is the node cloned, and error is the possible error message.

This query will result in the following graph:


Clone nodes and constraints

The below example will demonstrate what happens when apoc.refactor.cloneNodes is called using nodes with constraints on them.

The following creates a property constraint for all nodes with a specific label
The following creates a node with a key property set to 1
CREATE (:UniqueLabel {key: 1})
The following attempts to clone the node with a constraint on it
MATCH (n:UniqueLabel)
CALL apoc.refactor.cloneNodes([n])
YIELD error, output
RETURN error, output

The result of the above query will result in an error because of the uniqueness constraint placed on the original node.

Table 1. Results


"Node(<NNN>) already exists with label `UniqueLabel` and property `key` = 1"


Skipping properties on cloned nodes

It is possible to exclude propertes when cloning nodes. This is done by specifying the skipProperties list in the parameter.

In the below example, the age property of the original node is skipped in the cloned node.

The following creates a node
CREATE (f:Foo{name:'Bar', surname: 'Baz', age: 66})
The following clones the node, skipping its age property
MATCH (n:Foo)
CALL apoc.refactor.cloneNodes([n], false, ["age"])
YIELD output
RETURN properties(output) AS props
Table 2. Results

{ "surname": "Baz", "name": "Bar" }