跳轉到

RAG 中的知識圖譜:以 Neo4j 打造的真實示範

文章資訊

作者:Chuan Zhang  日期:2026-06-18

原文標題:Knowledge Graphs in RAG: A Realistic Demo with Neo4j

Medium 原連結https://chuan-zhang.medium.com/knowledge-graphs-in-rag-a-realistic-demo-with-neo4j-d07149a1e418

🎧 摘要語音

📝 重點摘要

TL;DR

知識圖譜把實體關係顯式化,讓 RAG 在多跳關聯查詢上比純向量檢索更精準可控。

核心問題

傳統 RAG 以語意相似度檢索文本片段,遇到需跨多個實體與約束條件「連線」的關聯型問題時力有未逮。本文以媒體供應鏈場景示範,如何用知識圖譜作為檢索層,補足這類多跳推理的缺口。

關鍵發現 / 數據

  • 合成資料集規模:5,000 個 Title、17,735 個 Version、53,082 筆 Rights、17,839 個本地化 Job、20,000 筆 DeliveryRequest、200 個 Client。
  • 範例查詢「Tier 1 客戶的延遲交付」回傳 18 筆 rows,皆透過顯式圖結構而非 chunk 相似度取得。
  • 每個示範問題至少橫跨 3 種節點型別、2+ 個關係跳數,純文本檢索難以回答。
  • 系統用 llama3.2 生成 Cypher、nomic-embed-text 做向量嵌入;本地端需 Docker + 8GB RAM 同時跑 Neo4j/Ollama/Weaviate。

方法亮點

  • LLM 接收「使用者問題 + 完整圖 schema」生成 Cypher,執行後再由第二次 LLM 呼叫合成接地答案。
  • Cypher 若被 Neo4j 拒絕,會把錯誤訊息回饋給 LLM 自動修復重試。
  • 將 Rights、LocalizationJob、DeliveryRequest 等「事件型」物件建模為一等節點(而非邊),承載 status、deadline 等流程狀態屬性。
  • 雙模式:Graph RAG 處理關聯型問題,Vector RAG 處理主題式內容探索。

對我的研究有用嗎?

「事件節點顯式建模」與「圖檢索作為操作層而非視覺化」兩個觀念對 GraphRAG schema 設計有參考價值。其 Text2Cypher + 錯誤回饋自我修復的 agent 流程、以及「圖定位實體路徑、文本補敘事、LLM 合成」的混合模式,是可直接借鏡的工程 pattern。

評語

工程示範清晰、可重現,但屬入門教學等級;資料為合成、缺乏 baseline 量化對比與評估指標,學術深度有限,適合快讀取觀念而非深讀。


🌐 中英對照

Author: Chuan Zhang
Published:
Source: https://chuan-zhang.medium.com/knowledge-graphs-in-rag-a-realistic-demo-with-neo4j-d07149a1e418
Fetched: 2026-06-18T16:35:18.112099


Knowledge Graphs in RAG: A Realistic Demo with Neo4j / RAG 中的知識圖譜:使用 Neo4j 的真實範例

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Retrieval-Augmented Generation (RAG) is one of the most practical ways to make large language model applications more reliable. Instead of asking the model to answer from parametric memory alone, we retrieve relevant knowledge at runtime and ground the response in that retrieved context.

檢索增強生成 (Retrieval-Augmented Generation, RAG) 是讓大型語言模型 (Large Language Model) 應用更可靠的最實用方法之一。我們不再要求模型僅憑參數化記憶 (parametric memory) 來作答,而是在執行階段檢索相關知識,並將回應建立在所檢索到的上下文之上。

It works well when the answer is mostly contained in one or two relevant passages. But many real questions are not just about finding a few matching chunks. They are about connecting entities across several constraints.

當答案大致包含在一兩段相關文字中時,這種方法運作良好。但許多真實問題不只是找到幾個匹配的文字區塊 (chunk),而是要在多個約束條件下將實體 (entity) 串連起來。

This is the gap where Knowledge Graphs become useful.

這正是知識圖譜 (Knowledge Graph, Knowledge Graphs) 派上用場的缺口。

A Knowledge Graph makes entities and relationships explicit. Instead of retrieving only chunks that look semantically similar to the question, the system can also retrieve structured facts about what is connected to what, under which conditions, and through which path.

知識圖譜讓實體與關係 (relationship) 變得明確。系統不再只是檢索與問題在語意上相似的文字區塊,還能檢索結構化的事實:什麼與什麼相連、在哪些條件下、透過哪條路徑。

This article is the practical companion to Knowledge Graphs in RAG: From Retrieval to Reasoning, which covers the conceptual foundations: why traditional RAG falls short on relational questions, what a Knowledge Graph adds to the retrieval layer, and the design patterns that work well in practice. If you haven’t read that piece yet, it’s a useful starting point. This article focuses on a concrete implementation: a synthetic but realistic media supply-chain dataset loaded into Neo4j using Python scripts, with real Cypher queries and a worked example of passing graph-retrieved context to an LLM. The data generator and loader are available in the public repository at github.com/chuan2019/knowledge-graph.

本文是 Knowledge Graphs in RAG: From Retrieval to Reasoning(《RAG 中的知識圖譜:從檢索到推理》)的實作篇姊妹作,前者涵蓋概念基礎:為何傳統 RAG 在關係型問題上力有未逮、知識圖譜為檢索層帶來什麼、以及在實務中行之有效的設計模式。如果你尚未讀過那篇文章,它是一個有用的起點。本文聚焦於一個具體的實作:使用 Python 腳本將一個合成但真實的媒體供應鏈 (media supply-chain, media supply-chain) 資料集載入 Neo4j,並搭配真實的 Cypher 查詢 (Cypher query, Cypher queries),以及一個將圖譜檢索上下文傳遞給 LLM 的完整範例。資料產生器與載入器可在公開儲存庫 github.com/chuan2019/knowledge-graph 取得。

Introduction / 引言

This section briefly recaps the motivation covered in depth in the companion article, Knowledge Graph in RAG: From Retrieval to Reasoning. If you’ve already read that piece, feel free to skip ahead to the section Demo: Media Supply-Chain Operations.

本節簡要回顧姊妹文 Knowledge Graph in RAG: From Retrieval to Reasoning 中深入探討的動機。如果你已讀過那篇文章,歡迎直接跳到 Demo: Media Supply-Chain Operations(範例:媒體供應鏈營運)一節。

Why Traditional RAG Starts to Struggle / 為何傳統 RAG 開始力不從心

In a standard RAG system, the pipeline often looks like this:

在一個標準的 RAG 系統中,流程通常如下:

  1. Split source documents into chunks.
  2. Convert chunks into embeddings.
  3. Store those embeddings in a vector database.
  4. Embed the user question.
  5. Retrieve the most similar chunks.
  6. Send the retrieved chunks to the LLM.

  7. 將來源文件切分成文字區塊。

  8. 將文字區塊轉換成嵌入向量 (embedding)。
  9. 將這些嵌入向量儲存在向量資料庫 (vector database) 中。
  10. 將使用者問題嵌入向量化。
  11. 檢索最相似的文字區塊。
  12. 將檢索到的文字區塊送給 LLM。

This is a strong baseline. But it has a structural limitation: retrieval is driven mainly by semantic similarity, not by explicit relationships among entities.

這是一個很強的基準。但它有一個結構性的限制:檢索主要由語意相似度 (semantic similarity) 驅動,而非由實體間的明確關係驅動。

That limitation becomes clearer when a question requires several joins at once.

當一個問題需要同時進行多個關聯 (join) 時,這個限制就會更明顯。

For example:

例如:

  • Which clients have active rights for a localized 4K title in a given territory?
  • Which titles have in-progress localization jobs and a delivery request that is already delayed?
  • Which delivery points in a region have mandatory specs for versions requested by Tier 1 clients?

  • 在某個特定地區,哪些客戶對某個已在地化的 4K 影片擁有有效授權?

  • 哪些影片有進行中的在地化工作,且其交付請求已經延遲?
  • 某個地區中,哪些交付點對 Tier 1 客戶所請求的版本有強制性規格要求?

These are not simply text-matching questions. They are relationship questions. A vector retriever may surface useful passages, but it does not naturally model the path from title to version to rights grant to client to region to delivery workflow.

這些不只是單純的文字匹配問題,而是關係型問題。向量檢索器 (vector retriever) 或許能找出有用的段落,但它無法自然地建模從影片到版本、到授權、到客戶、到地區、再到交付流程這樣的路徑。

That is where a Knowledge Graph can improve retrieval.

這正是知識圖譜能改善檢索之處。

What the Knowledge Graph Adds / 知識圖譜帶來了什麼

A Knowledge Graph represents information as:

知識圖譜以下列方式表示資訊:

  • nodes for entities
  • edges for relationships
  • properties for attributes on either nodes or relationships

  • 以節點 (node) 表示實體

  • 以邊 (edge) 表示關係
  • 以屬性 (property) 表示節點或關係上的特徵

The key advantage is that the system does not need to infer every relationship from prose at answer time. Many of the important relationships are already explicit in the graph.

關鍵優勢在於:系統不需要在作答時從散文文字中推斷出每一條關係。許多重要的關係在圖譜中已經是明確的。

It becomes much easier to see in a domain where versions, rights, localization, and delivery workflows all interact.

在一個版本、授權、在地化與交付流程相互交織的領域中,這一點會更容易看出來。

Demo: Media Supply-Chain Operations / 範例:媒體供應鏈營運

I chose media supply-chain operations for this demo because it naturally produces the kind of relationship-heavy questions that Knowledge Graphs handle well. Rights, versions, localization jobs, delivery points, regions, and delivery requests are all connected, and useful answers often depend on traversing several of those links at once. That makes the domain a strong fit for demonstrating how graph-based retrieval can add structure and control to a RAG pipeline.

我為這個範例選擇了媒體供應鏈營運,因為它自然會產生那種充滿關係的問題,而這正是知識圖譜擅長處理的。授權 (rights)版本 (versions)在地化工作 (localization jobs)交付點 (delivery points)地區 (regions)交付請求 (delivery requests) 全都彼此相連,而有用的答案往往取決於一次橫跨其中多個連結。這使得此領域非常適合用來展示以圖譜為基礎的檢索如何為 RAG 流程增添結構與控制力。

In this context, media supply-chain refers to the end-to-end flow of media assets and metadata from content creation and versioning through localization, rights management, packaging, and final delivery to downstream platforms, territories, and partners. It is not just about moving files; it is also about preserving the relationships among versions, entitlements, technical specifications, and operational status as content moves across systems.

在此脈絡下,媒體供應鏈指的是媒體資產與中繼資料 (metadata) 從內容創作與版本化,歷經在地化、授權管理、封裝,到最終交付給下游平台、地區與合作夥伴的端到端流程。它不只關乎搬移檔案,也關乎在內容跨系統流動時,保留版本、授權權益 (entitlement)、技術規格與營運狀態之間的關係。

The underlying data could also be modeled in a relational database, and for transactional workflows that may still be the right system of record. I use Neo4j here because the retrieval problem in KG-RAG is centered on connected paths rather than flat result sets. When the goal is to traverse several linked entities, retrieve a compact subgraph, and pass that structure to an LLM as grounded context, a graph database makes that workflow more natural to express and explain.

底層資料其實也可以用關聯式資料庫 (relational database) 來建模,對於交易型工作流程而言,那或許仍是正確的記錄系統 (system of record)。我在此使用 Neo4j,是因為 KG-RAG 中的檢索問題以相連的路徑為核心,而非以扁平的結果集為核心。當目標是要走訪多個相連的實體、檢索出一個精簡的子圖 (subgraph),並將該結構作為有依據的上下文傳給 LLM 時,圖資料庫 (graph database) 能讓這套工作流程更自然地被表達與解釋。

If you want to see how the industry is evolving in this direction, recent work around software-defined workflows, ontologies for media creation, and interoperable identifiers is a useful signal that the media supply-chain is becoming more data-driven and graph-friendly. Good starting points include MovieLabs’ The 2030 Vision, the December 2023 note on RDF and JSON releases of the Ontology for Media Creation, and the May 2025 article How to Avoid Identifier Mayhem: Best Practices.

如果你想了解產業朝這個方向如何演進,近期關於軟體定義工作流程 (software-defined workflows)、媒體創作本體論 (ontology),以及可互通識別碼 (interoperable identifiers) 的成果,是一個有用的訊號,顯示媒體供應鏈正變得更以資料為驅動、更適合圖譜化。不錯的起點包括 MovieLabs 的 The 2030 Vision、2023 年 12 月關於 RDF and JSON releases of the Ontology for Media Creation 的說明,以及 2025 年 5 月的文章 How to Avoid Identifier Mayhem: Best Practices

What makes this domain a natural fit for KG-RAG is that useful answers often require traversing several linked entities at once. Answering a delivery-risk question, for example, may require combining:

讓此領域天生契合 KG-RAG 的原因在於:有用的答案往往需要一次走訪多個相連的實體。舉例來說,回答一個交付風險 (delivery-risk) 問題,可能需要結合:

  • the Title
  • a particular Version
  • a DeliveryRequest
  • the target DeliveryPoint
  • the Region
  • any matching DeliverySpec
  • the Client that requested the delivery

  • Title(影片)

  • 某個特定的 Version(版本)
  • 一筆 DeliveryRequest(交付請求)
  • 目標 DeliveryPoint(交付點)
  • Region(地區)
  • 任何相符的 DeliverySpec(交付規格)
  • 提出該交付請求的 Client(客戶)

Instead of asking the language model to reconstruct that logic from scattered text snippets, the system can retrieve the relevant path directly and hand the LLM a grounded set of connected facts. The graph schema below reflects exactly that structure.

系統不需要要求語言模型從零散的文字片段中重建這套邏輯,而是可以直接檢索出相關的路徑,並將一組有依據的、彼此相連的事實交給 LLM。下方的圖譜結構描述 (graph schema) 正反映了這樣的結構。

Graph Schema Overview / 圖譜結構描述總覽

The sample graph is centered around media supply-chain operations. The core entities include:

範例圖譜以媒體供應鏈營運為核心。核心實體包括:

  • Title
  • Version
  • Client
  • Region
  • Language
  • DeliveryPoint
  • Rights
  • LocalizationJob
  • DeliverySpec
  • DeliveryRequest

  • Title(影片)

  • Version(版本)
  • Client(客戶)
  • Region(地區)
  • Language(語言)
  • DeliveryPoint(交付點)
  • Rights(授權)
  • LocalizationJob(在地化工作)
  • DeliverySpec(交付規格)
  • DeliveryRequest(交付請求)

At a high level, the graph looks like this:

從宏觀層面來看,圖譜長這樣:

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 1. media supply-chain operations graph

圖 1。 媒體供應鏈營運圖譜

This structure supports the kinds of multi-hop questions that appear in real enterprise workflows.

這個結構支援真實企業工作流程中會出現的那種多跳 (multi-hop) 問題。

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 2. graph schema of the media supply-chain operations graph

圖 2。 媒體供應鏈營運圖譜的圖譜結構描述

The Demo Dataset / 範例資料集

I generated a synthetic but structured dataset for a fictional media operations domain. The generator script produces CSV files for titles, versions, rights, localization jobs, delivery points, delivery specs, and delivery requests.

我為一個虛構的媒體營運領域產生了一個合成但結構化的資料集。產生器腳本會輸出影片版本授權在地化工作交付點交付規格交付請求的 CSV 檔案。

The current generated dataset contains:

目前產生的資料集包含:

  • 5,000 titles
  • 17,735 versions
  • 200 clients
  • 50 regions
  • 30 languages
  • 150 delivery points
  • 53,082 rights records
  • 17,839 localization jobs
  • 612 delivery specs
  • 20,000elivery requests

  • 5,000 部影片

  • 17,735 個版本
  • 200 個客戶
  • 50 個地區
  • 30 種語言
  • 150 個交付點
  • 53,082 筆授權記錄
  • 17,839 個在地化工作
  • 612 個交付規格
  • 20,000 筆交付請求

That scale is still manageable for a local demo, but large enough to make graph traversal meaningful.

這個規模對於本機範例而言仍可掌控,但又大到足以讓圖譜走訪 (graph traversal) 具有意義。

The main generated files are:

主要產生的檔案有:

  • kg4rag/kg-data-gen.py for data generation
  • kg4rag/kg-data-loader.py for loading the generated CSV data into Neo4j
  • kg4rag/kg_demo_data/ for the generated CSV files

  • kg4rag/kg-data-gen.py 用於資料產生

  • kg4rag/kg-data-loader.py 用於將產生的 CSV 資料載入 Neo4j
  • kg4rag/kg_demo_data/ 用於存放產生的 CSV 檔案

These files are available in the same public repository at github.com/chuan2019/knowledge-graph, which readers can use as the starting point for reproducing the demo locally.

這些檔案可在同一個公開儲存庫 github.com/chuan2019/knowledge-graph 取得,讀者可以此作為在本機重現此範例的起點。

Local Setup / 本機環境設置

The full demo runs with Docker Compose. You will need Dockerinstalled and at least 8 GB of RAM available, since Neo4j, Ollama, and Weaviate run concurrently.

完整範例使用 Docker Compose 執行。你需要安裝 Docker 並至少有 8 GB 可用記憶體,因為 Neo4jOllamaWeaviate 會同時執行。

The setup follows three steps.

設置分為三個步驟。

Step 1: Generate the CSV data / 步驟 1:產生 CSV 資料

Before starting the services, run the data generator to produce the synthetic CSV files:

在啟動服務之前,先執行資料產生器以產生合成的 CSV 檔案:

cd knowledge-graph  
uv run python kg4rag/kg-data-gen.py

Step 2: Start all services / 步驟 2:啟動所有服務

cd knowledge-graph  
docker compose - profile all up -d --build

This brings up Neo4j, Ollama, Weaviate, and the FastAPI application. On first run, Compose also pulls the required models (llama3.2 and nomic-embed-text by default) and loads the title synopses into Weaviate automatically. Model pulls can take several minutes depending on your hardware and connection speed.

這會啟動 Neo4jOllamaWeaviateFastAPI 應用程式。首次執行時,Compose 也會拉取所需的模型(預設為 llama3.2nomic-embed-text),並自動將影片劇情摘要載入 Weaviate。視你的硬體與連線速度而定,拉取模型可能需要數分鐘。

Step 3: Load the graph data into Neo4j / 步驟 3:將圖譜資料載入 Neo4j

Once the Neo4j container is healthy, load the graph:

一旦 Neo4j 容器處於健康狀態,即可載入圖譜:

cd knowledge-graph  
uv run python kg4rag/kg-data-loader.py

The loader connects to Neo4j at bolt://localhost:7687 with credentials neo4j / testpass.

載入器會以憑證 neo4j / testpass 連線到位於 bolt://localhost:7687Neo4j

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 3. Terminal output showing docker-compose — profile all up -d — build with all containers listed as running (Healthy), followed by the successful completion message from kg-data-loader.py.

圖 3。 終端機輸出顯示 docker-compose — profile all up -d — build,所有容器列為執行中(健康),接著是來自 kg-data-loader.py 的成功完成訊息。

After the data is loaded, four interfaces are available:

資料載入後,可使用四個介面:

  • Demo UI: http://localhost:8000/
  • Neo4j Browser: http://localhost:7474
  • Ollama API: http://localhost:11434
  • Weaviate API: http://localhost:8080

  • 範例 UIhttp://localhost:8000/

  • Neo4j 瀏覽器http://localhost:7474
  • Ollama APIhttp://localhost:11434
  • Weaviate APIhttp://localhost:8080

From the container list, you may have noticed that four other containers, Prometheus, Loki, Grafana, and Jaeger, are running as well. These are for service observability (metrics, logging, and tracing), and are beyond the scope of this article. If you are interested, please refer to my service observability series.

從容器清單中,你可能注意到另外四個容器 PrometheusLokiGrafanaJaeger 也在執行。這些是用於服務可觀測性 (service observability)(指標 (metrics)日誌 (logging)追蹤 (tracing)),不在本文範圍之內。如果你有興趣,請參閱我的服務可觀測性系列

The Demo Interface / 範例介面

With the services running and the data loaded, open http://localhost:8000/ in a web browser to reach the Knowledge Graph QA Service.

在服務執行且資料載入後,於網頁瀏覽器開啟 http://localhost:8000/ 即可進入知識圖譜問答服務 (Knowledge Graph QA Service)。

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 4. The browser UI at http://localhost:8000/ showing the question panel, the Graph RAG / Vector RAG model toggle, the sample question dropdown, and the four output panels: Answer, Generated Cypher, Agent Trace, and Retrieved Rows.

圖 4。 位於 http://localhost:8000/ 的瀏覽器 UI,顯示問題面板、Graph RAG / Vector RAG 模式切換、範例問題下拉選單,以及四個輸出面板:答案 (Answer)、產生的 Cypher (Generated Cypher)、代理追蹤 (Agent Trace) 與檢索到的資料列 (Retrieved Rows)。

The interface offers two retrieval modes, toggled at the top of the question panel.

此介面提供兩種檢索模式,可在問題面板頂端切換。

Graph RAG is the primary mode for this demo. You type a natural-language question, the service sends it to an LLM along with the graph schema, the LLM generates a Cypher query, and the service executes that query against Neo4j. The retrieved rows are then passed to a second LLM call to synthesize a grounded natural-language answer. If the generated Cypher is rejected by Neo4j, the service repairs it and retries automatically. The interface shows the generated Cypher, the retrieved rows, and a step-by-step agent trace alongside the final answer.

Graph RAG 是本範例的主要模式。你輸入一個自然語言問題,服務會將它連同圖譜結構描述一起送給 LLM,LLM 產生一個 Cypher 查詢,服務再對 Neo4j 執行該查詢。檢索到的資料列接著被傳入第二次 LLM 呼叫,以綜合出一個有依據的自然語言答案。如果產生的 Cypher 被 Neo4j 拒絕,服務會自動修復並重試。介面會在最終答案旁顯示產生的 Cypher、檢索到的資料列,以及逐步的代理追蹤。

Vector RAG handles content discovery questions. The question is embedded using nomic-embed-text and matched against title synopses in Weaviate by cosine similarity. The LLM synthesizes an answer from the most relevant documents. This mode is not about operational state: it answers questions like “find me science fiction titles about space exploration,” where the answer depends on thematic meaning rather than structured relationships.

Vector RAG 處理內容探索 (content discovery) 問題。問題會以 nomic-embed-text 嵌入向量化,並透過餘弦相似度 (cosine similarity, cosine similarity) 與 Weaviate 中的影片劇情摘要進行匹配。LLM 會從最相關的文件中綜合出答案。這個模式無關營運狀態:它回答的是像「幫我找出關於太空探索的科幻影片」這類問題,其答案取決於主題意涵,而非結構化的關係。

The sample question dropdown pre-loads eight questions per mode. For Graph RAG, the built-in examples include:

範例問題下拉選單為每個模式預先載入八個問題。對於 Graph RAG,內建範例包括:

  • Which Tier 1 clients have active rights for localized versions with delayed delivery requests?
  • Which active rights are expiring in the next 90 days, and which clients and regions are affected?
  • Show all high-priority delivery requests that missed their deadline, and which clients submitted them.
  • Which delivery points have the most failed or delayed delivery requests?
  • What titles have 4K or 8K versions with no delivery requests created yet?
  • Which studios have the most titles with active exclusive rights grants?

  • 哪些 Tier 1 客戶對已在地化、且交付請求延遲的版本擁有有效授權?

  • 哪些有效授權將在未來 90 天內到期,又有哪些客戶與地區受到影響?》」
  • 列出所有錯過截止期限的高優先級交付請求,以及是哪些客戶提交的。
  • 哪些交付點有最多失敗或延遲的交付請求?
  • 哪些影片有 4K 或 8K 版本,但尚未建立任何交付請求?
  • 哪些製片廠擁有最多帶有有效獨家授權的影片?

For Vector RAG, examples include:

對於 Vector RAG,範例包括:

  • Show me science fiction titles about space exploration and colonization.
  • Find animated titles about friendship, belonging, and found family.
  • What action thrillers involve government conspiracies or corruption?

  • 給我看關於太空探索與殖民的科幻影片。

  • 找出關於友情、歸屬感與「自選家庭 (found family)」的動畫影片。
  • 哪些動作驚悚片牽涉到政府陰謀或貪腐?

Any of these can be selected from the dropdown and submitted with one click. The following sections use the Graph RAG questions as concrete examples to show what the system generates and returns.

以上任一問題都可以從下拉選單中選取並一鍵提交。以下各節以 Graph RAG 的問題作為具體範例,展示系統產生與回傳的內容。

The Graph Model in Practice / 圖譜模型的實務應用

With the data loaded, it helps to see how the underlying CSV structure maps to the graph model. The two representations are close, but with one important design difference.

資料載入後,了解底層 CSV 結構如何對應到圖譜模型會很有幫助。這兩種表示法很接近,但有一個重要的設計差異。

At the relational level, the schema looks like this:

在關聯式層面上,結構描述長這樣:

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 5. Relational Data Model

圖 5。 關聯式資料模型 (Relational Data Model)

One practical design decision here is that Rights, LocalizationJob, DeliverySpec, and DeliveryRequest are modeled as nodes rather than collapsing everything into direct relationships. For a RAG system, this is useful because those records carry important operational properties such as status, deadlines, priorities, active flags, and timestamps.

這裡一個務實的設計決策是:將 RightsLocalizationJobDeliverySpecDeliveryRequest 建模為節點,而非把所有東西都壓縮成直接的關係。對於 RAG 系統而言,這很有用,因為這些記錄帶有重要的營運屬性,例如狀態 (status)截止期限 (deadlines)優先級 (priorities)有效旗標 (active flags)時間戳記 (timestamps)

It means the graph is not only a taxonomy of entities. It is also a representation of process state.

這意味著圖譜不只是實體的分類體系 (taxonomy),同時也是流程狀態 (process state) 的一種表示。

Example Questions the Graph Can Answer Well / 圖譜能良好回答的範例問題

With the above schema in place, the graph supports the kinds of multi-hop operational questions that are difficult to answer with text retrieval alone. These are the same questions available in the built-in sample dropdown in the browser UI:

有了上述結構描述,圖譜便能支援那些單靠文字檢索難以回答的多跳營運問題。以下這些問題與瀏覽器 UI 中內建範例下拉選單裡的問題相同:

  • Which Tier 1 clients have active rights for localized versions with delayed delivery requests?
  • Which active rights are expiring in the next 90 days, and which clients and regions are affected?
  • Show all high-priority delivery requests that missed their deadline, and which clients submitted them.
  • Which delivery points have the most failed or delayed delivery requests?
  • Which languages have the most completed localization jobs, and what are their average quality scores?
  • Which vendors completed the most localization jobs, and what is their average quality score?

  • 哪些 Tier 1 客戶對已在地化、且交付請求延遲的版本擁有有效授權?

  • 哪些有效授權將在未來 90 天內到期,又有哪些客戶與地區受到影響?
  • 列出所有錯過截止期限的高優先級交付請求,以及是哪些客戶提交的。
  • 哪些交付點有最多失敗或延遲的交付請求?
  • 哪些語言完成了最多的在地化工作,其平均品質分數又是多少?
  • 哪些供應商完成了最多的在地化工作,其平均品質分數又是多少?

Each of these questions spans at least three node types and two or more relationship hops. None of them can be answered well by retrieving a single passage from a document. They require the graph to traverse entity connections and apply property filters before the LLM has anything meaningful to work with.

這些問題每一個都橫跨至少三種節點類型與兩個以上的關係跳躍。它們之中沒有一個能透過從文件檢索單一段落而獲得良好的回答。它們都需要圖譜先走訪實體連結並套用屬性過濾,LLM 才會有任何有意義的內容可供處理。

Example Cypher Queries / Cypher 查詢範例

Here are a few representative examples using the generated graph structure.

以下是使用所產生圖譜結構的幾個代表性範例。

1. Active rights for localized versions / 1. 已在地化版本的有效授權

MATCH (t:Title)-[:HAS_VERSION]->(v:Version)  
MATCH (rg:Rights)-[:FOR_VERSION]->(v)  
MATCH (rg)-[:GRANTED_TO]->(c:Client)  
MATCH (rg)-[:FOR_REGION]->(r:Region)  
WHERE rg.is_active = true  
AND v.is_localized = true  
AND c.tier = 'Tier 1'  
RETURN t.title_name,  
v.version_id,  
c.client_name,  
r.region_name,  
rg.rights_type,  
rg.end_date  
LIMIT 20;

2. Delivery risk by region / 2. 依地區劃分的交付風險

MATCH (dr:DeliveryRequest)-[:FOR_VERSION]->(v:Version)  
MATCH (dr)-[:REQUESTED_BY]->(c:Client)  
MATCH (dr)-[:TO_POINT]->(dp:DeliveryPoint)-[:LOCATED_IN]->(r:Region)  
MATCH (t:Title)-[:HAS_VERSION]->(v)  
WHERE dr.status IN ['Delayed', 'Failed']  
RETURN t.title_name,  
v.version_id,  
c.client_name,  
dp.point_name,  
r.region_name,  
dr.status,  
dr.deadline  
ORDER BY dr.deadline ASC  
LIMIT 20;

3. Localization backlog / 3. 在地化積壓工作

MATCH (lj:LocalizationJob)-[:FOR_VERSION]->(v:Version)  
MATCH (lj)-[:LOCALIZED_FOR]->(l:Language)  
MATCH (t:Title)-[:HAS_VERSION]->(v)  
WHERE lj.status IN ['In Progress', 'Pending', 'QA Review']  
RETURN t.title_name,  
v.version_id,  
l.language_name,  
lj.job_type,  
lj.status,  
lj.vendor  
LIMIT 20;

These queries matter because they retrieve candidate facts through explicit graph structure rather than through chunk similarity alone.

這些查詢之所以重要,是因為它們透過明確的圖譜結構來檢索候選事實,而非僅靠文字區塊相似度。

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 6. Screenshots of the Cypher query results. (A) results of the delivery-risk by region query from the above section 2. (B) results of the localization backlog query from the above section 3.

圖 6。 Cypher 查詢結果的截圖。(A) 上述第 2 節依地區劃分交付風險查詢的結果。(B) 上述第 3 節在地化積壓工作查詢的結果。

Translating a User Question into Graph Constraints / 將使用者問題轉譯為圖譜約束

The translation from a natural-language question to a structured graph query is the core step in KG-RAG. In the demo system, this is done automatically: the LLM receives the user question alongside the full graph schema and returns a Cypher query, which the service then executes against Neo4j.

從自然語言問題轉譯為結構化圖譜查詢,是 KG-RAG 的核心步驟。在範例系統中,這是自動完成的:LLM 接收使用者問題連同完整的圖譜結構描述,並回傳一個 Cypher 查詢,服務接著對 Neo4j 執行該查詢。

Consider one of the built-in sample questions:

考慮其中一個內建範例問題:

Which Tier 1 clients have active rights for localized versions with delayed delivery requests?

哪些 Tier 1 客戶對已在地化、且交付請求延遲的版本擁有有效授權?

The LLM maps this to a structured retrieval plan:

LLM 將其對應成一個結構化的檢索計畫:

  • Client.tier='Tier 1'
  • Rights.is_active=true
  • Version.is_localized=true
  • DeliveryRequest.status IN ['Delayed', 'Failed', 'In Progress']

  • Client.tier='Tier 1'

  • Rights.is_active=true
  • Version.is_localized=true
  • DeliveryRequest.status IN ['Delayed', 'Failed', 'In Progress']

and generates a Cypher query to retrieve the exact candidate subgraph:

並產生一個 Cypher 查詢以檢索出確切的候選子圖:

MATCH (t:Title)-[:HAS_VERSION]->(v:Version)  
MATCH (rg:Rights)-[:FOR_VERSION]->(v)  
MATCH (rg)-[:GRANTED_TO]->(c:Client)  
MATCH (dr:DeliveryRequest)-[:FOR_VERSION]->(v)  
WHERE c.tier = 'Tier 1'  
AND rg.is_active = true  
AND v.is_localized = true  
AND dr.status IN ['Delayed', 'Failed', 'In Progress']  
RETURN t.title_name,  
v.version_id,  
c.client_name,  
dr.status,  
dr.deadline  
LIMIT 25;

If Neo4j rejects the generated query due to a syntax error, the service automatically repairs and retries it, feeding the error message back to the LLM on the next attempt.

如果 Neo4j 因語法錯誤而拒絕所產生的查詢,服務會自動修復並重試,在下一次嘗試時將錯誤訊息回饋給 LLM。

You can submit this question through the browser UI or directly via the REST API:

你可以透過瀏覽器 UI 提交此問題,或直接透過 REST API:

curl -X POST http://localhost:8000/api/v1/ask \  
-H 'Content-Type: application/json' \  
-d '{  
"question": "Which Tier 1 clients have active rights for localized versions with delayed delivery requests?",  
"include_rows": true  
}'

The response bundles the generated Cypher, the retrieved rows, and a step-by-step agent trace:

回應會打包產生的 Cypher、檢索到的資料列,以及逐步的代理追蹤:

{  
    "question": "Which Tier 1 clients have active rights for localized versions with delayed delivery requests?",  
    "answer": "Based on the graph data, the following Tier 1 clients hold active rights for localized versions with at least one delayed delivery request ...",  
    "cypher": "MATCH (t:Title)-[:HAS_VERSION]->(v:Version) ...",  
    "rows": [  
        {  
            "title_name": "...",  
            "version_id": "...",  
            "client_name": "...",  
            "dr_status": "Delayed",  
            "deadline": "2025–09–12"  
        }  
    ],  
    "row_count": 18,  
    "agent_trace": [  
        "Received user question.",  
        "Planned Cypher on attempt 1.",  
        "Executed Cypher and retrieved 18 rows.",  
        "Synthesized natural-language answer."  
    ]  
}

This is the real retrieval gain: the graph makes the question executable as structure, and the LLM never has to infer relationships from scattered text.

這就是真正的檢索收益:圖譜讓問題能以結構的形式被執行,而 LLM 完全不必從零散的文字中推斷關係。

Passing Graph Results to the LLM / 將圖譜結果傳遞給 LLM

Once the graph returns the matching rows, the service packages them into a synthesis prompt and sends them to the LLM. The LLM receives the original question, the Cypher query that was executed, and the returned rows as a JSON block. It is instructed to answer using only the provided graph facts and to note any uncertainty when relevant.

一旦圖譜回傳相符的資料列,服務便會將它們封裝成一個綜合提示 (synthesis prompt) 並送給 LLM。LLM 會接收到原始問題、所執行的 Cypher 查詢,以及以 JSON 區塊形式回傳的資料列。它被指示僅使用所提供的圖譜事實來作答,並在相關時註明任何不確定性。

For the rights-and-delivery question, the retrieved rows might include records like:

對於這個授權與交付問題,檢索到的資料列可能包含像這樣的記錄:

Title: Example Title A | Version: VER_TITLE_000123_001 | Client: Client A | Status: Delayed | Deadline: 2025–09–12  
Title: Example Title B | Version: VER_TITLE_000812_003 | Client: Client B | Status: Failed | Deadline: 2025–08–30

The LLM does not need to discover the relationships itself. The graph has already done the relational retrieval. The model’s job is to summarize, compare, prioritize, and explain.

LLM 不需要自行去發掘關係。圖譜已經完成了關係性的檢索。模型的工作是摘要 (summarize)比較 (compare)排定優先級 (prioritize)解釋 (explain)

In the browser UI (see Figure 7. for screenshot), the answer appears in the Answer panel at the top. The Generated Cypher panel shows exactly what query was executed. The Retrieved Rows panel shows the raw records the LLM used to generate the answer. The Agent Trace panel logs each step: question received, Cypher planned, query executed, answer synthesized.

在瀏覽器 UI 中(截圖見圖 7),答案會出現在頂端的答案面板。產生的 Cypher 面板會精確顯示所執行的查詢。檢索到的資料列面板會顯示 LLM 用來產生答案的原始記錄。代理追蹤面板會記錄每個步驟:已接收問題已規劃 Cypher已執行查詢已綜合答案

Press enter or click to view image in full size

按 Enter 或點擊以全螢幕檢視圖片

Figure 7. Screenshot: KG QA Service answer question in natural language using Graph RAG

圖 7。 截圖:知識圖譜問答服務使用 Graph RAG 以自然語言回答問題

What This Demo Shows / 這個範例展示了什麼

Beyond the graph traversal mechanics, this example highlights two design points that are easy to overlook when first working with Knowledge Graphs.

除了圖譜走訪的機制之外,這個範例還凸顯了兩個在初次接觸知識圖譜時容易被忽略的設計要點。

1. Event-like nodes are often worth modeling explicitly / 1. 類事件節點往往值得明確建模

In many practical systems, it is better to model objects such as rights grants, localization jobs, and delivery requests as first-class nodes rather than burying everything inside direct edges.

在許多實務系統中,將授權在地化工作交付請求這類物件建模為一等公民節點 (first-class node),會比把所有東西都埋進直接的邊裡更好。

That gives you:

這帶給你:

  • richer provenance
  • easier filtering by operational state
  • clearer explanations to the user
  • more flexible multi-hop traversals

  • 更豐富的來源溯源 (provenance)

  • 更容易依營運狀態進行過濾
  • 對使用者更清楚的解釋
  • 更靈活的多跳走訪

2. Knowledge Graphs improve retrieval quality, not just visualization / 2. 知識圖譜改善的是檢索品質,而不僅是視覺化

It is easy to treat a graph as a nice diagram. But in KG-RAG, the graph should act as an operational retrieval layer.

人們很容易把圖譜當成一張漂亮的示意圖。但在 KG-RAG 中,圖譜應該作為一個可運作的檢索層 (operational retrieval layer)。

The question to ask is not, “Does this graph look impressive?

該問的問題不是「這張圖譜看起來令人印象深刻嗎?

The question is, “Does this graph make my retrieval logic more precise, more controllable, and easier to explain?

該問的問題是「這張圖譜是否讓我的檢索邏輯更精確、更可控、更容易解釋?

In this demo, the answer is yes.

在這個範例中,答案是肯定的

Limitations and Design Notes / 限制與設計註記

This is still a synthetic dataset, so it does not capture every challenge of a production system.

這仍然是一個合成資料集,因此它並未涵蓋正式生產系統的每一項挑戰。

Some practical limitations remain:

仍存在一些實務上的限制

  • the data is generated, not extracted from real source documents
  • some reference dictionaries, such as audio and video formats, are not yet fully normalized into linked graph entities for every relevant field
  • the generated region continent values are currently simplified and would need cleanup for a production-ready reporting layer
  • query translation from natural language to Cypher is handled by the LLM, but the schema embedded in the prompt currently requires manual maintenance as the graph evolves

  • 資料是產生出來的,而非從真實來源文件中擷取

  • 某些參考字典(例如音訊與視訊格式)尚未針對每個相關欄位完全正規化 (normalize) 成相連的圖譜實體
  • 所產生的地區 continent(洲)值目前是簡化的,若要用於可投入生產的報表層,需要加以清理
  • 從自然語言到 Cypher 的查詢轉譯由 LLM 處理,但目前嵌入在提示中的結構描述,在圖譜演進時需要人工維護

Even so, the demo is useful because it represents a realistic multi-entity workflow rather than a single-entity lookup problem.

即便如此,這個範例仍然有用,因為它代表的是一個真實的多實體工作流程,而非單一實體的查找問題。

A Practical Hybrid Pattern / 一個實用的混合模式

None of those limitations change the core design principle. Whether the dataset is synthetic or production-grade, the most useful real-world design is still hybrid.

那些限制都不會改變核心的設計原則。無論資料集是合成的還是生產級的,最實用的真實世界設計仍然是混合式 (hybrid) 的。

One good pattern is:

一個不錯的模式是:

  1. Use the graph to identify the relevant entities, workflow nodes, and paths.
  2. Use text retrieval to fetch supporting documents, descriptions, tickets, or notes tied to those entities.
  3. Use the LLM to generate the final grounded answer.

  4. 使用圖譜來辨識相關的實體、工作流程節點與路徑。

  5. 使用文字檢索來取得與這些實體相關的支援文件、描述、工單或註記。
  6. 使用 LLM 來產生最終有依據的答案。

In this architecture, the graph gives you precision and structure, while text retrieval adds the supporting narrative detail.

在這個架構中,圖譜提供精確性與結構,而文字檢索則補上支援性的敘述細節。

Conclusion / 結論

Knowledge Graphs improve RAG when the problem is not simply about finding a relevant paragraph, but about retrieving connected facts under several constraints.

當問題不單純只是找到一段相關的段落,而是要在多個約束條件下檢索出彼此相連的事實時,知識圖譜便能改善 RAG。

In this media-operations demo, the graph is not just a conceptual teaching device. It becomes a practical retrieval layer for rights, localization, and delivery workflows that naturally require multi-hop reasoning.

在這個媒體營運範例中,圖譜不只是一個概念性的教學工具。它成為了授權、在地化與交付工作流程的實用檢索層,而這些流程天生就需要多跳推理。

The main lesson is simple: Knowledge Graphs do not replace language models, and they do not replace text retrieval. They improve the structure of retrieval so that the LLM receives better candidate facts to work with.

主要的啟示很簡單:知識圖譜不會取代語言模型,也不會取代文字檢索。它們改善的是檢索的結構,好讓 LLM 收到更好的候選事實來進行處理

When your questions are relational, your retrieval layer should be relational too.

當你的問題是關係型的,你的檢索層也應該是關係型的。

https://medium.com/@chuan-zhang/knowledge-graphs-in-rag-a-realistic-demo-with-neo4j-d07149a1e418


🔤 關鍵術語

英文 繁中譯名 文章中的脈絡 / 簡短說明
Retrieval-Augmented Generation (RAG) 檢索增強生成 在執行時檢索相關知識,將 LLM 回應建立在檢索到的脈絡之上,而非僅依賴參數記憶
Knowledge Graph (KG) 知識圖譜 以節點、邊、屬性顯式表達實體與關係,補足傳統 RAG 在關聯型問題上的不足
KG-RAG 知識圖譜檢索增強生成 以連結路徑為中心的檢索,將緊湊子圖作為接地脈絡傳給 LLM
Graph RAG 圖譜檢索 Demo 主要模式:LLM 依 schema 生成 Cypher,對 Neo4j 查詢後再合成自然語言答案
Vector RAG 向量檢索 將問題嵌入後以餘弦相似度比對標題簡介,適用於內容主題探索型問題
Neo4j Neo4j(圖資料庫) 用於儲存知識圖譜、執行 Cypher 查詢的圖資料庫
Cypher query Cypher 查詢語言 Neo4j 的圖查詢語言;LLM 將自然語言問題轉譯為 Cypher
embeddings 向量嵌入 將文字 chunk 轉成向量以儲存於向量資料庫並做相似度檢索
vector database 向量資料庫 儲存 embeddings 以供標準 RAG 流程做相似度檢索
semantic similarity 語意相似度 傳統 RAG 檢索主要依語意相似度驅動,而非顯式實體關係
cosine similarity 餘弦相似度 Vector RAG 中以此度量問題與標題簡介的相符程度
graph traversal 圖譜遍歷 沿著多個連結實體走訪以擷取候選事實,是 KG-RAG 的核心檢索方式
multi-hop reasoning 多跳推理 跨多個節點類型與關係跳轉才能回答的關聯型問題
subgraph 子圖 擷取一個緊湊的連結事實結構,作為接地脈絡傳給 LLM
nodes / edges / properties 節點/邊/屬性 知識圖譜的三大組成:實體、關係、節點或關係上的屬性
graph schema 圖譜結構描述 隨問題一起傳給 LLM,用以生成正確的 Cypher 查詢
grounding / grounded context 接地/接地脈絡 將回應建立在檢索到的真實事實上,減少幻覺
Weaviate Weaviate(向量資料庫) 儲存標題簡介向量,供 Vector RAG 做相似度檢索
Ollama Ollama 本地模型執行服務,提供 llama3.2 與 nomic-embed-text 等模型
nomic-embed-text nomic-embed-text(嵌入模型) 用於將問題與標題簡介轉為向量的嵌入模型
hybrid pattern 混合式檢索模式 先用圖譜定位實體與路徑,再用文字檢索補充說明,最後由 LLM 生成答案