Suppose we do not know if we have the movie Rocketman in our graph.
If it is not in the graph, we want to set the createdAt property with the value of datetime()
.
The datetime()
function returns the current date and time.
If it is in the graph, we want to set the matchedAt property with the value of datetime()
.
In either case, we want to set the updatedAt property with the value of datetime()
.
Modify the Cypher code in the sandbox to use MERGE
processing for the Movie node with the title Rocketman:
-
If the node already exists (
ON MATCH SET
clause):-
Set the matchedAt property for the node referenced by m to datetime().
-
-
If the node does not exist (
ON CREATE SET
clause):-
Set the createdAt property to datetime().
-
-
For either case:
-
Set the updatedAt property to datetime().
-
Execute your code twice to ensure that the the MERGE
processing occurs.
That is, the newly created node will have a createdAt property and the updated node will have a matchedAt property.
In both cases, the node will have the updatedAt property set.
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 matchedAt.
In addition, you must use 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 matchedAt
property will be null.
If the node already exists, the createdAt
property will not be set, but a matchedAt
property will be set.
For both conditions above, the updatedAt
property will be set to the current date and time.
/* First Run - only createdAt and updatedAt will be set */
MERGE (m:Movie {title: 'Rocketman'})
/* perform the ON MATCH setting of the matchedAt property */
ON MATCH SET m.matchedAt = datetime()
/* perform the ON CREATE setting of the createdAt property */
ON CREATE SET m.createdAt = datetime()
/* set the updatedAt property */
SET m.updatedAt = timestamp()
RETURN m.title, m.createdAt, m.matchedAt, m.updatedAt;
/* Second Run - all three properties will be set */
MERGE (m:Movie {title: 'Rocketman'})
/* perform the ON MATCH setting of the matchedAt property */
ON MATCH SET m.matchedAt = datetime()
/* perform the ON CREATE setting of the createdAt property */
ON CREATE SET m.createdAt = datetime()
/* set the updatedAt property */
SET m.updatedAt = timestamp()
RETURN m.title, m.createdAt, m.matchedAt, m.updatedAt
If you run this query twice, you will see that the matchedAt
property isn’t set the first time as the movie is created, but will be set to the current date and time on the second run.
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.