Neo4j - 从 JSON 列表创建关系



我正在学习如何使用Neo4j,并且正在使用JSON文件中的一些数据构建一个相当大的社交网络。

文件结构如下所示:

{
    "users": [
                {"id":"1", "name":"Bob", friends: ["2","3"]},
                {"id":"2", "name":"Alice", friends: ["1"]},
                {"id":"3", "name":"Robert", friends: ["1","4","5"]},
                ...
    ]    
}

按照本指南,我设法使用以下Cypher查询创建了所有节点:

WITH {json} AS data
UNWIND data.users AS user
MERGE (u:User {user_id: user.id, name: user.name})

但是现在我陷入了困境,我不太确定如何在friends字段中定义的节点之间创建关系。我也应该UNWIND friends领域吗?我是否应该以某种方式迭代我创建的每个节点并添加与其朋友的关系?也许这是一个基本问题,但我才刚刚从Cypher开始。

是的,您也应该UNWIND friends列。您可以再次传递同一组数据,通过id找到用户及其朋友,然后将它们连接起来。

这样的东西会起作用

WITH {json} AS data
UNWIND data.users AS user
// for each collection of friends
UNWIND user.friends as friend
// find the current user and their friends
MATCH (u:User {user_id: user.id}), (f:User {user_id: friend})
MERGE (u)-[:FRIENDS]-(f)

最好只找到用户一次,而不是为每个朋友找到,然后在单独的子句中匹配每个朋友并将它们连接起来。

WITH {json} AS data
UNWIND data.users AS user
// first create/find the user in the graph
MATCH (u:User {user_id: user.id})
WITH user, u
// iterate through each collection of friends
UNWIND user.friends as friend
// find each friend
MATCH (f:User {user_id: friend})
// hook them up
MERGE (u)-[:FRIENDS]-(f)

或者你可以在列表中的一次通过中做到这一点......

WITH {json} AS data
UNWIND data.users AS user
// first create/find the user in the graph
MERGE (u:User {user_id: user.id})
ON CREATE SET u.name = user.name
WITH u, user
// iterate through each collection of friends
UNWIND user.friends as friend
// find/create stub for each of the friends
MERGE (f:User {user_id: friend})
// hookup friends
MERGE (u)-[:FRIENDS]-(f)

最新更新