Creating relationships between nodes with WHERE clause and using ID in Neo4j

こ雲淡風輕ζ 提交于 2020-01-15 19:17:17

问题


I have two nodes named Room(4) and Houses(4). They have been created in the following way:

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

These are some of the relations that i am trying to create between the nodes

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) ;

The ID's have not been defined before so it should be creating new rooms based on ID's or should i add the ID's manually while creating as currently the relationships are not being created due to WHERE clause?


回答1:


Change your query to:

// 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}) ;

Some tips:

  • Avoid depending on Neo4j internal IDs because the are not safe. Neo4j reuses these IDs when nodes and relationships are deleted.

  • CREATE UNIQUE is deprecated. Use MERGE instead.



来源:https://stackoverflow.com/questions/46526337/creating-relationships-between-nodes-with-where-clause-and-using-id-in-neo4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!