使用NEO4j显示具有多个关系的节点

时间:2015-06-11 14:31:38

标签: neo4j cypher nodes relationship graph-databases

我使用以下代码创建了一个图表。如何不仅返回节点,还返回每个用户连接到多个视频的时间和位置以及每个视频是否连接到多个用户的关系?

CREATE CONSTRAINT ON (u:User) ASSERT u.user IS UNIQUE;
CREATE CONSTRAINT ON (v:Video) ASSERT v.video IS UNIQUE;

USING PERIODIC COMMIT 100000
LOAD CSV WITH HEADERS FROM 'asdfjkl;' AS line
WITH distinct line.user as user_data
MERGE (:User {user: user_data });

USING PERIODIC COMMIT 100000
LOAD CSV WITH HEADERS FROM 'asdfjkl;' AS line
WITH distinct line.video as video_data
MERGE (:Video {video: video_data });

USING PERIODIC COMMIT 100000
LOAD CSV WITH HEADERS FROM 'asdfjkl;' AS line
MATCH (u:User {user: line.user })
MATCH (v:Video {video: line.video})
MERGE (u)-[:VIEW]->(v);

2 个答案:

答案 0 :(得分:4)

根据更新后的问题进行编辑 - 获取连接到多个视频的用户的节点和关系:

MATCH (u:User)-[r:VIEW]->(:Video)
WITH u, count(r) AS count
WHERE count > 1
MATCH (u)-[r:VIEW]->(v:Video)
RETURN u,r,v;

获取连接到多个用户的视频的节点和关系:

MATCH (:User)-[r:VIEW]->(v:Video)
WITH v, count(r) AS count
WHERE count > 1
MATCH (u:User)-[r:VIEW]->(v)
RETURN u,r,v;

注意,在这两种情况下,既然你想要关系,你也会得到每一个u,r,v的行。如果您不想要人际关系,您可以收集所有视频,例如:

   MATCH (u:User)-[r:VIEW]->(:Video)
   WITH u, count(r) AS count
   WHERE count > 1
   MATCH (u)-[r:VIEW]->(v:Video)
   RETURN u,collect(v);

最后,为了让用户观看多个视频,多个用户观看了该视频:

MATCH (u:User)-[r:VIEW]->(:Video)
WITH u, count(r) AS count
WHERE count > 1
MATCH (u)-[r:VIEW]->(v:Video)<-[r2:VIEW]-(other:User)
RETURN u,r,v,collect(other);

答案 1 :(得分:0)

要列出多次查看的节点,此查询(与您的查询几乎相同)应该有效:

MATCH ()-[r:VIEW]->(h)
WITH h, COUNT(r) as rel_cnt
WHERE rel_cnt > 1
RETURN h;

您的查询从未定义r变量,并且会产生错误。