Relationships

In this lesson, you will:

  • Learn how to create relationships based on data in a CSV file

  • Create ACTED_IN relationships between the Person and Movie nodes.

Creating relationships

The acted_in.csv file contains the following data:

  • movieId - the movieId property of the Movie node

  • person_tmdbId - the tmbdId property of the Person node

  • role - the role the person played in the movie

To create the ACTED_IN relationship, you will need to:

  1. LOAD CSV data from the acted_in.csv file.

  2. MATCH the relevant Person and Movie nodes.

  3. Use MERGE to create the ACTED_IN relationship between the matched Person and Movie nodes.

Review the Cypher statement below, which creates the ACTED_IN relationships between the Person and Movie nodes.

cypher
LOAD CSV WITH HEADERS
FROM 'https://data.neo4j.com/importing-cypher/acted_in.csv' AS row
MATCH (p:Person {tmdbId: toInteger(row.person_tmdbId)})
MATCH (m:Movie {movieId: toInteger(row.movieId)})
MERGE (p)-[r:ACTED_IN]->(m)
SET r.role = row.role

Try to identify:

  • The 2 MATCH clauses that find the appropriate Person and Movie nodes using the movieId and person_tmdbId properties.

  • The MERGE clause that creates the ACTED_IN relationship between the matched p and m nodes

  • The SET clause that sets the role property of the ACTED_IN relationship r.

This approach of `MATCH`ing 2 nodes and `MERGE`ing a relationship between them is a typical Cypher pattern.

ACTED_IN relationship

Run the Cypher statement to create the ACTED_IN relationships.

cypher
LOAD CSV WITH HEADERS
FROM 'https://data.neo4j.com/importing-cypher/acted_in.csv' AS row
MATCH (p:Person {tmdbId: toInteger(row.person_tmdbId)})
MATCH (m:Movie {movieId: toInteger(row.movieId)})
MERGE (p)-[r:ACTED_IN]->(m)
SET r.role = row.role

To verify that you created the ACTED_IN relationships successfully, run the following Cypher statement to find people who acted in movies:

cypher
MATCH (p:Person)-[r:ACTED_IN]->(m:Movie) RETURN p, r, m LIMIT 25

Check Your Understanding

Creating relationships

Which Cypher clause would you use to create a relationship?

  • LOAD

  • MATCH

  • MERGE

  • SET

Hint

Relationships are created in the same way as creating nodes.

Solution

You would use MERGE to create a relationship. For example:

cypher
MERGE (startNode)-[:RELATIONSHIP]->(endNode)

Summary

In this lesson, you learned how to create relationships between nodes from data in a CSV file.

In the next lesson, you will create the DIRECTED relationship between the Person and Movie nodes