Knowledge Graphs and Ontologies
A graph states how things are connected, so an agent can follow facts instead of guessing relationships from similar words.
A knowledge graph stores entities and the typed relationships between them, each with identity and ideally a source. An ontology defines which kinds of things and relationships exist and what they mean. Graphs help agents answer connected questions, explain the path behind a result and respect business rules. They are worth their upkeep when relationships are central to the questions.
What you will learn: core concepts, taxonomy versus ontology versus graph, the two main data models, designing an ontology, queries and inference, and choosing storage.
Prerequisites: basic data modeling helps. Data Architecture for Agentic AI gives the wider picture.
The basic idea
A graph has nodes for things, such as a team, a service or a contract, and edges for relationships, such as "owns" or "depends on". A single fact can be read as a short sentence: checkout depends on payments. Chaining facts answers questions that no single record states: what does checkout depend on indirectly, and who owns each of those parts?
Taxonomy, ontology and knowledge graph
| Aspect | Taxonomy | Ontology | Knowledge graph |
|---|---|---|---|
| What it is | A hierarchy of categories | A formal model of kinds, relationships and rules | Actual entities and facts, ideally following a model |
| Typical link | Broader and narrower | Subclass, domain, range, constraints | Specific relationships between instances |
| Example | Database is a kind of service | Only a team can own a component | The finance team owns the ledger database |
| Agent use | Filtering and synonym handling | Validating and interpreting facts | Answering and explaining questions |
A thesaurus or controlled vocabulary sits near the taxonomy end and records preferred terms and synonyms. The W3C SKOS standard describes such vocabularies. Start there if your problem is simply that people use different words.
Two data models
| Aspect | RDF | Property graph |
|---|---|---|
| Unit | Triple of subject, predicate and object | Nodes and relationships with key-value properties |
| Identity | Global identifiers (IRIs) | Identifiers local to the database, plus your own keys |
| Query languages | SPARQL | GQL, Cypher and others |
| Schema and reasoning | RDF Schema, OWL, SHACL | Database constraints and application rules |
| Strong when | Data is shared across organizations and standards matter | Application teams need fast traversals with rich attributes |
Standards continue to move. W3C published RDF 1.2 Concepts and Semantics as Candidate Recommendations in April 2026, adding, among other things, ways to make statements about statements, which helps record sources and confidence. Other parts of the family were still drafts at that time. For property graphs, ISO published the GQL query language as ISO/IEC 39075 in April 2024. Product support varies, so check what your chosen database implements.
Designing an ontology for agents
- Write competency questions. List the questions the graph must answer, such as "Which customers are affected by this outage?"
- Name the kinds. Only those the questions need.
- Name the relationships. Give each a direction, a definition and allowed end types.
- Choose identifiers. Reuse stable keys from systems of record.
- Add time and source. Most business facts start, end and come from somewhere.
- Test with real data. Load a sample and answer the questions before extending the model.
- Publish definitions where both people and agents can read them.
"Related to" connects everything and explains nothing. Prefer "supplies", "approves" or "replaces". If you cannot define a relationship in one sentence, an extraction model and your users will not agree on it either.
Validation and simple inference
An ontology earns its keep when software uses it. The example checks each new fact against allowed types and infers that a database is also a component through the class hierarchy.
"""A tiny ontology: classes, allowed relationships and simple inference."""
subclass = {"Database": "Service", "Service": "Component",
"Team": "Party", "Component": "Thing", "Party": "Thing"}
relations = {"owns": ("Team", "Component"),
"depends_on": ("Component", "Component")}
types = {"payments": "Service", "ledger": "Database",
"finance": "Team", "march_report": "Thing"}
facts = []
def is_a(kind, wanted):
while kind:
if kind == wanted:
return True
kind = subclass.get(kind)
return False
def add(subject, relation, obj):
if relation not in relations:
return f"rejected: unknown relation {relation}"
domain, range_ = relations[relation]
for node, needed in ((subject, domain), (obj, range_)):
if node not in types:
return f"rejected: unknown entity {node}"
if not is_a(types[node], needed):
return f"rejected: {node} is not a {needed}"
facts.append((subject, relation, obj))
return "accepted"
for triple in [("finance", "owns", "ledger"),
("payments", "depends_on", "ledger"),
("ledger", "owns", "finance"),
("payments", "depends_on", "march_report"),
("payments", "likes", "ledger")]:
print(triple, "->", add(*triple))
components = sorted(n for n, k in types.items() if is_a(k, "Component"))
print("all components (inferred):", components)
Output:
('finance', 'owns', 'ledger') -> accepted
('payments', 'depends_on', 'ledger') -> accepted
('ledger', 'owns', 'finance') -> rejected: ledger is not a Team
('payments', 'depends_on', 'march_report') -> rejected: march_report is not a Component
('payments', 'likes', 'ledger') -> rejected: unknown relation likes
all components (inferred): ['ledger', 'payments']
The reversed ownership fact, the dependency on a report and the invented relationship are all rejected before they can mislead anyone. Both the payments service and the ledger database appear in the component list although neither was declared a component directly.
This code treats domain and range as validation rules. In RDF Schema and OWL, they are used for inference instead: stating that only teams own things would lead a reasoner to conclude that an owner is a team, not to reject the data. OWL also assumes that missing information is unknown, not false. To validate RDF data against required shapes, use SHACL. Mixing up these two behaviors is a very common source of surprise.
Querying and traversal
Graph query languages describe patterns to match. The same traversal can also be expressed in SQL with a recursive query, which is often enough for moderate depths.
"""Multi-hop impact analysis with the path that justifies each result."""
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE edge(src TEXT, dst TEXT)") # src depends on dst
db.executemany("INSERT INTO edge VALUES (?,?)", [
("checkout", "payments"), ("payments", "ledger"),
("reports", "ledger"), ("ledger", "storage"),
("search", "catalog"), ("storage", "ledger"), # a cycle
])
QUERY = """
WITH RECURSIVE hit(name, hops, path) AS (
SELECT ?1, 0, '/' || ?1 || '/'
UNION ALL
SELECT e.src, h.hops + 1, h.path || e.src || '/'
FROM edge e JOIN hit h ON e.dst = h.name
WHERE h.hops < ?2 AND instr(h.path, '/' || e.src || '/') = 0
)
SELECT name, min(hops), path FROM hit WHERE hops > 0
GROUP BY name ORDER BY 2, 1
"""
for limit in (1, 3):
print(f"If storage fails, affected within {limit} hop(s):")
for name, hops, path in db.execute(QUERY, ("storage", limit)):
chain = " <- ".join(path.strip("/").split("/"))
print(f" {name:<9} {hops} {chain}")
Output:
If storage fails, affected within 1 hop(s):
ledger 1 storage <- ledger
If storage fails, affected within 3 hop(s):
ledger 1 storage <- ledger
payments 2 storage <- ledger <- payments
reports 2 storage <- ledger <- reports
checkout 3 storage <- ledger <- payments <- checkout
Two details make this safe for an agent. The depth limit bounds the work and the size of the answer. The path check stops the cycle between storage and ledger from running forever. Returning the path matters as much as the names: it lets the agent explain why checkout is affected and lets a person spot a wrong edge.
In a property graph query language the pattern is shorter. A Cypher-style version looks like this:
MATCH p = (c:Component)-[:DEPENDS_ON*1..3]->(s:Component {name: $name})
RETURN c.name, length(p), [n IN nodes(p) | n.name]
LIMIT 100
Note the parameter, the hop limit and the row limit. The exact syntax differs between products and GQL.
Kinds of reasoning
| Kind | Example | Caution |
|---|---|---|
| Hierarchy | A database is a service, so service rules apply | Wrong hierarchy spreads wrong conclusions widely |
| Transitive | Part of a part is a part | Not every relationship is transitive |
| Rules | If a supplier is suspended, flag its open orders | Rules need owners and tests |
| Path search | How is this account linked to that one? | Through busy nodes, almost everything is linked |
| Graph algorithms | Which service is most depended upon? | A score suggests where to look, not what is true |
| Model reasoning over paths | A language model explains retrieved facts | It may state links that were never retrieved |
Mark inferred facts as inferred and keep the rule that produced them. When a supporting fact is removed, recompute or remove its conclusions.
How agents should use a graph
| Interface | Flexibility | Risk |
|---|---|---|
| Named tools such as "impact_of" with parameters | Low | Low, easy to test and authorize |
| Bounded neighbor exploration | Medium | Many calls; needs budgets |
| Model-written graph queries | High | Wrong or expensive queries; needs read-only access and limits |
| Retrieval with graph expansion | Medium | Irrelevant neighbors flood context, see GraphRAG and Hybrid Graph Retrieval |
Start with named tools for the most common questions. Entity linking, the step that matches "the payments system" to a node, causes many failures, so return candidates when a name is ambiguous and let the agent ask. Absence needs care: no path in the graph may mean no relationship, or only that nobody recorded it. The answer should say which sources the graph covers.
Graphs for agent memory
A graph can store what an agent learns about people, projects and their relationships, with validity dates so that new facts supersede old ones without erasing history. It adds extraction errors and privacy duties, and a simple table is often adequate. Compare options in Memory Storage: Vector, SQL or Knowledge Graph.
Choosing storage
| Option | Consider when |
|---|---|
| Relational tables with recursive queries | Shallow traversals and existing database skills |
| Graph extension to your database | You want graph queries without another system |
| Dedicated property graph database | Deep, frequent traversals and graph algorithms |
| RDF triple store | Standards-based exchange and formal vocabularies |
| In-memory library | Small graphs, analysis and prototypes |
Evaluate permissions, backup, query portability, license and the health of the project. The last point is practical: the embedded graph database Kuzu was archived by its maintainers in October 2025, leaving users to stay on the final release, move to a fork or migrate. Keeping your model and load process independent of one product makes such moves much cheaper.
Knowing that two people are linked, or that a project exists, may itself be confidential. Apply permissions to edges and paths, not only to node details, and test that traversal cannot cross a restricted link.
An operations assistant answers outage questions from a graph of services, dependencies and owners loaded from the configuration database and team directory. A tool returns affected services with paths and owning teams, limited to three hops. When a service has no recorded owner, the assistant lists it separately instead of leaving it out.
Do you need a graph at all?
A graph is another system to load, secure and keep correct. Ask these questions before building one.
| Question | If yes | If no |
|---|---|---|
| Do real questions chain three or more relationships? | A graph model is likely to help | Joins or filters are probably enough |
| Do the number and depth of links vary widely? | Traversal languages simplify queries | A fixed relational schema fits well |
| Do you already hold the relationships in reliable systems? | Load them and start small | Budget for extraction and review |
| Is there an owner for definitions and data? | The graph can stay accurate | Resolve ownership first |
| Must users see why an answer follows? | Paths give a readable explanation | Simple retrieval with citations may do |
Run a short experiment: write ten competency questions, load a few hundred real facts into whatever store you already have and answer them. If the queries are simple and fast, you may be finished. If they become long, fragile and slow, you now have evidence for a graph database and a test set to compare candidates. Either way, the definitions you wrote remain useful for tool descriptions, metadata and the Semantic Layers and Business Metrics for AI that sit beside the graph.
Changing a model safely
Ontologies change as questions change. Adding a new kind or an optional property is usually harmless. Renaming a relationship, narrowing what it may connect or splitting one class into two breaks queries, mappings and agent tools that relied on the old form. Version the model, describe each change, keep deprecated terms working for a transition period and run the competency questions against every new version. An agent's tool descriptions should be generated from, or checked against, the current model so that the two cannot drift apart.
Common mistakes
- Modeling the whole business before answering one question.
- Vague or duplicate relationship types.
- Using names as identifiers.
- No dates or sources on facts.
- Expecting an OWL reasoner to reject invalid data.
- Unlimited traversal from highly connected nodes.
- Reading a missing edge as proof of no relationship.
Checklist
- Competency questions define the scope.
- Each kind and relationship has a written definition.
- Identifiers come from systems of record where possible.
- Facts carry source and validity dates.
- Validation runs on every load.
- Agent queries are bounded by depth, rows and time.
- Permissions apply to paths.
- Coverage limits are stated in answers.
Frequently asked questions
Is a knowledge graph the same as a graph database?
No. The graph is the modeled information. A graph database is one place to store it, alongside relational tables, triple stores and files.
Do I need OWL?
Only if you need formal inference or must exchange models in that form. Many useful graphs rely on a clear schema and validation rules.
Can a model build the ontology for me?
It can propose terms from sample documents. Domain owners should decide definitions, because the ontology records agreements that a model cannot make.
How large should the first graph be?
Small enough to check by hand: a few kinds, a few relationships and one set of questions with known answers.
References and further reading
- Hogan et al.: Knowledge Graphs, a broad survey
- W3C: RDF 1.2 Concepts and Abstract Data Model
- W3C: OWL 2 overview
- W3C: Shapes Constraint Language (SHACL)
- W3C: SKOS reference
- ISO/IEC 39075: GQL
Next steps
Building and Governing Knowledge Graphs
Fill the graph and keep it right.
Semantic Layers and Business Metrics for AI
Define measures as well as things.
GraphRAG and Hybrid Graph Retrieval
Use graphs in retrieval.