Sravan
Sravan

Reputation: 553

How to create a Duplicate Node from a Node in Neo4j?

I am copying part of my Main Neo4j Graph(mainDB) into another Graph (dupDB), while doing so how can I create a Node in dupDB that has similar properties as one in mainDB.

I would do

Node main = mainDB.getNodeByID(477);
Node dup = dupDB.createNode();

Now I have to copy each property in main to dup manually, is there any one-line method to do this?

Upvotes: 8

Views: 8569

Answers (3)

psygo
psygo

Reputation: 7543

These days, there are functions for cloning nodes in the APOC library, see Neo4j Docs - Clone nodes for example.

One example from the docs:

MATCH (f:Foo{name:'Foo'}),(b:Bar{name:'Bar'})
CALL apoc.refactor.cloneNodes([f,b])
YIELD input, output, error
RETURN *

You can also clone nodes with relationships, clone nodes while skipping properties, etc.

Upvotes: 0

Dave Bennett
Dave Bennett

Reputation: 11216

You can create a duplicate with a map in Neo4j 2.1 (not sure of earlier)

MATCH (n:Node {name: 'abc'}) 
WITH n AS map 
CREATE (copy:Node) 
SET copy=map
RETURN copy

If you have a uniqueness constraint on any of the properties it will fail though with the message...

Node already exists with label XX and property "property"=[value]

You can avoid that by supplying a new value for the property with the uniqueness constraint, creating the new node and copying the other non-unique property values from the original node.

MATCH (n:Node {name: 'abc'}) 
WITH n as map 
CREATE (copy:Node {name: 'def'}) 
SET copy.property1 = map.property1
, copy.property2 = map.property2
RETURN copy

Upvotes: 9

LameCoder
LameCoder

Reputation: 1297

I don't think this existed a year ago. However this might solve the problem today.

The Neo4j shell has a dump command: http://docs.neo4j.org/chunked/preview/shell-commands.html#_dumping_the_database_or_a_cypher_result_to_cypher_statements

dump START n=node({self}) MATCH (n)-[r]-(m) return n,r,m;

You could then take the output of this and send it to another database to create those nodes, properties and all.

Upvotes: 3

Related Questions