Chapter 6: Knowledge Graphs
6.1 From Logic to Knowledge Graphs¶
Chapters 4 and 5 represented knowledge as logical sentences. Logic is precise and supports deduction, but writing large bodies of knowledge in it is hard, and reasoning with full first-order logic is expensive (even undecidable). Knowledge graphs keep the most useful part, facts about entities and their relations, in a form that scales to billions of facts.
| Year | Milestone |
|---|---|
| 1960s | semantic networks: concepts as nodes, relations as labelled links |
| 1985 | WordNet begins: English words organised by meaning |
| 2001 | the Semantic Web vision: machine-readable data on the Web (RDF, OWL, SPARQL standards follow) |
| 2007 | DBpedia and YAGO: facts extracted from Wikipedia |
| 2012 | Google’s Knowledge Graph: search results about things, not just matching strings |
| 2012 | Wikidata: a free, collaborative knowledge graph, now with over 100 million items |
A knowledge graph is a directed graph whose nodes are entities (Riyadh, Saudi Arabia, the Arabic language) or values, and whose labelled edges are relations (capitalOf, language). Compared with first-order logic, it uses only binary relations and no general rules; in exchange, it is easy to build, merge, store, query and learn from.
6.2 Triples and RDF¶
Every edge is a triple (subject, predicate, object):
| Subject | Predicate | Object |
|---|---|---|
| Riyadh | capitalOf | Saudi Arabia |
| Saudi Arabia | locatedIn | Asia |
| Saudi Arabia | language | Arabic |
| Cairo | capitalOf | Egypt |
| Egypt | locatedIn | Africa |
The W3C standard for triples is RDF (Resource Description Framework). Entities and relations are named by IRIs (web addresses), so that graphs from different sources can be merged without name clashes; values such as numbers and dates are literals. A common syntax is Turtle:
@prefix ex: <http://example.org/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
ex:Riyadh ex:capitalOf ex:SaudiArabia ;
rdfs:label "Riyadh"@en, "الرياض"@ar .
ex:SaudiArabia ex:locatedIn ex:Asia ;
ex:language ex:Arabic .(; repeats the subject; , repeats the subject and predicate; "..."@ar is a string in Arabic.)
Property graphs (used by graph databases such as Neo4j) are a popular alternative: nodes and edges can carry key–value properties directly (“since: 1932” on an edge). RDF expresses the same with extra nodes; property graphs are often handier for applications, RDF for publishing and merging data.
Source
import networkx as nx
import matplotlib.pyplot as plt
triples = [('Riyadh', 'capitalOf', 'Saudi Arabia'), ('Saudi Arabia', 'locatedIn', 'Asia'), ('Saudi Arabia', 'language', 'Arabic'),
('Cairo', 'capitalOf', 'Egypt'), ('Egypt', 'locatedIn', 'Africa'), ('Egypt', 'language', 'Arabic'),
('Tunis', 'capitalOf', 'Tunisia'), ('Tunisia', 'locatedIn', 'Africa'), ('Tunisia', 'language', 'Arabic'),
('Paris', 'capitalOf', 'France'), ('France', 'locatedIn', 'Europe'), ('France', 'language', 'French'),
('Tunisia', 'language', 'French')]
G = nx.MultiDiGraph()
for s, p, o in triples: G.add_edge(s, o, label=p)
pos = {'Riyadh': (0, 3), 'Saudi Arabia': (1.5, 3), 'Asia': (3, 3.6), 'Cairo': (0, 1.8), 'Egypt': (1.5, 1.8), 'Africa': (3, 1.0),
'Tunis': (0, 0.6), 'Tunisia': (1.5, 0.6), 'Arabic': (3.2, 2.5), 'Paris': (0, -0.6), 'France': (1.5, -0.6), 'Europe': (3, -0.6), 'French': (3.2, 0.2)}
kind = {'Riyadh': 'C0', 'Cairo': 'C0', 'Tunis': 'C0', 'Paris': 'C0', 'Asia': 'C2', 'Africa': 'C2', 'Europe': 'C2', 'Arabic': 'C4', 'French': 'C4'}
plt.figure(figsize=(9, 5))
nx.draw_networkx_nodes(G, pos, node_color=[kind.get(n, 'C1') for n in G], node_size=1700, alpha=0.85)
nx.draw_networkx_labels(G, pos, font_size=8)
nx.draw_networkx_edges(G, pos, arrowsize=14, node_size=1700, edge_color='gray')
nx.draw_networkx_edge_labels(G, pos, edge_labels={(s, o): p for s, p, o in triples}, font_size=7, label_pos=0.68)
plt.title('A small knowledge graph: capitals (blue), countries (orange), continents (green), languages (purple)'); plt.axis('off'); plt.tight_layout(); plt.show()
6.3 Schemas and Inference¶
Facts become more useful with a schema (an ontology) that says what kinds of things exist. RDF Schema (RDFS) provides a few relations about relations:
| RDFS statement | Meaning | Inference rule |
|---|---|---|
Capital rdfs:subClassOf City | every capital is a city | if x rdf:type Capital then x rdf:type City |
subClassOf is transitive | if A ⊑ B and B ⊑ C then A ⊑ C | |
capitalOf rdfs:domain Capital | the subject of capitalOf is a capital | if x capitalOf y then x rdf:type Capital |
capitalOf rdfs:range Country | the object of capitalOf is a country | if x capitalOf y then y rdf:type Country |
isCapitalCityOf rdfs:subPropertyOf capitalOf | a more specific relation | if x isCapitalCityOf y then x capitalOf y |
Worked example¶
Schema: Capital ⊑ City, City ⊑ Place, Country ⊑ Place, capitalOf has domain Capital and range Country. One fact: Riyadh capitalOf SaudiArabia. Applying the rules until nothing new appears (forward chaining, as in Chapter 4):
domain:
Riyadh rdf:type Capitalrange:
SaudiArabia rdf:type Countrysub-class:
Riyadh rdf:type Citysub-class:
Riyadh rdf:type Place, andSaudiArabia rdf:type Place
One stated fact yielded five more. Nobody had to write “Riyadh is a place”.
OWL (the Web Ontology Language) adds more expressive statements: inverse properties (hasCapital is the inverse of capitalOf), transitive or functional properties (a country has one capital), disjoint classes (nothing is both a city and a country), cardinalities. Reasoning with OWL is based on description logics, carefully chosen fragments of first-order logic that stay decidable.
The open-world assumption¶
A database assumes that what it does not contain is false (closed world). Knowledge graphs usually assume the open world: a missing fact is unknown, not false. If the graph does not say that Tunisia’s language includes Berber, that does not mean it does not. Every real knowledge graph is incomplete: in Freebase, for example, about 70% of the people had no recorded place of birth.
6.4 Querying with SPARQL¶
SPARQL is the query language of RDF. A query is a pattern of triples with variables (?x); the answers are the bindings of the variables that make the whole pattern match the graph.
Capitals of Arabic-speaking countries in Africa:
PREFIX ex: <http://example.org/>
SELECT ?capital ?country WHERE {
?capital ex:capitalOf ?country .
?country ex:language ex:Arabic ;
ex:locatedIn ex:Africa .
}On our graph: (Cairo, Egypt) and (Tunis, Tunisia). The three triple patterns share the variable ?country: matching them is a join, like in SQL.
| Feature | Example | Meaning |
|---|---|---|
FILTER | FILTER(?pop > 10000000) | keep only answers satisfying a condition |
OPTIONAL | OPTIONAL { ?c ex:language ?l } | include the part if it exists (open world!) |
| aggregates | SELECT ?l (COUNT(?c) AS ?n) ... GROUP BY ?l | count, sum, average by group |
| property paths | ?city ex:locatedIn+ ?place | follow one or more locatedIn edges |
ORDER BY, LIMIT | ORDER BY DESC(?n) LIMIT 5 | the top 5 |
Public knowledge graphs offer SPARQL endpoints on the Web: for example, the Wikidata Query Service answers queries over its whole graph.
6.5 Knowledge Graphs in the Real World¶
| Graph | Content | Built by |
|---|---|---|
| WordNet | English nouns, verbs, adjectives grouped into synonym sets, linked by “is a kind of”, “is part of” | linguists, by hand |
| Wikidata | over 100 million items about everything: people, places, works, species, ... | volunteers and bots, collaboratively |
| DBpedia, YAGO | facts extracted from Wikipedia’s infoboxes and categories; YAGO adds a clean taxonomy from WordNet | automatic extraction |
| Gene Ontology | the functions of genes and proteins | biologists, curated |
| Enterprise graphs | Google, Amazon, LinkedIn and many companies keep graphs of products, people and documents | mixed |
Uses. Search engines (the information panel next to the results), question answering and voice assistants, product recommendation, fraud detection (rings of linked accounts), drug discovery (genes–proteins–diseases–drugs), and grounding the answers of language models (Section 6.8).
6.6 Building Knowledge Graphs¶
| Source | Method |
|---|---|
| Structured data (tables, databases) | map rows and columns to triples: each row an entity, each column a predicate |
| Semi-structured (Wikipedia infoboxes, web tables) | wrappers and extraction rules |
| Text | information extraction: |
| 1. named-entity recognition: find the mentions (“Cairo”, “the Nile”) | |
| 2. entity linking: decide which entity each mention means (Paris, France or Paris, Texas?) | |
3. relation extraction: find the relation stated between them (“Cairo is the capital of Egypt” → capitalOf) | |
| Large language models | prompted to extract triples from text, or to propose missing facts, with human or automatic checking |
The hard problems are quality: extraction errors, contradictory sources, out-of-date facts, and entity resolution (recognising that two records describe the same entity). Each fact can carry its provenance (where it came from) and a confidence.
6.7 Reasoning and Completion¶
Paths and rules¶
Many questions are multi-hop: “Which languages are spoken in the continent where Cairo’s country lies?” follows capitalOf, then locatedIn, then (backwards) locatedIn and language. Rules can also be mined from the graph itself: if, in most cases where capitalOf and locatedIn , the graph also says locatedIn , the rule
holds with a measurable confidence, and can propose the missing facts where it does not yet.
Knowledge graph embeddings¶
An embedding gives each entity and each relation a vector, learnt so that true triples score high and false ones low; then any candidate fact can be scored, including those missing from the graph: link prediction.
TransE (Bordes et al., 2013) models a relation as a translation: for a true triple , . The score is
Worked example (2 dimensions). Suppose training produced Paris , France , Berlin , Germany , Rome , Italy , and capitalOf .
Paris + capitalOf France: score 0, a perfect fit; likewise Berlin + capitalOf Germany.
To predict the country of Rome: Rome + capitalOf . Distances: Italy 0.1, Germany 2.8, France 3.2. Italy ranks first.
Source
import numpy as np
E = {'Paris': (1, 2), 'France': (2, 3), 'Berlin': (4, 1), 'Germany': (5, 2), 'Rome': (2, -1), 'Italy': (3, 0.1)}
r = np.array([1, 1])
plt.figure(figsize=(6, 4.2))
for name, (x, y) in E.items():
plt.scatter(x, y, s=80, c='C0' if name in ('Paris', 'Berlin', 'Rome') else 'C1', zorder=3)
plt.annotate(name, (x, y), textcoords='offset points', xytext=(6, 6))
for cap in ['Paris', 'Berlin', 'Rome']:
h = np.array(E[cap]); plt.annotate('', h + r, h, arrowprops=dict(arrowstyle='->', color='C2', lw=2))
plt.scatter(3, 0, marker='x', c='C3', s=90, zorder=4); plt.annotate('Rome + capitalOf', (3, 0), textcoords='offset points', xytext=(8, -14), color='C3')
plt.title('TransE: capitalOf is the same arrow (1, 1) everywhere'); plt.grid(alpha=0.3); plt.axis('equal'); plt.tight_layout(); plt.show()
Training uses negative sampling: corrupt each true triple by replacing its head or tail with a random entity, and minimise a margin loss so that true triples score at least higher.
Evaluation: for each held-out test triple , rank every entity by score, and report
Hits@k: the fraction of test triples whose true answer is in the top ;
MRR (mean reciprocal rank): the average of (1 if always first).
TransE handles one-to-one relations well but struggles with one-to-many ones (a continent containing many countries) and symmetric ones. Later models such as DistMult, ComplEx and RotatE (a relation as a rotation) and graph neural networks (which pass messages along edges) address these limits.
6.8 Knowledge Graphs and Language Models¶
Large language models (Chapter 21) store a great deal of world knowledge in their weights, but they can hallucinate (state false facts fluently), cannot easily be corrected or updated, and do not cite sources. Knowledge graphs are the opposite: explicit, checkable, editable, but incomplete and hard to query in natural language. The two are increasingly combined:
| Direction | How |
|---|---|
| KG → LLM (grounding) | retrieve the relevant facts from the graph and give them to the model with the question (retrieval-augmented generation, GraphRAG), so that its answer rests on checkable facts |
| LLM → KG (construction) | use the model to extract triples from text, link entities, or translate questions into SPARQL |
| Both | an assistant that answers in fluent language, with every factual claim traced to the graph |
6.9 Summary¶
A knowledge graph stores triples (subject, predicate, object); RDF uses IRIs and literals; Turtle is a readable syntax.
RDFS/OWL schemas let a reasoner derive new facts (types from domains and ranges, sub-class chains); knowledge graphs follow the open-world assumption.
SPARQL matches triple patterns with variables, with
FILTER,OPTIONAL, aggregates and property paths.Large graphs (Wikidata, DBpedia, WordNet) are built from curated data, extraction from text and, increasingly, language models; quality and entity resolution are the hard parts.
Embeddings such as TransE () predict missing links, evaluated by Hits@k and MRR.
Knowledge graphs ground language models; language models help build and query knowledge graphs.
Exercises¶
Write the facts of the figure in Turtle, using
;and,where possible.With the schema of Section 6.3, list everything that follows from the single fact
Cairo capitalOf Egypt.Write a SPARQL query listing every language together with the number of countries that speak it, most spoken first.
Why does
OPTIONALmatter under the open-world assumption? Give an example query where omitting it would lose answers.In the TransE example, add Madrid and Spain . Is (Madrid, capitalOf, Spain) well modelled? Which country would TransE predict for Madrid?
Why does TransE struggle with the relation
locatedInbetween countries and continents? (Hint: many different heads, one tail.)Give two kinds of question for which a knowledge graph would help a chatbot answer more reliably.
Further Reading¶
A. Hogan et al., “Knowledge Graphs”, ACM Computing Surveys, 2021 (also a free book): a broad, readable survey.
The W3C RDF 1.1 Primer and SPARQL 1.1 Query Language recommendations.
D. Vrandečić, M. Krötzsch, “Wikidata: a free collaborative knowledgebase”, Communications of the ACM, 2014.
A. Bordes et al., “Translating Embeddings for Modeling Multi-relational Data”, NeurIPS, 2013.
S. Pan et al., “Unifying Large Language Models and Knowledge Graphs: A Roadmap”, IEEE TKDE, 2024.
C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 12.