iTranslated by AI
Knowledge Graphs Vol. 8: Cypher Basics and the Magic of the MERGE Clause
Introduction
I am currently building a farm work recording system that combines Neo4j and CAVOC (Farm Work Ontology). While I was impressed by the visual syntax of Cypher last time, this time I went a step further and learned about "Updating, Deleting, and Ensuring Uniqueness" in data.
Specifically, I will organize the "fear" of ending up with a pile of junk data if you blindly repeat CREATE, and the powerful mechanism of the MERGE clause used to solve it, based on the contents of Chapter 3 of the "Knowledge Graph Construction Guide."
1. Deleting Data: DELETE and DETACH DELETE
While studying, I needed to clean up my database because I had accumulated too much test data. That's when I learned about two ways to delete data.
| Clause | Behavior | Note |
|---|---|---|
DELETE |
Deletes nodes that match the criteria. | It will result in an error if the node has existing relationships (arrows). |
DETACH DELETE |
Deletes the node along with all connected relationships. | Useful for completely cleaning up the graph, but needs to be used carefully due to its wide impact. |
I felt that the behavior of DELETE, which "does not delete automatically if relationships exist," is a safety feature characteristic of graph databases to protect data integrity.
2. The Trap of CREATE and Avoiding Duplicates with MERGE
This was the biggest takeaway from this session.
"The CREATE clause always creates new data."
For example, if you CREATE the same place node "Kumamoto City" multiple times, a large number of "separate Kumamoto City nodes that just happen to have the same name" will be generated in the database. This prevents the connections from functioning as a knowledge graph.
This is where the MERGE clause comes in.
MERGE Clause = "Match if it exists, Create if it doesn't"
MERGE first searches to see if the specified pattern already exists:
- If it exists: Reuses (matches) that node.
- If it doesn't exist: Creates (creates) a new one.
It performs this exclusive processing atomically.
// Create or match a node representing London, UK
MERGE (london:Place {city: 'London', country: 'UK'})
With this single line, you can "prevent duplicates while ensuring the node is available as a variable." In the context of farm work records, this is an essential operation when linking new work records without creating duplicate "same field nodes."
3. The Ironclad Guard via CONSTRAINT
As a more advanced concept, I learned the importance of setting up "CONSTRAINTS" on the database side, rather than relying solely on MERGE.
// Constraint to ensure the combination of city and country is unique
CREATE CONSTRAINT FOR (p:Place) REQUIRE (p.city, p.country) IS NODE KEY
By applying a constraint like this, you can distinguish between, for example, "London, UK" and "London, Ontario," while preventing the registration of duplicate data at the system level.
4. What is Variable Binding?
The aspect that piqued my interest the most in this reading range was variable binding.
Since I felt my understanding was shallow, I decided to dig a little deeper.
4.1. "Binding" means giving a "Nickname" (Variable)
When you write (n:Person {name: 'Rosa'}) in a Cypher query, the n is the variable (nickname).
- Before binding: You need a long explanation like "The Person node with the name 'Rosa'."
- After binding: You can refer to that node simply by calling it "that thing (n)."
4.2. Why does binding make subsequent processing smooth?
This "nickname" really shows its true value when creating relationships (arrows). Let's look at the following query:
// 1. MERGE Rosa and bind it to variable 'r' (assign a nickname)
MERGE (r:Person {name: 'Rosa'})
// 2. MERGE Berlin and bind it to variable 'b'
MERGE (b:Place {city: 'Berlin'})
// 3. Draw an arrow from 'r' to 'b'
MERGE (r)-[:LIVES_IN]->(b)
What if there was no "binding"?
You would have to rewrite the entire node information every time you create a relationship.
MERGE (:Person {name: 'Rosa'})-[:LIVES_IN]->(:Place {city: 'Berlin'})
With this approach, when you create a complex graph (e.g., when one person relates to multiple locations), you have to write the same thing over and over, which increases the chance of errors.
- Advantages of using variable binding:
Once defined, it's ready to go: Once you assign a "nickname," you can connect relationships simply by calling that name (r or b).
Shorter queries: Even after searching for nodes with complex conditions, using variables allows you to connect to the next process smartly.
4.3. The "Magic" of Combining with MERGE
The form MERGE (n:Label {prop: 'val'}) used in this book is the most frequently used pattern in practice.
Search or Create: Searches if the node exists in the database; if not, it creates it.
Binding: Fixes the node found (or created) as the variable n.
Utilization: You can add new labels to n or connect it to other nodes in the very next line.
4.4 Summary: Practical Example in a Farm Work Recording System
For instance, let's imagine tying "today's work (w)" to "Field A (f), where we usually work."
-
MERGE (f:Field {name: 'Field A'})gives the nicknamefto Field A. -
CREATE (w:WorkInstance {date: '2025-12-21'})defines today's work asw. MERGE (w)-[:PERFORMED_IN]->(f)
By just writing this, the relationship "today's work was done in Field A" is complete.
This ability to "determine the target, assign a nickname, and connect" in one seamless flow is the brilliance of "variable binding."
Summary: The Hidden Side of "Intuition" Found Through Copying Queries
By actually moving my hands and copying the queries, I gained the following realizations:
-
Variable Binding: The flow of binding a node to a variable
nlikeMERGE (n:Label {prop: 'val'})and connecting it to subsequent processes (like relationship creation) is extremely smooth. -
Ensuring Idempotency: The peace of mind provided by
MERGE, which maintains the same state no matter how many times it is executed. - Beauty of the Graph: A clean graph without duplicates is the source of "self-explanatory power."
I was able to delve into "variable binding," which I wasn't confident about, and deepened my understanding. Parts that I previously left entirely to AI are beginning to settle as my own "knowledge," and writing Cypher is becoming more and more fun. Next, I will challenge myself with building even more complex relationships and advanced data extraction!
References
Handbook for Building Knowledge Graphs (Authors: Jesús Barrasa, Jim Webber)
Discussion