Search code examples
databasegraphneo4jcypherbipartite

Bipartite graph projection via Cypher query Neo4j


I'm new in neo4j and Im trying to make a projection of a bipartite graph of users and movies that they rated. Here is the information that I have:

enter image description here

I create the graph in Neo4j and this is what I got:

enter image description here

I'm trying to do a projection to connect users who rated movies with the SAME rating, but I have not been successful. This is the code that I have for the projection:

MATCH (u:User)-[r:RATED_MOVIE]->(m:Movie) 
WITH m, collect(u) as users, collect(r) as raitings, count(r) as weights
UNWIND users as u1
UNWIND users as u2
UNWIND raitings as r1
UNWIND raitings as r2
WITH  u1, u2, r1, r2
WHERE u1.UserId < u2.UserId and r1.rating = r2.rating
CREATE (u1)-[:CONNECTED{common_movies_rated:weights}]->(u2)
RETURN u1, u2

The expected output is a graph like this:

enter image description here


Solution

  • Good description, thanks for specifying the desired output.

    What you are looking for are paths where two people give the same rating to the same movie, and then count those occurrences between the two people to get the weight so you can create the relationship between them.

    We can use a simpler query to get the results you need.

    MATCH (u1:User)-[r:RATED_MOVIE]->(m:Movie)<-[r2:RATED_MOVIE]-(u2)
    WHERE id(u1) < id(u2) AND r.rating = r2.rating
    WITH u1, u2, count(m) as weight
    CREATE (u1)-[:CONNECTED {common_movies_rated:weight}]->(u2)
    RETURN u1, u2