Yoann Maingon
Yoann Maingon

Reputation: 315

Cannot duplicate node due to constraint violation on an _id

We are trying to clone nodes on a label that has a duplicate constraint on the property _id

MATCH (s:part{_id:'aaaaa'})
CREATE (newNode:part)
SET newNode = s, newNode._id = 'bbbbb'
RETURN  newNode

and we get

Node(52) already exists with label `part` and property `_id` = 'aaaaa'

How can you clone a node just changing the constrained property?

Upvotes: 2

Views: 134

Answers (2)

dgrana
dgrana

Reputation: 108

You can clone nodes using apoc.refactor.cloneNodes like this:

MATCH (s:part{_id:'aaaaa'}) WITH s CALL apoc.refactor.cloneNodes([s]) yield input, output RETURN *

This query will clone your node without the unique properties, so you have to set that properties later:

MATCH (copy:part) WHERE not exists(copy._id) SET copy._id='bbbbb' RETURN copy

This link explain how to clone nodes and relationships: https://neo4j-contrib.github.io/neo4j-apoc-procedures/3.5/graph-refactoring/clone-nodes/

Upvotes: 1

InverseFalcon
InverseFalcon

Reputation: 30397

We can use a map instead of a node variable for the source of the properties to set.

Using map projection, we can let that map take all the properties of the first node, and selectively overwrite the properties we would like to replace.

MATCH (s:part{_id:'aaaaa'})
CREATE (newNode:part)
SET newNode = s {.*, _id:'bbbbb'}
RETURN  newNode

Upvotes: 2

Related Questions