Building an Ontology-Based Knowledge Graph Extraction and Visualization System: A Practical Case Study
This article walks through a practical case of building a system that extracts entities and relations from text, validates them against an ontology, stores them in a graph database, and displays them in a web interface. It explains why long-horizon software tasks are hard to complete, how an ontology constrains extraction results, how the project was split into eight delivery stages with acceptance criteria, and how generate-check-fix loops and operational safeguards apply to this kind of work.
1. Background: Why Long-Horizon Tasks Are Hard
In software engineering, some tasks have long chains of steps that depend on each other. A single function or a single page cannot complete them. They need data processing, model calls, storage design, API services, and user interfaces to work together. Such tasks are often called long-horizon tasks.
Long-horizon tasks carry three main risks. First, an error in an early step propagates down the chain. For example, if extraction output has inconsistent field formats, the data may fail to be written to the database, and the page may end up showing nothing. Second, each step has its own acceptance criteria, and code that merely runs is hard to check for semantic errors. Third, the task is large, so context is easily lost, and design decisions made early may be forgotten or violated later.
A common response is to add a control framework around the model. It usually has three roles: a planning step breaks the task down, a generation step writes the code, and an evaluation step checks the results. Together they form a loop, and each round of output must pass checks before it moves to the next round. The value of this approach is that it accepts that models make mistakes and designs the process around that fact, rather than hoping a single output is fully correct.
As model capabilities improve, some of the control logic can be handled by the model itself. Within one context, a model can write code, run tests, read error messages, and revise the code. Therefore, which parts of the outer framework can be simplified and which must be kept should be decided item by item, based on the nature of the task and the capabilities of the model. This article uses one concrete project to show how that decision can be made.
2. Task Definition: Ontology-Based Knowledge Graph Extraction
The case in this article is a system that builds a knowledge graph from text, based on an ontology. Its goal is to identify entities and relations in unstructured text, validate the results against a predefined ontology specification, write them into a graph database, and let users query and browse them through a front-end interface.
This task suits a long-horizon sample because it includes at least five stages:
- Understand the ontology definition. The ontology specifies which classes exist, which properties each class has, and which relations are allowed between classes. For example, in a sample schema covering movies, directors, and actors, a director can be linked to a movie by a “DIRECTED” relation, and an actor can be linked to a movie by an “ACTED_IN” relation.
- Extract entities and relations from text. This step relies on natural language processing and must handle coreference resolution, alias normalization, and relation direction.
- Write the extraction results into a graph database. How nodes and edges are modeled directly affects later query efficiency and data consistency.
- Provide query and export interfaces for upstream applications.
- Provide a visualization interface so users can browse entities and relations graphically.
These five stages depend on each other strictly. If extraction results violate the ontology constraints, the database receives dirty data. If the API returns unstable structures, the front end cannot render correctly. If any one stage fails, the whole system cannot deliver usable results.
3. The Role of the Ontology: From Storing Data to Constraining Data
Many knowledge graph projects focus on storing data and overlook what gets stored and whether it makes sense. This is where an ontology adds value. It gives the graph a unified type system and relation constraints, so the data can be validated.
In practice, an ontology can be understood as a machine-readable schema. It includes at least three parts:
- Classes: for example, movies, people, and organizations.
- Properties: for example, a movie’s release year or a person’s name.
- Relations: for example, a directing relation between a person and a movie. The relation must specify the types of its head and tail entities.
The following is an illustrative schema definition that shows how extraction results should be validated:
ontology = {"classes": {"Movie": {"properties": {"title": str, "year": int}},"Person": {"properties": {"name": str}},},"relations": {"DIRECTED": {"domain": "Person", "range": "Movie"},"ACTED_IN": {"domain": "Person", "range": "Movie"},},}def validate_triple(subject, predicate, obj, ontology):rel = ontology["relations"].get(predicate)if rel is None:return False, f"Unknown relation: {predicate}"if subject["type"] != rel["domain"] or obj["type"] != rel["range"]:return False, "Entity types at both ends of the relation do not match the ontology constraint"return True, "Passed"
This code reflects a basic principle: the output of the extraction model must not be written to the database directly. It must pass ontology validation first. Records that fail validation should go to a review queue, rather than being silently discarded or forcibly written.
The ontology also lets the graph evolve over time. When new text introduces concepts that the ontology does not cover, the system can record them as candidate types. After human review, the ontology can be extended. In this way, the graph keeps a stable structure while improving gradually as the business changes.
4. System Breakdown: Delivery Order Across Eight Stages
A common reason complex systems fail is unclear dependencies, which leads to rework later. This case uses the following eight-stage delivery order. Each stage depends on a runnable result from the stage before it:
Backend foundation → Schema engine → Extraction API → Ontology CRUD → RDF export → Front-end scaffold → Graph visualization → Integration testing
The responsibilities and acceptance methods of each stage are described below.
4.1 Backend Foundation
This stage builds the service skeleton. It includes the project structure, configuration management, logging, database connections, and a health check endpoint. Configuration values should be injected through environment variables or a secret management service, not written into the code repository. The acceptance criteria are that the service starts, the health check endpoint returns a normal status, and database connections can be opened and closed.
4.2 Schema Engine
The schema engine loads the ontology definition, parses classes and relations, and provides validation functions. It is the source of rules for all later stages, so it should be completed first. Acceptance testing should cover typical cases such as valid triples, invalid relation names, and type mismatches, to confirm that the validation logic is stable.
4.3 Extraction API
The extraction API receives text, calls a language model or a rule-based method to identify entities and relations, outputs structured results, and passes them to the schema engine for validation. The key points are to agree on a unified output format, such as fixed JSON fields, and to handle parsing errors in model output. When parsing fails, the service should retry or log the original text, rather than raising an error and exiting.
4.4 Ontology CRUD
This stage provides endpoints to create, read, update, and delete ontology definitions. Changes to the ontology affect the validity of existing data, so updates should run a compatibility check first. For example, the check can confirm whether existing data references a type that is about to be deleted. Delete operations should require confirmation by default.
4.5 RDF Export
RDF is a general data model in knowledge representation. It describes facts as subject-predicate-object triples. The export feature lets other systems read graph data in a standard format. The implementation must ensure that entity identifiers follow a stable generation rule, so the same entity keeps the same identifier across repeated exports. Special characters must also be escaped.
4.6 Front-End Scaffold
The front-end scaffold includes project initialization, routing, state management, API wrappers, and basic components. The API wrapper layer should handle error codes and timeouts in one place, so that each page does not implement its own logic.
4.7 Graph Visualization
The visualization stage renders nodes and edges as an interactive graph. It supports filtering by type, viewing properties by clicking a node, and searching entities by keyword. When the number of nodes is large, the interface should load data in pages or expand nodes on demand to prevent slowdowns.
4.8 Integration Testing
Integration testing covers the full path from input text to page display. Test cases should include normal samples, boundary samples, and error samples.
