Neo4j - 从JSON列表创建关系

时间:2017-06-21 12:20:54

标签: json graph neo4j cypher

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

文件结构如下所示:

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

关注this guide我设法使用以下 Cypher 查询创建所有节点:

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

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

1 个答案:

答案 0 :(得分:0)

是的,您也应该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)