phil_20686
phil_20686

Reputation: 4080

Correct usage of CREATE UNIQUE and/or MERGE, example

The following query:

MATCH (LOCALID0:Ship {ShipID: "12345", ShipName: "Phil's Yacht"} ) 
CREATE UNIQUE (LOCALID0:Ship {ShipID: "12345", ShipName: "Phil's Yacht" } ) -    [LOCALID1:contains] - > (LOCALID2:container {ContainerID: "91812" } ), 
(LOCALID0) - [LOCALID3:contains] - > (LOCALID4:container {ContainerID: "87132" } ), 
(LOCALID0) - [LOCALID5:contains] - > (LOCALID6:container {ContainerID: "47490" } ), 
(LOCALID0) - [LOCALID7:contains] - > (LOCALID8:container {ContainerID: "13157" } ), 
(LOCALID0) - [LOCALID9:contains] - > (LOCALID10:container {ContainerID: "22676" } )

Gives the following error:

Exception in thread "main" Can't create `LOCALID0` with properties or labels here. It already exists in this context

When I reuse one of the Cypher ID's, so I have to keep reusing its properties? Is the problem that it doesnt realise that LOCALID0:Ship {ShipID: "12345", ShipName: "Phil's Yacht"} is the same node as LOCALID0?

Upvotes: 1

Views: 149

Answers (1)

Luanne
Luanne

Reputation: 19373

No, you just re-use the identifier:

MATCH (LOCALID0:Ship { ShipID: "12345", ShipName: "Phil's Yacht" }) 
CREATE UNIQUE 
(LOCALID0)-[LOCALID1:contains]- >(LOCALID2:container { ContainerID: "91812" }),
(LOCALID0)-[LOCALID3:contains]- >(LOCALID4:container { ContainerID: "87132" }),
(LOCALID0)-[LOCALID5:contains]- >(LOCALID6:container { ContainerID: "47490" }),
(LOCALID0)-[LOCALID7:contains]- >(LOCALID8:container { ContainerID: "13157" }),
(LOCALID0)-[LOCALID9:contains]- >(LOCALID10:container { ContainerID: "22676" })

This will create the container pattern provided that LOCALID0 is matched, else it will not.

If you were looking to create the ship + container pattern if the ship is not found(and create this pattern once only), then you might try:

MERGE (LOCALID0:Ship { ShipID: "12345", ShipName: "Phil's Yacht" })
CREATE UNIQUE
(LOCALID0)-[LOCALID1:contains]- >(LOCALID2:container { ContainerID: "91812" }),
(LOCALID0)-[LOCALID3:contains]- >(LOCALID4:container { ContainerID: "87132" }),
(LOCALID0)-[LOCALID5:contains]- >(LOCALID6:container { ContainerID: "47490" }),
(LOCALID0)-[LOCALID7:contains]- >(LOCALID8:container { ContainerID: "13157" }),
(LOCALID0)-[LOCALID9:contains]- >(LOCALID10:container { ContainerID: "22676" })

Upvotes: 2

Related Questions