0
votes

I'm trying to build a Cypher query which will connect an actor to the movie, or update existing relationship with new values of relationship property. I'm thinking of something like this:

MATCH (actor:Person{name:"Tom Hanks"})
MATCH (movie:Movie{title:"Cloud Atlas"})
OPTIONAL MATCH (actor)-[r:ACTED_IN]->(movie)
SET r.roles = ['Role 1', 'Role 2']

This works fine for the actors and movies which came from the example in Neo4j and are already connected, but not when I try to create new relationship, because r is null and cannot be updated.

So, how can I update r.roles if the relationship r exists or create a new relationship if it doesn't?

1

1 Answers

2
votes

You want to use MERGE, which creates a pattern if it doesn't exist, otherwise it is retrieved:

MATCH (actor:Person{name:"Tom Hanks"})
MATCH (movie:Movie{title:"Cloud Atlas"})
MERGE (actor)-[r:ACTED_IN]->(movie)
SET r.roles = ['Role 1', 'Role 2']

You should also check out ON CREATE SET and ON MATCH SET, which will allow you to do different things depending on if the pattern was created or retrieved:

MATCH (actor:Person{name:"Tom Hanks"})
MATCH (movie:Movie{title:"Cloud Atlas"})
MERGE (actor)-[r:ACTED_IN]->(movie)
    ON MATCH SET r.roles = ['Role 1', 'Role 2']
    ON CREATE SET r.roles = ['Role 3', 'Role 4']