Adding or Updating a Movie

In this challenge, you will use ON MATCH and ON CREATE clauses to add the date and time when nodes are created and updated.

Your task is to create a Cypher script which will add createdAt and updatedAt to Movie nodes:

  1. The createdAt property should be set to the current date and time when the node is created.

  2. If the node already exists, the updatedAt property should be set.

Update this Cypher statement, replacing the ????, to use ON CREATE and ON MATCH clauses to set the createdAt and updatedAt properties.

cypher
MERGE (m:Movie {title: 'Rocketman'})
ON ????? SET m.????? = datetime()
ON ????? SET m.????? = datetime()
SET m.tagline = "The Only Way to Tell His Story is to live His Fantasy.",
    m.released = 2019
RETURN m

The first time you run the code, the createdAt property should be set. The second time, the updatedAt property should be set.

You can check the values have been set correctly by running the following query:

cypher
MATCH (m:Movie {title: 'Rocketman'})
RETURN m.title, m.createdAt, m.updatedAt

Validate Results

Once you have run the MERGE statement twice, click the Check Database button and we will check the database for you.

Hint

You must use ON CREATE SET to set createdAt. You must use ON MATCH SET to set updatedAt.

Solution

The following query uses a MERGE clause to find or create a :Movie node with the title Rocketman.

When initially created, the createdAt property will be set but the updatedAt property will be null.

If the node already exists, the createdAt property will not be set, but a updatedAt property will be set.

cypher
MERGE (m:Movie {title: 'Rocketman'})
ON CREATE SET m.createdAt = datetime()
ON MATCH SET m.updatedAt = datetime()
SET m.tagline = "The Only Way to Tell His Story is to live His Fantasy.",
    m.released = 2019
RETURN m

You will need to run this query twice to see the createdAt and `updatedAt properties.

Summary

In this challenge, you demonstrated how to add or update properties when a node is created or found in the graph. In the next lesson, you will learn how to delete nodes and relationships from the graph.