使用WHERE子句在节点之间创建关系并在Neo4j中使用ID

时间:2017-10-02 13:21:33

标签: neo4j cypher

我有两个名为Room(4)和Houses(4)的节点。它们是通过以下方式创建的:

CREATE (n:Room { code: 1})
CREATE (n:Room { code: 1})
CREATE (n:Room { code: 1})
CREATE (n:Room { code: 1})

CREATE (n:House { code: 1})
CREATE (n:House { code: 2})
CREATE (n:House { code: 3})
CREATE (n:House { code: 4})

这些是我试图在节点之间创建的一些关系

MATCH (room:Room), (house:House{code:1})
WHERE id(room) = 40
CREATE UNIQUE (room)-[:PLACED_IN]->(house) ;
MATCH (room:Room), (house:House{code:2})
WHERE id(room) = 41
CREATE UNIQUE (room)-[:PLACED_IN]->(house) ;
MATCH (room:Room), (house:House{code:3})
WHERE id(room) = 42
CREATE UNIQUE (room)-[:PLACED_IN]->(house) ;

以前没有定义过ID,因此应该根据ID创建新的房间,还是应该在创建时手动添加ID,因为当前由于WHERE子句而没有创建关系?

1 个答案:

答案 0 :(得分:1)

将您的查询更改为:

// match room by internal id
MATCH (room:Room)
WHERE id(room) = 40
// merge will create a relationship between `room.id = 40`
// and `house.code = 1`. If `house.code = 1` does not exists, it will be created
MERGE (room)-[:PLACED_IN]->(:House {code:1}) ;
MATCH (room:Room)
WHERE id(room) = 41
MERGE (room)-[:PLACED_IN]->(:House {code:2}) ;
MATCH (room:Room)
WHERE id(room) = 42
MERGE (room)-[:PLACED_IN]->(:House {code:3}) ;

一些提示:

  • 避免依赖Neo4j内部IDs因为不安全。删除节点和关系时Neo4j reuses these IDs

  • CREATE UNIQUE已弃用。请改用MERGE