Contents
Figure 1: Build a Knowledge Graph from Text with Python — the facts are already in the text, scattered across sentences that never mention each other
Text holds facts, but a search box cannot connect them. "Maria founded Nova Labs" lives in one paragraph, "Nova Labs is based in Austin" in another, and no keyword search links Maria to Texas.
A knowledge graph turns those scattered sentences into connected facts you can query. I built the whole pipeline with the standard library and NetworkX, and it works — up to a point that is worth measuring precisely.
My rules pulled 8 triples from a 10-sentence corpus at 0.875 precision. The same rules pulled 0 triples from a 600-character Wikipedia paragraph. Both numbers are in this article, because the gap between them is the real lesson.
What a Knowledge Graph Is
A knowledge graph stores facts as triples: subject, relation, object. For example, (Maria Chen, founded, Nova Labs). Entities become nodes and relations become labelled edges, so you can walk from one fact to the next.
The standard build pipeline has five stages:
- Split text into sentences or chunks.
- Extract entities — people, organisations, places.
- Extract relations between those entities.
- Resolve duplicates — is "M. Chen" the same person as "Maria Chen"?
- Load triples into a graph and query them.
Every framework in this space follows that flow, and the surveys describe it the same way: unstructured text goes through entity recognition and linking, then relation extraction, and the triples feed a store [1][2].
Step 1: Pick an Extraction Method
Three families of options, trading speed against accuracy:
- Rules and patterns — regular expressions or dependency-parse patterns. Fast, transparent, and brittle.
- NLP models — spaCy's named entity recognition for entities, plus dependency patterns for relations. Better boundaries, still no relation semantics.
- LLM extraction — prompt a model to return triples as JSON. Handles complex relationships and normalisation, but needs validation.
I start with rules, because you can see exactly what happens, then swap in the other two and show what each one actually produces on the same text.
Step 2: Extract Triples With Patterns
The corpus is deliberately tiny — ten sentences about invented people and companies, so every failure is visible:
CORPUS = """Nova Labs was founded by Maria Chen in 2015. Maria Chen is the CEO of Nova Labs.
Daniel Ortiz is the CTO of Nova Labs. Nova Labs is headquartered in Austin.
Nova Labs acquired Brightwave in 2021. Daniel Ortiz lives in San Diego California.
M. Chen studied at Rice University. Austin is located in Texas.
Priya Raman, who leads engineering, joined Nova Labs in 2019.
Analysts say the company may grow quickly."""
A regex captures capitalised names as entities, and one pattern per relation turns sentences into triples:
import re
import networkx as nx
ENT = r"[A-Z][\w\.]*(?:\s[A-Z][\w\.]*)*"
YEAR = r"(?:\s+in\s+(?P<year>\d{4}))?"
PATTERNS = [
(rf"(?P<s>{ENT}) was founded by (?P<o>{ENT}){YEAR}",
lambda m: (m["o"], "founded", m["s"])),
(rf"(?P<s>{ENT}) is the (?P<r>CEO|CTO|CFO) of (?P<o>{ENT})",
lambda m: (m["s"], m["r"].lower() + "_of", m["o"])),
(rf"(?P<s>{ENT}) is headquartered in (?P<o>{ENT})",
lambda m: (m["s"], "headquartered_in", m["o"])),
(rf"(?P<s>{ENT}) acquired (?P<o>{ENT}){YEAR}",
lambda m: (m["s"], "acquired", m["o"])),
(rf"(?P<s>{ENT}) lives in (?P<o>{ENT})",
lambda m: (m["s"], "lives_in", m["o"])),
(rf"(?P<s>{ENT}) works at (?P<o>{ENT})",
lambda m: (m["s"], "works_at", m["o"])),
(rf"(?P<s>{ENT}) was born in (?P<o>{ENT}){YEAR}",
lambda m: (m["s"], "born_in", m["o"])),
(rf"(?P<s>{ENT}) is located in (?P<o>{ENT})",
lambda m: (m["s"], "located_in", m["o"])),
(rf"(?P<s>{ENT}) studied at (?P<o>{ENT})",
lambda m: (m["s"], "studied_at", m["o"])),
]
def extract(text):
triples, skipped = [], []
for sent in sentences(text):
for rx, build in PATTERNS:
m = re.search(rx, sent.rstrip("."))
if m:
s, p, o = build(m.groupdict())
triples.append((s, p, o, m.groupdict().get("year"), sent))
break
else:
skipped.append(sent)
return triples, skipped
Two design choices carry the pipeline.
Every triple keeps its source sentence, so you can trace any fact back to evidence. And every sentence that matches no pattern goes into a skipped list instead of disappearing, which tells you what your rules miss — that list is the most useful output in the whole article.
The Bugs I Hit
The first run produced a wrong triple, and it came from one line of the splitter.
The naive version treats every period as a sentence boundary:
re.split(r"(?<=[.!?])\s+", text)
Run it on the corpus and "M. Chen studied at Rice University." becomes two sentences:
'Daniel Ortiz lives in San Diego California.'
'M.'
'Chen studied at Rice University.'
Which produces this triple:
('Chen', 'studied_at', 'Rice University')
The subject is now "Chen" — a node that exists nowhere else in the graph, so Maria's education is attached to a stranger.
The fix is a negative lookbehind that refuses to split after a single capital letter and a period:
re.split(r"(?<=[.!?])(?<![A-Z]\.)\s+", text)
Ten sentences in, ten sentences out, and "M. Chen" survives intact.
Then a second bug appeared, in entity resolution. With "M. Chen" no longer chopped, the candidate list for it contained two entries:
candidates for 'M. Chen': ['M. Chen', 'Maria Chen']
The resolver requires exactly one candidate, so it refused to merge the mention with itself. The fix is to exclude initial-form names from the candidate list, since a mention cannot be its own canonical form:
cands = [k for k in known
if not re.fullmatch(r"[A-Z]\.\s+[A-Z]\w+", k)
and k.split()[-1] == last and k.startswith(init)]
Neither bug needed advanced math. Both came from text-handling details, which is what extraction work actually is.
Step 3: Resolve Entities
Entity resolution decides which mentions refer to the same thing. My rule is deliberately tiny: map "M. Chen" to "Maria Chen" when exactly one known person matches that initial and surname.
def resolve(name, known):
m = re.fullmatch(r"([A-Z])\.\s+([A-Z]\w+)", name)
if m:
init, last = m.groups()
cands = [k for k in known
if not re.fullmatch(r"[A-Z]\.\s+[A-Z]\w+", k)
and k.split()[-1] == last and k.startswith(init)]
if len(cands) == 1:
return cands[0]
return name
The "exactly one candidate" condition matters more than the matching. If two people share an initial and surname, guessing merges two distinct people, and that error is much worse than leaving a duplicate — a wrong merge is silent and spreads through every query downstream, while a missed merge is visible as two nodes.
Production systems add blocking, fuzzy string matching, embeddings, and attributes such as organisation or location, usually with a human reviewing the borderline cases [4]. The asymmetry stays the same at every scale: prefer a missed merge to a wrong one.
Step 4: Build the Graph
NetworkX loads the triples into a directed multigraph, which allows several relation types between the same pair of nodes:
G = nx.MultiDiGraph()
for s, p, o, year, src in triples:
G.add_edge(s, o, key=p, relation=p, year=year, source=src)
The key=p argument is what makes it a multigraph. Without it, Maria's founded and ceo_of edges to Nova Labs would overwrite each other, and you would silently lose a fact.
My run produced 8 triples, 8 nodes, and 8 edges:
nodes: ['Austin', 'Brightwave', 'Daniel Ortiz', 'Maria Chen', 'Nova Labs',
'Rice University', 'San Diego California', 'Texas']
(Maria Chen) -[founded]-> (Nova Labs)
(Maria Chen) -[ceo_of]-> (Nova Labs)
(Maria Chen) -[studied_at]-> (Rice University)
(Nova Labs) -[headquartered_in]-> (Austin)
(Nova Labs) -[acquired]-> (Brightwave)
(Daniel Ortiz) -[cto_of]-> (Nova Labs)
(Daniel Ortiz) -[lives_in]-> (San Diego California)
(Austin) -[located_in]-> (Texas)
"M. Chen" now appears as Maria Chen, so her education and her founding role attach to one node. And "San Diego California" is a single node, which is the error the next section costs you.
Step 5: Query It
This is the payoff. No single sentence says how Daniel Ortiz relates to Texas, but the graph answers:
nx.shortest_path(G.to_undirected(), "Daniel Ortiz", "Texas")
# ['Daniel Ortiz', 'Nova Labs', 'Austin', 'Texas']
That path chains three facts from three different sentences: Daniel is CTO of Nova Labs, Nova Labs is headquartered in Austin, and Austin is in Texas.
You can also ask for everything pointing at Nova Labs:
in-edges to Nova Labs:
('Daniel Ortiz', 'cto_of')
('Maria Chen', 'ceo_of')
('Maria Chen', 'founded')
And a degree-centrality check ranks Nova Labs first at 0.714 — with 8 nodes, the maximum possible is 1.0, and Nova Labs has 5 of the 7 available connections.
The Query That Does Not Run
The obvious next query is Priya Raman to Rice University. It fails:
nx.shortest_path(G.to_undirected(), "Priya Raman", "Rice University")
# NetworkXError: Source Priya Raman is not in G
Priya Raman is not in the graph at all. Her only sentence — "Priya Raman, who leads engineering, joined Nova Labs in 2019" — contains a relative clause, no pattern matches it, and it went straight into the skipped list. A node with no edges does not exist, so the query has nothing to start from.
This is the failure mode that matters in practice. A skipped sentence is not a neutral omission: it silently deletes an entity and every path through it. The graph still looks fine. Only the query tells you something is missing.
Add one sentence — "Priya Raman works at Nova Labs." — and the path appears:
nx.shortest_path(G.to_undirected(), "Priya Raman", "Rice University")
# ['Priya Raman', 'Nova Labs', 'Maria Chen', 'Rice University']
Three edges, three different sentences, one answer no sentence contains.
Evaluate Against Gold Triples
Never trust an extractor without measuring it. I wrote a 9-fact gold set from the corpus itself — every fact the text states that maps to one of my relations:
predicted 8, gold 9, TP 7, FP 1, FN 2
precision 0.875 recall 0.778 F1 0.824
false positive: (Daniel Ortiz, lives_in, San Diego California)
missed: (Daniel Ortiz, lives_in, San Diego)
(Priya Raman, works_at, Nova Labs)
Two errors, two different causes, and one of them is the more interesting.
The entity-boundary error. My capitalised-words regex glued "San Diego California" into one entity, so the fact is present but attached to a node that does not exist. The fix is not a better regex — it is a model that knows a city from a state, which the next section shows.
The pattern-coverage error. The relative clause in Priya's sentence is invisible to a linear pattern. Regexes match surface order; English puts relations inside subordinate clauses.
Add the missing sentence and the numbers move to 0.889 precision, 0.889 recall, 0.889 F1 — one sentence, 0.065 F1. That is how sensitive these measurements are on a ten-sentence corpus, and why you should not read anything into the third decimal.
One honest caveat: I wrote this corpus to fit these patterns. 0.875 precision on text I designed is not evidence that the rules work. It is evidence that they work on their own test case, which is exactly why the next section exists.
The Rules Do Not Survive Real Text
I ran the same extractor on the Wikipedia summary of a well-known AI company — 600 characters, six facts, ordinary encyclopedic prose:
triples 0 | nodes 0 | skipped 5
Zero triples. Five of five sentences skipped. The text contains a founding, a headquarters, a product, a valuation, and two named executives, and the rules found none of it, because every sentence used a construction the patterns did not anticipate.
A second summary, about a data company, did slightly better:
triples 1 | nodes 2 | skipped 2
Palantir -[ headquartered_in ]-> Miami
One triple out of the facts stated — and the founding sentence, which lists five founders in a comma series, was skipped entirely.
Three things the real text exposes:
- Passive voice with an agent list — "was founded in 2003 by Peter Thiel, Stephen Cohen, …" matches no single-object pattern.
- Appositives and relative clauses — "…, who are president and CEO, respectively" breaks the subject.
- Comma-separated place names — "Miami, Florida" loses Florida, because my entity regex stops at the comma.
This is the number to remember from the whole article: 8 triples on my corpus, 0 on real text. Rules are how you learn the pipeline. They are not how you build the graph.
Swap In Better Extractors
When rules stop scaling, upgrade the extraction step and keep everything else.
spaCy for Entity Boundaries
I ran this, with spaCy 3.8.18 and en_core_web_sm:
import spacy
nlp = spacy.load("en_core_web_sm") # python -m spacy download en_core_web_sm
doc = nlp("M. Chen studied at Rice University in San Diego California.")
print([(e.text, e.label_) for e in doc.ents])
# [('M. Chen', 'PERSON'), ('Rice University', 'ORG'),
# ('San Diego', 'GPE'), ('California', 'GPE')]
Both text bugs are gone in one line. "M. Chen" stays a single PERSON — no splitter to protect — and "San Diego California" splits into two GPEs, which is the boundary error my regex could not see.
But do not expect spaCy to type your entities correctly. On my invented corpus it labelled "Nova Labs" as PERSON, "Brightwave" as PERSON, and "CTO" as ORG. A small statistical model has never seen your domain's names, so it gets the boundaries right and the types wrong. That is still progress: boundaries are the errors that destroy facts, and types are the errors that annoy you.
Dependency Parses for Relations
Pair the parser with subject-verb-object patterns. My first attempt used token.text, and it truncated every multi-word name:
('Labs', 'found', 'Chen')
('Labs', 'acquire', 'Brightwave')
"Nova Labs" became "Labs". My second attempt expanded each token to its left_edge–right_edge span, which over-corrected:
('Priya Raman, who leads engineering,', 'join', 'Nova Labs')
The span swallowed the relative clause. The fix is to use noun chunks, which stop at the clause boundary:
def chunk_of(tok):
for ch in tok.doc.noun_chunks:
if ch.start <= tok.i <= ch.end:
return ch.text
return tok.text
With that, the demo corpus yields four clean triples:
('Nova Labs', 'found', 'Maria Chen')
('Nova Labs', 'acquire', 'Brightwave')
('Priya Raman', 'join', 'Nova Labs') <- the sentence the regexes skipped
('who', 'lead', 'engineering')
Note the third line. The dependency parse recovered exactly the fact my regexes missed, which is the strongest argument for using one: it reads structure, not word order.
On real text it is still thin. The 600-character summary produced one triple, ('Anthropic', 'found', 'former members') — right subject, object truncated before "of OpenAI". The second summary produced a wrong one, ('an American publicly traded company', 'develop', 'data integration and analytics software'), because the subject was a relative clause.
Generic dependency patterns give you cleaner spans and better coverage, not correct facts. You still need evaluation, which is why the gold set comes first.
LLM Extraction, With Validation
Prompt a model with the text and a required JSON schema, then validate every field. The validation is not optional, because models return malformed JSON, invent facts, and drift on relation names.
I did not run this block — there is no model client in my environment — but the validation logic is ordinary Python, and it is the part that decides whether the triples are usable.
import json
RELATIONS = {"founded", "ceo_of", "cto_of", "cfo_of", "headquartered_in",
"acquired", "lives_in", "works_at", "born_in", "located_in",
"studied_at"}
PROMPT = """Extract factual relationships as a JSON array of objects with keys
"subject", "relation", "object". Use only facts stated in the text.
The relation must be one of: {rels}
Text: {text}"""
def llm_triples(text, call_llm):
raw = call_llm(PROMPT.format(rels=", ".join(sorted(RELATIONS)), text=text))
triples = json.loads(raw)
return [t for t in triples
if {"subject", "relation", "object"} <= t.keys()
and t["relation"] in RELATIONS]
Fixing the relation vocabulary in the prompt and rejecting anything outside it is what stops "founded", "established", and "created" from becoming three different edges to the same concept. For multi-document corpora, extract per document, then merge into one graph through the entity-resolution step — which is also where graph-based retrieval systems attach chunks back to nodes [3].
Where to Store the Graph
Choose storage by scale and use case:
- NetworkX — in-memory, ideal for prototyping and analysis, limited by RAM. My 9-node graph is nowhere near the limit.
- Neo4j — a property-graph database queried with Cypher, suited to persistent, shared, large graphs.
- RDF triple stores — standards-based, with SPARQL as the query language, and better suited when you must merge graphs from several sources.
- A vector store alongside — retrieval systems link graph nodes to source passages, so a query can return both the fact and the text it came from [3].
The storage decision is the least interesting one. Moving from NetworkX to Neo4j is a weekend. Fixing an extraction pipeline that produces wrong triples is a quarter.
Common Pitfalls
- Skipping evaluation. Without a gold set you cannot tell progress from regression — and my 0.875 became 0.889 from one added sentence.
- Trusting naive sentence splitting. Initials and abbreviations break it, and the damage is a node that silently does not exist.
- Merging entities too eagerly. A wrong merge corrupts the graph quietly and propagates into every query.
- Letting relation names drift. "Founded", "established", and "created" fragment your graph unless you fix a vocabulary.
- Dropping provenance. Keep the source sentence for every triple, or you cannot audit a fact later.
- Treating LLM output as truth. Validate the schema, validate the relation vocabulary, and check the fact against the text.
- Ignoring time. Facts expire. Store dates and update the graph when sources change.
- Building a giant graph before defining questions. Start from the queries you want to answer; that decides which relations deserve patterns.
- Assuming rules scale. Mine produced 8 triples on my corpus and 0 on a Wikipedia paragraph.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Knowledge Graphs: Fundamentals, Techniques, and Applications | covers schema design, extraction, entity resolution, and the storage choices above, with the theory the tutorials skip. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after you have run the demo. The book explains why entity resolution is a blocking-and-matching problem rather than a string comparison, which is the part that decides whether your graph is usable at scale.
Wrapping Up
A knowledge graph pipeline runs sentence splitting, entity extraction, relation extraction, entity resolution, and graph loading. Start with rules so you understand each step, measure against hand-labelled facts, then upgrade to spaCy or an LLM where the rules fail.
The numbers from my run: 8 triples from 10 sentences at 0.875 precision and 0.778 recall, 0 triples from a 600-character Wikipedia paragraph, and a Priya Raman query that raised NodeNotFound until I added the sentence the regexes could not read.
The graph's real value shows up in multi-hop queries that no single sentence answers — Daniel to Texas in three edges. But every one of those edges had to survive extraction first.
Copy the pattern code, add three sentences of your own, and read the skipped list. That list tells you where to improve next, and on real text it is longer than the list of triples.
Frequently Asked Questions
What is a knowledge graph in simple terms?
A graph of facts stored as triples: subject, relation, object. Entities become nodes and relations become labelled edges, so (Maria Chen, founded, Nova Labs) is one edge. Because facts share entities, you can walk from one to the next and answer questions no single sentence answers.
How do I extract triples from text with Python?
Split the text into sentences, then match relation patterns with regular expressions or dependency parses. Each match becomes a subject-relation-object triple, and you keep the source sentence as provenance. My demo extracted 8 triples from a 10-sentence corpus at 0.875 precision, with one entity-boundary error.
Why did my regex extractor stop working on real text?
Because real sentences do not match your patterns. My rules pulled 8 triples from a corpus I wrote for them, then 0 triples from a 600-character Wikipedia paragraph, because every sentence used a construction the patterns did not cover. Rules are a teaching device, not a production extractor.
How do I handle the same entity written differently?
Entity resolution maps mentions to canonical names. My rule resolves an initial form to a full name only when exactly one known person matches, which is the safe direction: a wrong merge corrupts the graph silently, while a missed merge just leaves a duplicate you can fix later.
Should I use NetworkX or Neo4j for a knowledge graph?
NetworkX for prototyping and analysis, because it is in-memory and needs no server. Neo4j when the graph must persist, be shared, and be queried with Cypher. My demo graph has 9 nodes and 9 edges, which is nowhere near the point where a database earns its overhead.
Sources
[1]Hogan et al., Knowledge Graphs — the reference survey on graph models, schemas, identity, and knowledge-graph construction: arxiv.org[2]Ji et al., A Survey on Knowledge Graphs: Representation, Acquisition and Applications — knowledge acquisition, relation extraction, and the taxonomy of construction methods: arxiv.org[3]Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization — linking extracted entities and relations back to source text for retrieval: arxiv.org[4]Christophides et al., End-to-End Entity Resolution for Big Data: A Survey — blocking, matching, and the clustering step that decides which mentions become one entity: arxiv.org
