'Clone nodes and relationships with Cypher

Is it possible to clone arbitrary nodes and relationships in a single Cypher neo4j 2.0 query? 'Arbitrary' reads 'without specifying their labels and relationship types'. Something like:

MATCH (node1:NodeType)-[e]->(n)
CREATE (clone: labels(n)) set clone=n set clone.prop=1 
CREATE (node1)-[e1:type(e)]->(clone) set e1=e set e1.prop=2

is not valid in Cypher, so one cannot simply get labels from one node or relationship and assign them to another, because labels are compiled into the query literally.

Sure, labels and relation types are important for MATCH and WHERE for producing effective query plan, but isn't CREATE making another case?



Solution 1:[1]

The easiest way to clone parts of a graph is to use the dump command in Neo4j shell. dump generates cypher create statements from your return clauses. The result of dump can be appied to the graph database to create clones.

Solution 2:[2]

Today, April 2022, I believe the best approach might be using an APOC procedure

I had a similar requirement and this worked for me.

MATCH  (rootA:Root{name:'A'}),
       (rootB:Root{name:'B'})
MATCH path = (rootA)-[:LINK*]->(node)
WITH rootA, rootB, collect(path) as paths
CALL apoc.refactor.cloneSubgraphFromPaths(paths, {
    standinNodes:[[rootA, rootB]]
})
YIELD input, output, error
RETURN input, output, error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan Armbruster
Solution 2 johnaco