Clone nodes

The available procedures are described in the table below:

Qualified Name Type Release

apoc.refactor.cloneNodes

apoc.refactor.cloneNodes([node1,node2,…​]) clone nodes with their labels and properties

Procedure

APOC Core

apoc.refactor.cloneNodesWithRelationships

apoc.refactor.cloneNodesWithRelationships([node1,node2,…​]) clone nodes with their labels, properties and relationships

Procedure

APOC Core

The apoc.refactor.cloneNodesWithRelationships(<nodes>) has been deprecated in favor of apoc.refactor.cloneNodes(<nodes>, true).

Example Usage

The examples below will help us learn how to use these procedures.

Clone nodes only

The following creates a graph with two nodes, Foo and Bar:
CREATE (f:Foo{name:'Foo'}),(b:Bar{name:'Bar'})
apoc.refactor.cloneNodes.dataset
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
RETURN *

where input is the source node id, output is the node cloned and error is the possible error message.

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

apoc.refactor.cloneNodes

In case of an error, the message will be thrown in the error result, for example with this constraint:

CREATE CONSTRAINT ON (n:UniqueLabel) ASSERT n.key IS UNIQUE

We can create this node:

CREATE (:UniqueLabel {key: 1})

and then we can execute:

MATCH (n:UniqueLabel) WITH n
CALL apoc.refactor.cloneNodes([n])
YIELD error, output
RETURN error, output

getting as a result:

Table 1. Results
error

output

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

null

Clone nodes with relationships

The following creates a graph containing two different nodes of type Actor connected with other two different node of type Movie
CREATE (k:Actor {name:'Keanu Reeves'})-[:ACTED_IN {role:'Neo'}]->(m:Movie {title:'The Matrix'}),
       (t:Actor {name:'Tom Hanks'})-[:ACTED_IN {role:'Forrest'}]->(f:Movie {title:'Forrest Gump'})
RETURN *
apoc.refactor.cloneNodesWithRelationships.dataset
The following creates copies of both of these nodes and their relationships:
MATCH (k:Actor {name:'Keanu Reeves'})
MATCH (t:Actor {name:'Tom Hanks'})
CALL apoc.refactor.cloneNodes([k,t], true)
YIELD output
MATCH p=(output)--()
RETURN *

As result we have a copy of the nodes and relationships

apoc.refactor.cloneNodesWithRelationships

Clone nodes skipping properties

We can clone nodes excluding some properties, by specifying the `propertyKey`s list as the third parameter For example, with this node:

CREATE (f:Foo{name:'Bar', surname: 'Baz', age: 66})

we can execute:

MATCH (n:Foo)
CALL apoc.refactor.cloneNodes([n], false, ["age"])
YIELD output
RETURN properties(output) AS props
Table 2. Results
props

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