MERGE clause tries to match the query pattern in database or, if not present, create the pattern in database. MERGE <pattern> can be interrepted as If MATCH <pattern> then RETURN <pattern> ELSE CREATE <pattern>. Note that there is no notion of partially matching of the pattern
and creating the remaining parts. That is, either the whole pattern is matched or the whole pattern is created.
Similar to INSERT ON CONFLICT in SQL, MERGE clause comes with ON CREATE and ON MATCH set operation allowing users to specify additional update logic if the pattern is (not) found.
We will use the example database for demonstration, whose schema and data import commands are given here.
Merge Nodes
Merge Existing Nodes
The following query tries to merge a user with name “Adam”. Since user “Adam” exists in the database, no user is created.
Merge Non-existing Nodes
The following query tries to merge a user with name “Bob”. Since user “Bob” does not exist in the database, a new user with name “Bob” is created.
Merge with ON MATCH
ON MATCH specifies the SET operation once a match is found. The followng query updates age property if pattern is matched.
Merge with ON CREATE
ON CREATE specifies the SET operation if no match is found. The following query updates age property if pattern is not matched.
Merge Relationships
Merge Existing Relationships
The following query tries to merge a follows edge since 2020 between “Adam” and “Zhang”. A match is found in this case.
Merge Non-existing Relationships
The following query tries to merge a follows edge since 2022 between “Adam” and “Zhang”. No match is found and an edge is created.
Merge with ON MATCH
Similar to merge nodes, the following query update edge since property if the pattern is found.
Merge with ON CREATE
Similar to merge nodes, the following query update edge since property if the pattern is not found.
Merge Complex Patterns
Previous examples have shown how to merge single node and relationship pattern. It’s also possible to merge a complex pattern involving