Knowledge Graphs and Ontologies

A graph states how things are connected, so an agent can follow facts instead of guessing relationships from similar words.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Things and relationships

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?

Checkoutapplication
Paymentsservice it depends on
Ledgerdatabase below that
Finance teamowner of the ledger
Arrows show relationships with a name and direction.

Taxonomy, ontology and knowledge graph

AspectTaxonomyOntologyKnowledge graph
What it isA hierarchy of categoriesA formal model of kinds, relationships and rulesActual entities and facts, ideally following a model
Typical linkBroader and narrowerSubclass, domain, range, constraintsSpecific relationships between instances
ExampleDatabase is a kind of serviceOnly a team can own a componentThe finance team owns the ledger database
Agent useFiltering and synonym handlingValidating and interpreting factsAnswering 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

AspectRDFProperty graph
UnitTriple of subject, predicate and objectNodes and relationships with key-value properties
IdentityGlobal identifiers (IRIs)Identifiers local to the database, plus your own keys
Query languagesSPARQLGQL, Cypher and others
Schema and reasoningRDF Schema, OWL, SHACLDatabase constraints and application rules
Strong whenData is shared across organizations and standards matterApplication 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.

Intermediate Designing and querying

Designing an ontology for agents

  1. Write competency questions. List the questions the graph must answer, such as "Which customers are affected by this outage?"
  2. Name the kinds. Only those the questions need.
  3. Name the relationships. Give each a direction, a definition and allowed end types.
  4. Choose identifiers. Reuse stable keys from systems of record.
  5. Add time and source. Most business facts start, end and come from somewhere.
  6. Test with real data. Load a sample and answer the questions before extending the model.
  7. Publish definitions where both people and agents can read them.
Specific relationships beat vague ones

"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.

Expert Reasoning, agents and storage

Kinds of reasoning

KindExampleCaution
HierarchyA database is a service, so service rules applyWrong hierarchy spreads wrong conclusions widely
TransitivePart of a part is a partNot every relationship is transitive
RulesIf a supplier is suspended, flag its open ordersRules need owners and tests
Path searchHow is this account linked to that one?Through busy nodes, almost everything is linked
Graph algorithmsWhich service is most depended upon?A score suggests where to look, not what is true
Model reasoning over pathsA language model explains retrieved factsIt 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

InterfaceFlexibilityRisk
Named tools such as "impact_of" with parametersLowLow, easy to test and authorize
Bounded neighbor explorationMediumMany calls; needs budgets
Model-written graph queriesHighWrong or expensive queries; needs read-only access and limits
Retrieval with graph expansionMediumIrrelevant 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

OptionConsider when
Relational tables with recursive queriesShallow traversals and existing database skills
Graph extension to your databaseYou want graph queries without another system
Dedicated property graph databaseDeep, frequent traversals and graph algorithms
RDF triple storeStandards-based exchange and formal vocabularies
In-memory librarySmall 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.

Relationships can be sensitive

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.

Illustrative example: who must be told?

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.

QuestionIf yesIf no
Do real questions chain three or more relationships?A graph model is likely to helpJoins or filters are probably enough
Do the number and depth of links vary widely?Traversal languages simplify queriesA fixed relational schema fits well
Do you already hold the relationships in reliable systems?Load them and start smallBudget for extraction and review
Is there an owner for definitions and data?The graph can stay accurateResolve ownership first
Must users see why an answer follows?Paths give a readable explanationSimple 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

Next steps