Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
07-02-2021 04:34 PM
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 thisMERGE
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.
- Use the default behavior. The relationship will be created if it doesn’t exist.
- Specify ON CREATE to perform additional processing when the relationship is created.
- Specify ON MATCH to perform additional processing when the relationship is not created.
- 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?
07-05-2021 12:14 AM
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
All the sessions of the conference are now available online