Building and Governing Knowledge Graphs

Loading facts is easy. Keeping one node per real thing, with evidence and dates, is the real work.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Build a knowledge graph from the most reliable sources first, extract further facts from text only where needed, and merge records that describe the same thing with care. Keep the source and validity period of every fact, measure precision and recall on reviewed samples, and manage the model and data with owners, versions and a way to undo mistakes.

What you will learn: a construction process, extraction methods, entity resolution, quality measurement, conflicts and time, and governance and versioning.
Prerequisites: Knowledge Graphs and Ontologies.

Beginner The construction process

From questions to a working graph

Scopequestions and model
Loadstructured sources
Extractfacts from text
Resolveone node per thing
Validaterules and review
Publishversioned release
↺ Corrections and new questions feed the next release
Deliver a thin slice through all steps before widening any of them.

Start with the best sources

SourceReliabilityEffort
Master data and systems of recordHigh for what they ownMapping keys and meanings
Operational databases and APIsGood, with gapsMapping and refresh
Maintained spreadsheetsVariesValidation and ownership
Structured fields in documentsGood if templates are followedParsing
Free textVaries widelyExtraction, review and evidence tracking

Teams often start by extracting facts from documents although the same relationships already sit in a database. Check first. Mapping a trusted table is cheaper and far more accurate than reading prose.

A worked scope

Suppose the goal is to answer "Who leads each project and what does it depend on?" The first model needs three kinds (person, project, system) and two relationships (leads, uses). People come from the staff directory, systems from the asset register and the links from project documents. That is enough to build, test and show value. Budgets, risks and meetings can wait until a question requires them.

Intermediate Extraction and resolution

Extracting entities and relationships

MethodStrengthWeakness
Rules and patternsPrecise and cheap on regular textBrittle when wording changes
Trained extraction modelsConsistent and fast for fixed typesNeeds labeled examples
Language model with a schemaFlexible and quick to startCan invent or overgeneralize; cost per document
PeopleBest judgmentSlow; use for review and hard cases

When using a language model, give it the allowed types and definitions, require structured output, and require the exact supporting sentence for each fact. Then check in code that the quotation really appears in the source and mentions both ends. Pay special attention to negation ("no longer leads"), plans ("will replace") and reported opinions, which are easily recorded as current facts.

Entity resolution

Entity resolution decides whether two records describe the same real thing. It usually has three steps: blocking to avoid comparing every pair, scoring the candidates, and deciding with more than two outcomes.

"""Entity resolution with three outcomes: merge, review or keep apart."""
from difflib import SequenceMatcher
from itertools import combinations

records = [
    {"id": "a", "name": "Acme Ltd.", "country": "GB", "tax": "GB111"},
    {"id": "b", "name": "ACME Limited", "country": "GB", "tax": "GB111"},
    {"id": "c", "name": "Acme Ltd", "country": "GB", "tax": "GB999"},
    {"id": "d", "name": "Acme Ltd", "country": "GB", "tax": None},
    {"id": "e", "name": "Acme Ltd", "country": "US", "tax": None},
]
SUFFIXES = {"ltd", "limited", "inc", "llc"}

def clean(name):
    words = name.lower().replace(".", "").split()
    return " ".join(w for w in words if w not in SUFFIXES)

def decide(x, y):
    similar = SequenceMatcher(None, clean(x["name"]), clean(y["name"])).ratio()
    if x["tax"] and y["tax"]:
        if x["tax"] == y["tax"]:
            return "merge", similar, "same tax id"
        return "apart", similar, "different tax ids"
    if similar == 1.0:
        return "review", similar, "same name, no id to confirm"
    if similar >= 0.7:
        return "review", similar, "similar name"
    return "apart", similar, "names differ"

pairs = compared = 0
for x, y in combinations(records, 2):
    pairs += 1
    if x["country"] != y["country"]:       # blocking
        continue
    compared += 1
    verdict, score, why = decide(x, y)
    print(f'{x["id"]}-{y["id"]} {verdict:<6} name={score:.2f} {why}')
print(f"compared {compared} of {pairs} possible pairs after blocking")

Output:

a-b merge  name=1.00 same tax id
a-c apart  name=1.00 different tax ids
a-d review name=1.00 same name, no id to confirm
b-c apart  name=1.00 different tax ids
b-d review name=1.00 same name, no id to confirm
c-d review name=1.00 same name, no id to confirm
compared 6 of 10 possible pairs after blocking

Records a and b merge because they share a tax identifier despite different spelling. Records a and c have identical cleaned names but different identifiers, so they stay apart: name similarity alone would have merged two companies. Record d has no identifier and matches all three by name, so each pair goes to review. It cannot belong to both a and c, which shows why pairwise decisions must not be chained together automatically. The US record was never compared, because blocking by country removed it. That saves work, and it also means a wrong country code would hide a true match.

ErrorEffectGuard
False mergeFacts of different things are joined; may expose dataStrict automatic thresholds, conflicting identifiers block
Missed matchConnections and totals are incompleteSeveral blocking keys, aliases, review queues
Chain mergeA resembles B resembles C, so unrelated records joinCheck the whole cluster, limit cluster size
Irreversible mergeMistakes cannot be repairedKeep source records and link them to an entity

Never destroy the original records. Store a mapping from each source record to an entity identifier, with the reason and who or what decided, so that a merge can be undone.

Measuring quality

Label a sample by hand and compare. Precision is the share of recorded facts that are correct. Recall is the share of true facts that were recorded.

"""Score extracted facts, and keep source and validity with each one."""
gold = {("ng", "leads", "atlas"), ("atlas", "uses", "ledger"),
        ("park", "leads", "orion"), ("orion", "uses", "ledger")}
extracted = [
    ("ng", "leads", "atlas", "plan.md", 0.97),
    ("atlas", "uses", "ledger", "design.md", 0.92),
    ("park", "leads", "orion", "plan.md", 0.88),
    ("ng", "leads", "orion", "chat.txt", 0.55),
    ("atlas", "uses", "search", "ideas.md", 0.61),
]

def score(threshold):
    kept = {f[:3] for f in extracted if f[4] >= threshold}
    right = kept & gold
    return len(kept), len(right) / len(kept), len(right) / len(gold)

for threshold in (0.5, 0.8, 0.95):
    count, precision, recall = score(threshold)
    print(f"threshold {threshold:.2f}: {count} facts "
          f"precision {precision:.2f} recall {recall:.2f}")

leaders = {}
for subject, relation, project, source, _ in extracted:
    if relation == "leads":
        leaders.setdefault(project, []).append((subject, source))
for project, claims in sorted(leaders.items()):
    if len(claims) > 1:
        print(f"conflict, {project} has two leaders: {claims}")

history = [("park", "2025-01-01", "2026-03-31"), ("ng", "2026-04-01", None)]

def leader_on(day):
    return [who for who, start, end in history
            if start <= day and (end is None or day <= end)]

print("orion leader on 2026-02-10:", leader_on("2026-02-10"))
print("orion leader on 2026-05-10:", leader_on("2026-05-10"))

Output:

threshold 0.50: 5 facts precision 0.60 recall 0.75
threshold 0.80: 3 facts precision 1.00 recall 0.75
threshold 0.95: 1 facts precision 1.00 recall 0.25
conflict, orion has two leaders: [('park', 'plan.md'), ('ng', 'chat.txt')]
orion leader on 2026-02-10: ['park']
orion leader on 2026-05-10: ['ng']

Raising the threshold from 0.50 to 0.80 removes two wrong facts without losing a correct one in this sample. Raising it further keeps precision but discards most of what was known. Recall never reaches 1.00 at any setting shown, because one true fact was never extracted; no threshold can recover it. A model's confidence is only a ranking signal until you have checked how it relates to correctness on your own data.

DimensionHow to check
CorrectnessReviewed sample per relationship type and source
CompletenessCompare with an independent list; count missing required links
ConsistencyConstraint violations, such as two current owners
IdentityFalse merge and missed match rates
TimelinessAge since each fact was confirmed
EvidenceShare of facts with a working source link
UsefulnessTest questions answered correctly through the graph
Expert Conflict, time and governance

Conflicting facts

The quality example found two claimed leaders for one project. Do not pick silently. Choose a policy per relationship and record its result.

PolicyUse when
System of record winsOne source owns the fact
Newest confirmed winsFacts change often and dates are reliable
Corroboration requiredThe consequence of error is high
Keep both and flagA person must decide

"Newest" is risky when a recent chat message contradicts an approved plan. Rank sources by authority first.

Facts that change over time

Many facts are true only for a period. Instead of overwriting, close the old fact and add a new one, as the leader history in the example does: the same question returns different people for February and May. Two time lines can matter: when a fact was true in the world and when the graph learned it. Keeping both lets you answer "what did we believe at the time?", which audits often need. Erasure duties still apply, so history is not a reason to keep personal data indefinitely.

Provenance on every assertion

  • Source identifier, version and location of the evidence.
  • Method that produced it, including model and prompt versions.
  • Confidence, and whether a person confirmed it.
  • Valid-from, valid-to and recorded-at times.
  • Access restrictions inherited from the source.

When a source is deleted or corrected, use these links to remove or recheck the facts it supported, including inferred ones.

Keeping the graph current

Apply source changes incrementally with the patterns in Knowledge Ingestion and Real-Time Pipelines: stable identifiers, versions and tombstones. For extracted facts, replace all facts attributed to the old document version with those from the new one, so that removed statements disappear. Run reconciliation on a schedule to catch drift.

Governance and versioning

ObjectOwner decidesVersion control
OntologyDefinitions, allowed relationships, breaking changesFiles in a repository, reviewed
Mappings and promptsHow sources become factsSame, with tests
Data releasesWhen a build is fit to serveSnapshot or change log with identifier
Manual correctionsWho may override, and for how longSeparate, auditable layer reapplied after rebuilds

Treat a renamed relationship or a split class as a breaking change for every query and agent tool that uses it. Announce it, run old and new in parallel where needed and update test questions. Keep manual corrections apart from generated facts; otherwise the next rebuild erases them.

Release gates

Before publishing a build, check counts against the last release, constraint violations, merge cluster sizes and the answers to competency questions. A sudden change in any of them deserves a person's look before agents rely on it.

Security

Whoever can write to a source can influence the graph. Weigh facts by source trust, require review for relationships that grant rights or move money, restrict who may add corrections and log changes. A false "approves" edge is far more dangerous than a false paragraph, because it looks like structured truth.

Illustrative example: supplier graph

A purchasing team builds a graph of suppliers, contracts and products. Registry numbers drive automatic merges; name-only matches go to a weekly review. Contract dates close old relationships. An early release is held back when the gate shows one supplier cluster suddenly holding hundreds of records, caused by a blank identifier being treated as equal.

Planning the effort

Initial loading is visible and exciting. Review and maintenance take most of the time over a graph's life, so estimate them from the start.

WorkEstimate fromWays to reduce it
Mapping structured sourcesNumber of sources and how consistent their keys areShared identifiers, reusable mappings
Extraction runsDocument volume and change rateProcess changed documents only, use cheaper methods for regular text
Match reviewUncertain pairs per week and minutes per decisionBetter identifiers at the source, remembered decisions
Fact reviewSample size per relationship typeReview by risk, not uniformly
Model changesQueries and tools affectedNamed tools that hide the schema

Remember review decisions. If a person decided that two records are different, store that as a constraint, or the same pair will return to the queue after every rebuild. The best long-term fix for poor matching is usually upstream: capturing a registry number or an internal key at the moment a record is created saves countless later comparisons.

Publishing a release to agents

Agents should read a stable, named release, not a graph that changes under them in the middle of a task. Build into a separate space, run the gates, then point readers at the new release. Record the release identifier in each answer's trace so that a disputed result can be reproduced. Urgent removals, such as an erasure or a revoked permission, must not wait for the next release: apply them to the live graph immediately and to the next build.

Collect feedback where the graph is used. When someone says a dependency or owner is wrong, capture the exact edge, route it to the owner of its source and fix the source where possible. A correction made only in the graph hides the fault from every other system that reads the same data.

Common mistakes

  • Extracting from text what a database already knows.
  • Merging on names alone.
  • Treating missing identifiers as matching.
  • Overwriting history and losing evidence.
  • Reporting precision without recall.
  • Manual fixes that vanish at the next rebuild.
  • No owner for definitions.

Checklist

  • Scope is tied to written questions.
  • Trusted structured sources are loaded first.
  • Extracted facts quote verifiable evidence.
  • Merges are reversible and conflicting identifiers block them.
  • Precision and recall are measured by relationship type.
  • Conflict policies and time validity are defined.
  • Releases pass gates and can be rolled back.
  • Corrections survive rebuilds.

Frequently asked questions

How accurate must a graph be?

It depends on the decision. Suggestions for a person to check can tolerate errors that automated access decisions cannot. Set targets per relationship type.

Should a model decide merges?

It can help rank and explain candidates. Use strong identifiers for automatic merges and keep doubtful or consequential ones for review.

How do I handle a fact with no source?

Mark it unverified and keep it out of consequential answers, or remove it. Unsourced facts cannot be corrected or deleted reliably.

How often should the graph be rebuilt?

Update incrementally and rebuild when the model, mappings or extraction method changes. Test that a rebuild reproduces approved corrections and deletions.

References and further reading

Next steps