query to copy a node with relations in neo4j without the clone procedure

Viewed 99

I want to copy a node with all its properties and relations with others nodes. Im using Neo4j version 3.4.7 so I can't use the clone procedure. My node might have different types of relations and I want to copy them all. I wanted to use this query

match (map:student {name:'test'})
create (copy:student) set copy=map with copy,map
match (map)-[r1]->(n)
with collect(r1) as rels,map,copy,n
foreach( rel in rels | create (copy)-[r2:type(rel)]->(n) set r2+=rel)
return copy,n

but I get invalid syntax error using type(rel) in foreach. Is there a way to do this without knowing the types of relations?

1 Answers

The easiest way is to install the APOC library, and call the procedure apoc.refactor.cloneNodesWithRelationships, as documented here.

In your case, your query would become:

MATCH (map:student {name:'test'})
CALL apoc.refactor.cloneNodesWithRelationships([map])

Note: node labels usually start with an upper letter (Student is more common than student in Neo4j datasets).

Related