Show nodes with more than one relationship using NEO4j

3.8k views Asked by At

I created a graph using the following code. How do I return not only the nodes but also the relationship when and where each user is connected to more than one video and each video is connect to more than one user?

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

There are 2 answers

0
Luanne On BEST ANSWER

Edited based on the updated question- To get nodes and relationships for a user connected to more than one video:

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;

To get nodes and relations for a video connected to more than one user:

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;

Note than in both these cases, since you want the relations as well you'll get a row for each u,r,v. If you did not want relationships, you would be able to collect all videos, for example:

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

Finally, to get users that have viewed more than one video, where the video has been viewed by more than one user:

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);
0
cybersam On

To list the nodes that were viewed more than once, this query (which is almost identical with yours) should work:

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

Your query never defined the r variable, and would have generated an error.