ON CREATE SET is an optional Cypher subclause of MERGE. MERGE first looks for the pattern named in the query. When it must create the node, ON CREATE SET assigns properties that belong only on that newly created node. When the node already exists, these assignments do not run. section 3.1.7
Use a stable, unique identifier in MERGE, then keep extra attributes in ON CREATE SET. This separates the property used to find a Person, User, or Tweet from properties such as location, creation time, text, and registration time that should be initialized only once. section 3.1.7 section 3.2.5
Initialize a person only when it is new
This query finds a Person named Amy or creates one. A newly created node receives location and createdAt. An existing node instead receives updatedAt through ON MATCH SET. MERGE (t:Person {name:"Amy"}) ON CREATE SET t.location = "Taj Mahal", t.createdAt = datetime() ON MATCH SET t.updatedAt = datetime() section 3.1.7
This pattern is especially useful during imports. For each CSV row, MERGE can locate or create a User by id, while ON CREATE SET copies the user details only for new nodes. Re-running an import therefore avoids creating duplicate nodes while preserving the initialization behavior. section 3.2.5
Listing 3.37 Cypher query that imports user information from a CSV file
LOAD CSV WITH HEADERS FROM "https:/ /bit.ly/39JYakC" AS row
MERGE (u:User {id:row.id})
ON CREATE SET u.name = row.name,
u.username = row.username,
u.registeredAt = datetime(row.createdAt)
Inspect a CSV import that merges each User by id and initializes name, username, and registration time only upon creation. section 3.2.5
Import tweets without rewriting existing tweet properties
Merge each Tweet by its id, then initialize its text and creation time only if the Tweet is new. The query can separately merge the PUBLISH relationship from the matching author. section 3.2.5
