正确使用CREATE UNIQUE和/或MERGE,例如

时间:2014-02-13 19:48:48

标签: neo4j cypher

以下查询:

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" } )

给出以下错误:

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

当我重复使用其中一个Cypher ID时,我必须继续重用其属性吗?问题是它没有意识到LOCALID0:Ship {ShipID:" 12345",ShipName:" Phil' Yacht"}是与LOCALID0相同的节点?

1 个答案:

答案 0 :(得分:2)

不,您只需重复使用标识符:

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" })

这将创建容器模式,前提是LOCALID0匹配,否则不会。

如果您没有找到船只,那么您正在寻找船舶+集装箱模式(和 只创建一次这个模式,然后你可以尝试:

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" })