Graph Academy: MERGE

In Creating Nodes and Relationships In Neo4j 4.x course - Merging Data in the Graph section, Question 3

Given this MERGE clause. Suppose that the p and m nodes exist in the graph, but you do not know whether the relationship exists. What are your options to process this MERGE clause?

Cypher

MATCH (p {name: 'Jane Doe'}),(m:Movie {title:'The Good One'})
MERGE (p)-[rel:ACTED_IN]->(m)
SET rel.role=['role']

Select the correct answers.

  1. Use the default behavior. The relationship will be created if it doesn’t exist.
  2. Specify ON CREATE to perform additional processing when the relationship is created.
  3. Specify ON MATCH to perform additional processing when the relationship is not created.
  4. Specify ON DELETE to perform additional processing when the relationship is deleted.

The given answer is 1, 2 and 3.

However, I thought that the answer should just be 1. This is because MERGE (p)-[rel:ACTED_IN]->(m) would create the relationship if it didn't already exist and nothing would be created if it already existed. Either way rel would be available for SET rel.role=['role'].

In any case, since we wouldn't know if the relation already existed or not, we would not know whether to use ON CREATE or ON MATCH, right?

Hi rogeryu,

you are correct in saying that " Either way rel would be available for SET rel.role=['role'] ."
However, there might be additional properties you would want to set if the relationship existed before or not.

I also get your confusion as to how to use ON CREATE and ON MATCH. Let me give you an example:

Assume you would like to keep track of which user created which edge:

MATCH (p {name: 'Jane Doe'}),(m:Movie {title:'The Good One'})
MERGE (p)-[rel:ACTED_IN]->(m)
ON CREATE SET rel.createdByUser = 'user1'

This now means "if the edge is created then the attribute 'createdByUser' is going to be set. If the edge is not created but matched, then nothing happens".

Here is some other example: cypher - Neo4J RelationShips MERGE ONCREATE ONMATCH - Stack Overflow

Regards,
Elena

1 Like