iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥅

Knowledge Graph Vol. 9: Mastering the MATCH Clause in Neo4j to Deep Dive into Knowledge Graphs

に公開
2025/12/26

Introduction

To ensure Neo4j Desktop runs smoothly, I took on the challenge of expanding the memory of my old PC. Although I struggled for two days with stuck screws on the back cover, I finally succeeded! Now I have an environment where I can fully immerse myself in the world of knowledge graphs without worrying about resource shortages.

Following up on my previous post, this continues from Chapter 3 of the "Knowledge Graph Construction Guide."
"The foundation of Cypher queries is the MATCH clause. The MATCH clause is used when querying the database for records that match a specific pattern in the knowledge graph."
I will focus particularly on this part and share my takeaways in this blog post.

In this article, I will summarize what I have learned about data exploration (graph-local queries) using the "MATCH clause," the true essence of graph databases.


1. Exploring Knowledge Graphs: Basics of the MATCH Clause

While I learned about data registration (MERGE) and deletion (DELETE) in my previous study, this time I focused on "how to extract information from stored data."

The Essence of the MATCH Clause and "Graph-Local Queries"

The MATCH clause is a pattern-matching mechanism that instructs the database to "find a pattern of this shape."

Binding: When you write MATCH (p:Person) -[:LIVES_IN]-> (:Place {city: 'Berlin'}), the "Berlin" on the right is a known part where the location is already specified. In contrast, (p) on the left is an unknown part that searches for and assigns (binds) items that meet the criteria.

What is a Graph-Local Query?

A query that explores information surrounding a specific node (e.g., a place called Berlin) as a starting point is called a "graph-local query." Instead of scanning all data, you place a pin at a specific point (e.g., Berlin) and explore only what is connected to it in the immediate vicinity (locally).

  • Why it is important: Even if the database becomes huge, as long as you start from a specific node, the search scope is limited, so the response speed is not affected by the total amount of data and is always kept fast.
// Who lives in Berlin?
MATCH (p:Person) -[:LIVES_IN]-> (:Place {city: 'Berlin', country: 'DE'})
RETURN (p)

In this query, the following processing takes place:

  • Pattern Specification: You specify the known node called Berlin using (:Place {city: 'Berlin', ...}).

  • Binding to a Variable: The :Person node that matches the criteria is bound (linked) to the variable p.

  • Reuse and Return: By using RETURN on the bound variable p, you can extract specific individuals (e.g., Rosa) as a result.

Why are Graph-Local Queries Fast?

As an example, while my database currently contains 247,823 nodes, a query starting from a specific field (1 node) does not scan the entire database, but only explores the few dozen nodes connected to it.

Measured Example:

  • Full data scan: Several seconds to tens of seconds
  • Graph-local query: Tens of milliseconds

This difference becomes more pronounced as the amount of data increases.


2. Preventing Data Duplication with "MERGE" and "Unique Constraints"

The definitive difference between traditional databases (RDBMS/Relational Databases) and graph databases lies in how they handle "relationships."

  • Traditional DB (RDBMS): Data is saved in "tables." To connect data points, heavy calculation processing called "JOIN" is required at runtime.

  • Graph Database: Connections (arrows) themselves are stored alongside the data.

Advantage: When looking for information like "Person A and Person B are friends," you don't need to search through tables; you simply follow the pre-existing lines, allowing complex connections to be processed at high speed.

One unavoidable issue when expanding data is the "duplication problem." Simply repeating CREATE will result in multiple nodes being created for the same entity (e.g., the city of London).

Data Storage and Advanced Queries on "Known Nodes"

When building a knowledge graph, you first register "core information (known nodes)" and then expand from there.

Storage: Using clauses like MERGE, you first confirm "unique entities that do not allow duplication (e.g., specific pesticides or fields)."

Advanced Queries: This refers to expanding exploration from a "specific node" you already know to nodes several steps away.

Example: Queries that span multiple hops (stepping stones), such as "this field" -> "pesticides used there" -> "crops applied to" -> "cultivation standards," are something the graph model excels at.

Points to Note for the MERGE Clause

While MERGE is a powerful syntax that means "match or otherwise create," be aware that it applies to the entire pattern. Since partial matches are not performed, it can lead to unintended duplication.

Utilizing Unique Constraints

The "rule" to prevent this is the unique constraint.

CREATE CONSTRAINT no_duplicate_cities FOR (p:Place) 
REQUIRE (p.country, p.city) IS NODE KEY

By setting it up this way, you can safely refuse the creation of nodes where the combination of city name and country name is duplicated at the database level.


3. Practice: Flexible Graph Updates and Deletions

Knowledge graphs are not static; they grow by repeatedly performing updates (SET) and deletions (REMOVE).

  • Adding/Updating Properties: You can add information to an existing node like SET p.dob = "1990-01-01".

  • Deleting Properties or Labels: By using REMOVE, it is possible to delete specific attributes or labels without deleting the node itself.


Closing: Next Steps Toward "Deep Exploration"

So far, the focus has been on exploring paths of length 1 (adjacent nodes), but the true value of knowledge graphs lies in "deep exploration." For example, even queries that trace a "friend of a friend" can be realized with minimal computational cost in Neo4j.

Practical Example: Deep Exploration in Agricultural Data

In the agricultural record system I am currently developing, I am actually performing multi-hop explorations like the following:

// Field -> Work -> Work Type -> Parent Work Type
MATCH (f:Fude {name: 'Hanazono_Ochouzu_01'})<-[:PERFORMED_AT]-(wi:WorkInstance)
-[:HAS_WORK_TYPE]->(child:WorkType)-[:broader]->(parent:WorkType)
RETURN f.name, wi.work_date, parent.label, child.label

This query involves a 4-hop exploration, but it can be executed at high speed due to the characteristics of graph databases.

As a Next Step

Looking ahead, I would like to deepen my theoretical understanding of complex queries like those I use in my actual agricultural record system through text. Practical deep exploration:

  1. Variable-length paths: Finding "all crops that can use this pesticide"
  2. Aggregation queries: Calculating "work density by district"
  3. Time-series analysis: Discovering "correlation between temperature and work patterns"

These are all applications of graph-local queries. With an environment powered up by increased memory, I look forward to tackling these complex pattern-matching challenges next.

References

First Knowledge Graph Construction Guide Author: Jesús Barrasa, Jim Webber
https://book.mynavi.jp/ec/products/detail/id=144556

Discussion