AI AI-02.05
Knowledge graphs and ontologies
Triples, RDF and property graphs, ontologies, entity linking, knowledge graphs in search, and a first look at combining graphs with LLMs.
The big idea
Type "taj mahal" into a search box. Do you mean the monument in Agra, the blues musician who took that name, or a casino? To a classic search engine those are just two words to match against pages. A knowledge graphA graph of real-world entities (people, places, products, concepts) connected by typed relationships, stored as subject-predicate-object facts. turns them into things: distinct entities, each with an identity, a type, and links to other entities. Once the system knows which thing you mean, it can show facts about it, answer follow-up questions, and connect it to related things.
Think of the difference between a library's shelves and a well-kept family tree. Shelves hold documents that mention people. The family tree holds the people themselves, with each relationship drawn as a line you can follow: Marie's daughter, that daughter's husband, his prize. Questions like "which of Marie's relatives also won a Nobel Prize?" are a short walk along the lines, while on the shelves they mean reading every book.
Knowledge graphs are the semantic networks of Knowledge representation , grown up: billions of facts, standard formats, careful identities, and query languages. They sit behind search panels, product catalogues, fraud investigations and, increasingly, the retrieval systems that feed language models.
How it works
Step 1: Triples
Everything in a knowledge graph is a tripleA single fact in the form (subject, predicate, object), such as (Paris, capital_of, France). A knowledge graph is a large set of triples.: (subject, predicate, object).
- (Paris, capital_of, France)
- (France, currency, Euro)
- (Marie Curie, award, Nobel Prize in Physics)
Subjects and objects are nodes; predicates are labelled edges. Because every fact has the same shape, facts from many sources can be merged into one graph, and new kinds of relationship can be added without redesigning a schema. The object can also be a plain value, such as a date or a number: (Paris, population, 2100000).
Step 2: Identity and entity linking
The hard part is not storing triples but knowing which thing each name refers to. Each entity gets a unique identifier, separate from its names: two cities called Paris get two identifiers, and "Paris", "Paname" and "the French capital" can all be labels of the same one. Entity linkingDeciding which entity in a knowledge graph a mention in text refers to, such as mapping 'Paris' in a sentence to the French capital rather than the city in Texas. maps a mention in a query or document to the right identifier, usually by comparing the surrounding words with what the graph knows about each candidate:
Step 3: RDF and property graphs
Two data models dominate:
- RDFResource Description Framework: a W3C standard that represents knowledge as triples, with entities and predicates identified by URIs. It is queried with SPARQL. (Resource Description Framework) is a W3C standard. Every entity and predicate is identified by a URI, so graphs published by different organisations can link to each other. It is queried with SPARQL, which matches triple patterns with variables, exactly like the unification of First-order logic . Wikidata and many public-sector datasets use RDF.
- Property graphs, used by graph databases such as Neo4j, let nodes and edges carry key-value properties directly ("this employment edge has a start date"). They are queried with languages such as Cypher or the ISO standard GQL, and are popular for application data, fraud and recommendation.
Both answer the same kind of question: follow edges, match patterns, join the results.
Step 4: Ontologies
An ontologyA formal description of the types of things in a domain and how they relate: classes, subclass hierarchies, the properties each class can have, and constraints on them. is the schema of a knowledge graph, and more: it defines the classes (City, Country, Person), their hierarchy (a City is a Place), which properties connect which classes (capital_of goes from City to Country), and constraints (a country has exactly one capital). Standard languages such as RDFS and OWL, built on description logics, let a reasoner infer new facts: if Agra is a City and every City is a Place, Agra is a Place, without anyone storing that triple. Shared vocabularies such as schema.org define common classes and properties that web pages use to describe products, events and organisations.
Try it
A knowledge graph and its query engine fit in a few dozen lines: triples in a list, pattern matching with ?variables, and joins between patterns:
# A knowledge graph as (subject, predicate, object) triples.
T = [
("Paris", "capital_of", "France"), ("Rome", "capital_of", "Italy"),
("Berlin", "capital_of", "Germany"), ("Paris", "on_river", "Seine"),
("Vienna", "capital_of", "Austria"), ("Berlin", "on_river", "Spree"),
("Budapest", "capital_of", "Hungary"), ("Rome", "on_river", "Tiber"),
("Vienna", "on_river", "Danube"), ("Budapest", "on_river", "Danube"),
("France", "currency", "Euro"), ("Austria", "currency", "Euro"),
("Hungary", "currency", "Forint"), ("Paris", "located_in", "France"),
("Paris", "label", "paris"), ("Paris_TX", "label", "paris"),
("Paris_TX", "located_in", "Texas"),
]
def match(pattern, b=None):
"""Yield bindings for "?x" variables that match a stored triple."""
for triple in T:
nb = dict(b or {})
for p, v in zip(pattern, triple):
p = nb.get(p, p)
if p.startswith("?"):
nb[p] = v
elif p != v:
break
else:
yield nb
def query(*patterns):
"""Join several patterns, like a tiny SPARQL or Cypher query."""
results = [{}]
for pat in patterns:
results = [nb for b in results for nb in match(pat, b)]
return results
# Which capitals lie on the Danube, and what currency do they use?
for r in query(("?city", "on_river", "Danube"),
("?city", "capital_of", "?country"),
("?country", "currency", "?cur")):
print(f"{r['?city']} is the capital of {r['?country']} ({r['?cur']})")
# Entity linking: the string "paris" names two things. Pick the one whose
# neighbours overlap most with the words around it in the query.
def link(word, context):
cands = [r["?e"] for r in query(("?e", "label", word))]
score = lambda e: sum(o in context for s, p, o in T if s == e)
return {e: score(e) for e in cands}, max(cands, key=score)
for text in ["paris france euro prices", "paris texas weather"]:
scores, best = link("paris", text.title().split())
print(f"{text!r:28} -> {best} (scores {scores})")Output
Vienna is the capital of Austria (Euro)
Budapest is the capital of Hungary (Forint)
'paris france euro prices' -> Paris (scores {'Paris': 2, 'Paris_TX': 0})
'paris texas weather' -> Paris_TX (scores {'Paris': 0, 'Paris_TX': 1}) The query is a multi-hop question, which capitals lie on the Danube and what currency they use, answered by joining three patterns: river, then capital, then currency. No single stored fact contains the answer. Entity linking scores each candidate "paris" by how many of its neighbours appear in the query: "france" and "euro" point to the French capital, "texas" to the city in Texas. Real systems use the same idea with far richer signals, including popularity and learned text similarity.
Going deeper
Building a knowledge graph
Large graphs are assembled from many sources: curated databases, encyclopaedias, structured markup on web pages, and information extraction that pulls triples out of text. The work is mostly cleaning: merging duplicate entities, resolving conflicting values, tracking where each fact came from and when it was last confirmed. A graph is only as trustworthy as its provenance.
Knowledge graphs and language models
Language models know a great deal, but implicitly: they can be fluent and wrong about a specific fact, and they cannot cite where it came from. Knowledge graphs are the opposite: exact, current and traceable, but rigid. Combining them is an active area:
- Grounding: look up facts in the graph and give them to the model as context, so answers about prices, dates or relationships come from a source of truth.
- Graph-based retrieval (often called GraphRAG): build a graph of entities and relations from a document collection, then retrieve connected facts and community summaries instead of isolated text chunks. This helps with questions that need many hops or a view across many documents. The retrieval pipeline it extends is covered in Why RAG? .
- Extraction: use a language model to propose new triples from text, then validate them against the ontology before they enter the graph.
Trade-offs
| Option | Wins when | Loses when |
|---|---|---|
| Knowledge graph | Exact, connected facts; multi-hop questions; disambiguation; traceability | Costly to build, clean and keep current; rigid for fuzzy knowledge |
| Relational database | Fixed schemas, transactions, heavy aggregation | Deep or variable-length relationship queries get awkward |
| RDF with ontologies | Linking data across organisations; standard semantics and inference | Verbose; steeper learning curve |
| Property graph database | Application data with rich edge properties; fast traversals | Less standard semantics; weaker built-in inference |
Common mistakes
- Using names as identifiers. Two things called Paris must be two nodes; one city with three names must be one.
- Storing facts without provenance or dates. When sources disagree, you need to know which to trust.
- Designing an ontology so detailed that no one can populate it. Start with the questions you must answer.
- Assuming the graph is complete. A missing edge means "not known", not "false", the same open-world caution as in Knowledge representation .
In the wild
In May 2012 Google launched the Knowledge Graph to move search from matching keywords to understanding "things, not strings", using "taj mahal" (monument, musician or casino) as the example. Built from sources including Freebase, Wikipedia and the CIA World Factbook, it held more than 500 million objects and 3.5 billion facts and relationships at launch. The post describes three uses that map onto this lesson: disambiguating which entity you mean, summarising key facts about it, and following its relationships to related entities.
Check yourself
-
How is a fact stored in a knowledge graph?
Show answer
B. As a triple: subject, predicate, object Every fact has the same (subject, predicate, object) shape, which makes facts from many sources easy to merge and query.
-
A query mentions 'Jaguar' next to 'top speed' and 'dealership'. What decides which entity is meant?
Show answer
B. Entity linking, using the context to pick the car maker over the animal Entity linking compares the surrounding words and other signals with what the graph knows about each candidate.
-
What does an ontology add to a set of triples?
Show answer
B. Classes, hierarchies, allowed properties and constraints that support inference The ontology is the formal schema, and a reasoner can use it to infer facts no one stored, such as Agra being a Place.
-
Why combine a knowledge graph with a language model?
Show answer
B. The graph supplies exact, current, traceable facts; the model supplies fluent language Grounding answers in a curated graph reduces confident errors on specific facts and lets the system cite its source.
Recap
- A knowledge graph stores facts as triples about entities, each with an identity separate from its names.
- Entity linking maps mentions to the right entity using context.
- RDF (with SPARQL) and property graphs (with Cypher or GQL) are the two main data models.
- Ontologies define classes, hierarchies and constraints, so reasoners can infer new facts.
- Search engines use knowledge graphs to disambiguate, summarise and connect; graphs also ground LLM answers.