Skip to content
ImagineWorld

Knowledge Graphs and Semantic Modeling

node_idnode-book_neo4j-mastery_chapter-07-knowledge-graphs-and-semantic-modeling
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleKnowledge Graphs and Semantic Modeling
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Knowledge Graphs and Semantic Modeling

Section titled “Chapter 7 — Knowledge Graphs and Semantic Modeling”

Chapter 5: Knowledge Graphs and Semantic Modeling

Section titled “Chapter 5: Knowledge Graphs and Semantic Modeling”

The year 2025 marks the moment when knowledge graphs ceased to be an academic curiosity or a niche technology used only by the largest technology companies. They have become the indispensable semantic backbone of every serious generative-AI deployment, every enterprise master data management initiative, every regulatory compliance platform, and every intelligent search or recommendation system that must explain its reasoning. A knowledge graph is no longer a nice-to-have layer; it is the only known data structure that can simultaneously satisfy the demands of structured reasoning required by symbolic AI, the statistical pattern recognition required by neural systems, and the auditability required by regulated industries.

Neo4j has quietly become the de-facto platform for enterprise knowledge graphs because it combines the expressive power of the labeled property graph model with the performance required for real-time reasoning at billions of triples, the flexibility to evolve schemas without downtime, and the richest ecosystem of semantic tooling in the industry. This chapter teaches how to design, populate, query, and activate knowledge graphs that stand at the center of modern AI architectures.

The journey begins with the fundamental distinction between data graphs and knowledge graphs, proceeds through rigorous ontology engineering, continues with industrial-scale ingestion and entity resolution, advances into sophisticated semantic query techniques, and culminates with concrete patterns for integrating knowledge graphs with large language models, retrieval-augmented generation, and agentic workflows.

5.1 Introduction to Knowledge Graph Concepts

Section titled “5.1 Introduction to Knowledge Graph Concepts”

A knowledge graph is a graph whose nodes represent real-world entities and concepts, whose relationships represent semantically meaningful predicates, and whose structure is governed by an explicit or implicit ontology that defines the allowed types, properties, and logical constraints. The critical difference between a knowledge graph and an arbitrary property graph is intentional semantics: every label, relationship type, and property carries a precise, machine-interpretable meaning that can be reasoned over automatically.

Three foundational principles separate mature knowledge graphs from mere connected data.

First, entities possess stable, globally unique identifiers that survive name changes, mergers, splits, and typos. A pharmaceutical company does not identify “Aspirin” by its trade name but by its INN (International Nonproprietary Name) or CAS registry number. A financial institution does not identify “JPMorgan Chase & Co.” by its ticker symbol alone but by its LEI (Legal Entity Identifier). These canonical identifiers are the anchors of truth.

Second, relationships are typed with predicates drawn from a controlled vocabulary (often an ontology). Instead of a generic :RELATED_TO relationship, a mature knowledge graph asserts :DRUG_TREATS_CONDITION, :PERSON_HOLDS_POSITION_AT_ORGANIZATION, or :GENE_ENCODATES_PROTEIN. This predicate typing enables logical inference and cross-domain integration.

Third, the graph is governed by an ontology that defines classes, properties, domains, ranges, cardinality constraints, and logical axioms. Even when the ontology is lightweight and implicit, its existence distinguishes knowledge graphs from opportunistic data graphs.

These principles produce three superpowers that no other data architecture can replicate simultaneously: explainable reasoning, cross-silo integration, and the ability to fuse structured enterprise data with unstructured text and generative output in a single coherent model.

5.2 Ontologies, Taxonomies, and Entity Relationships

Section titled “5.2 Ontologies, Taxonomies, and Entity Relationships”

An ontology is a formal, explicit specification of a conceptualization. In practice, most enterprise knowledge graphs operate with a spectrum of formality ranging from rigid OWL-DL ontologies to lightweight taxonomies expressed as simple hierarchies.

A taxonomy is a controlled hierarchy of concepts connected by broader/narrower relationships (subClassOf, subPropertyOf). It answers classification questions. An ontology adds property definitions, domain/range constraints, cardinality, and logical axioms. It answers reasoning questions.

cypher

1 // 5.2.1 Minimal but powerful enterprise ontology expressed in Neo4j

// Core classes

CREATE (:owl__Class {uri: “http://example.org/ontology#Organization”})

CREATE (:owl__Class {uri: “http://example.org/ontology#LegalEntity”}) -[:rdfs__subClassOf]->(:owl__Class {uri: “http://example.org/ontology#Organization”})

CREATE (:owl__Class {uri: “http://example.org/ontology#Person”})

// Object properties with domain and range

CREATE (:owl__ObjectProperty {uri: “http://example.org/ontology#hasLegalEntity”})

CREATE (:owl__ObjectProperty {uri: “http://example.org/ontology#employedBy”})

// Data properties

CREATE (:owl__DatatypeProperty {uri: “http://example.org/ontology#legalName”})

CREATE (:owl__DatatypeProperty {uri: “http://example.org/ontology#leiCode”})

// Axiom: every LegalEntity must have exactly one leiCode

CREATE CONSTRAINT legal_entity_lei_unique IF NOT EXISTS FOR (n:LegalEntity) REQUIRE n.leiCode IS UNIQUE;

Commentary: Lines 3–5 create a lightweight class hierarchy using the conventional owl__ and rdfs__ prefixes (no OWL reasoner required). Lines 8–13 define reusable predicate vocabulary. Line 16 enforces a cardinality constraint using Neo4j’s native constraint system.

Reification for Statement-Level Metadata

Knowledge is rarely absolute. Statements have provenance, validity periods, confidence scores, and sources. Reification turns statements into first-class nodes.

cypher

1 // 5.2.2 Reified statement with provenance and temporal validity 2 MATCH (p:Person {personId: “P-123”}) 3 MATCH (org:LegalEntity {leiCode: “5493000IBP36HF4T0M88”})

4

5 CREATE (stmt:Statement { 6 statementId: apoc.create.uuid(), 7 predicate: “employedBy”, 8 confidence: 0.97, 9 assertedAt: datetime(), 10 source: “hr-system-export-2025-03” 11 })

12

13 CREATE (stmt)-[:SUBJECT]->(p) 14 CREATE (stmt)-[:OBJECT]->(org) 15 CREATE (stmt)-[:VALID_FROM]->(date(“2024-01-01”)) 16 CREATE (stmt)-[:VALID_TO]->(date(“2026-12-31”))

17

18 // Query current employment 19 WITH datetime() AS now 20 MATCH (stmt:Statement {predicate: “employedBy”}) 21 -[:VALID_FROM]->(from), (stmt)-[:VALID_TO]->(to) 22 WHERE from <= now <= to 23 MATCH (stmt)-[:SUBJECT]->(person), (stmt)-[:OBJECT]->(employer) 24 RETURN person.name, employer.legalName;

Commentary: Lines 5–11 create a reified statement node carrying metadata. Lines 15–16 attach temporal validity using dedicated relationships (preferred pattern over properties for range queries).

Large enterprises use a three-layer approach: upper ontology (DUL, BFO), mid-level domain ontologies, and enterprise-specific extensions.

// 5.2.3 Enterprise upper ontology alignment
CREATE (:Class:Upper {uri: "http://purl.org/dul/DUL.owl#Agent"})
CREATE (:Class:Upper {uri: "http://purl.org/dul/DUL.owl#Organization"})
CREATE (:Class:Domain {uri: "http://example.org/finance#Counterparty"})
-[:subClassOf]->(:Class:Upper {uri: "http://purl.org/dul/DUL.owl#Organization"})
CREATE (:Class:Enterprise {uri: "http://company.com/ontology#Client"})
-[:subClassOf]->(:Class:Domain {uri: "http://example.org/finance#Counterparty"});

5.3 Mapping Real-World Data into Semantic Graphs

Section titled “5.3 Mapping Real-World Data into Semantic Graphs”

Ninety-five percent of knowledge graph effort is data integration and entity resolution.

Entity Resolution at Scale with Fuzzy Matching and Blocking

Section titled “Entity Resolution at Scale with Fuzzy Matching and Blocking”
// 5.3.1 Blocking + fuzzy matching pipeline using APOC
// Step 1: Create phonetic blocks
MATCH (p:Person)
WITH p,
apoc.text.clean(p.name) AS cleanName,
apoc.text.phonetic(cleanName) AS phonetic
SET p.namePhonetic = phonetic

// Step 2: Candidate generation using blocking keys

WITH phonetic, collect(p) AS candidates WHERE size(candidates) > 1 AND size(candidates) < 100

// Step 3: Pairwise similarity

UNWIND apoc.coll.pairsMin(candidates) AS pair WITH pair[0] AS p1, pair[1] AS p2 WHERE id(p1) < id(p2) // avoid duplicates AND apoc.text.levenshteinSimilarity(p1.name, p2.name) > 0.92 MERGE (p1)-[s:SIMILAR_TO {score: apoc.text.levenshteinSimilarity(p1.name, p2.name)}]->(p2) ON CREATE SET s.source = “fuzzy-name-match”;

Master Entity Creation with Survivorship Rules

cypher

// 5.3.2 Golden record creation using survivorship

MATCH (cluster)-[:SIMILAR_TO*1..5]-(member) WITH cluster, collect(member) AS members // Choose the record with most properties as master WITH cluster, apoc.coll.sortMaps(members, ’^’)[-1] AS masterRecord MERGE (master:MasterPerson { masterId: apoc.create.uuid(), created: datetime() }) SET master += properties(masterRecord) WITH master, members UNWIND members AS member MERGE (master)-[:HAS_SOURCE {system: member.sourceSystem, ingested: member.ingested}]->(member);

RDF vs Property Graph – Pragmatic Hybrid Approach

Section titled “RDF vs Property Graph – Pragmatic Hybrid Approach”

Most enterprises adopt a hybrid model: import RDF when required for standards compliance, store natively as property graph for performance.

// 5.3.3 Ingesting FIBO (Financial Industry Business Ontology) fragment
CALL n10s.graphconfig.init({handleVocabUris: "MAP", keepLangTag: true});
// Import TTL using neosemantics
CALL n10s.rdf.import.fetch(
"file:///var/lib/neo4j/import/fibo-be-le-lei.ttl",
"Turtle"
) YIELD nodesCreated, relationshipsCreated
RETURN nodesCreated, relationshipsCreated;
// Map FIBO classes to enterprise labels
MATCH (n) WHERE n.`http://www.w3.org/1999/02/22-rdf-syntax-ns#type` = "http://fibo.foundry.org/LegalEntity"
SET n:LegalEntity
REMOVE n.`http://www.w3.org/1999/02/22-rdf-syntax-ns#type`;

5.4 Querying Knowledge Graphs with Cypher and APOC Procedures

Section titled “5.4 Querying Knowledge Graphs with Cypher and APOC Procedures”

Semantic queries combine pattern matching with inference.

// 5.4.1 SPARQL-style query using n10s inference
CALL n10s.inference.nodesLabeled("LegalEntity", {
inLabel: "LegalEntity",

subPropertyOf: “rdfs:subPropertyOf”, subClassOf: “rdfs:subClassOf” }) YIELD node RETURN node.legalName, labels(node);

Path-Based Inference with Variable-Length Relationships

Section titled “Path-Based Inference with Variable-Length Relationships”

cypher // 5.4.2 Infer ultimate beneficial ownership through arbitrary nesting MATCH path = (individual:Person)-[:OWNS|CONTROLS*]->(entity) WHERE entity:LegalEntity AND all(r IN relationships(path) WHERE r.ownershipPct IS NOT NULL) WITH individual, entity, reduce(pct = 1.0, r IN relationships(path) | pct * coalesce(r.ownershipPct, 1.0) / 100.0) AS effectivePct WHERE effectivePct >= 0.25 RETURN individual.name, entity.legalName, effectivePct ORDER BY effectivePct DESC;

cypher // 5.4.3 Retrieval-augmented generation preparation CALL db.index.fulltext.queryNodes(“documentIndex”, “quantum computing acquisition”) YIELD node, score MATCH (node)-[:MENTIONS]->(e) WHERE (e:Person OR e:Organization OR e:Technology) WITH e, collect({text: node.text, relevance: score}) AS contexts RETURN e.uri AS entity, contexts ORDER BY size(contexts) DESC LIMIT 20;

5.5 Integrating Knowledge Graphs with AI and NLP Applications

Section titled “5.5 Integrating Knowledge Graphs with AI and NLP Applications”

The modern AI stack is a knowledge graph sits in the middle.

Vector + Graph Hybrid Retrieval (GraphRAG)

Section titled “Vector + Graph Hybrid Retrieval (GraphRAG)”
# 5.5.1 GraphRAG implementation using LangChain + Neo4j
from langchain_community.graphs import Neo4jGraph
from langchain_openai import OpenAIEmbeddings
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI
graph = Neo4jGraph(
url="bolt://localhost:7687",
username="neo4j",
password="Mastery2025!"
)
# Refresh schema for accurate Cypher generation
graph.refresh_schema()
chain = GraphCypherQAChain.from_llm(
ChatOpenAI(temperature=0, model="gpt-4o"),
graph=graph,
verbose=True,
top_k=20
)
response = chain.run(
"Which pharmaceutical companies have acquired startups working on GLP-1 agonists since 2023?"
)

25 )

26 print(response)

Agentic Reasoning with Knowledge Graph Tools

Section titled “Agentic Reasoning with Knowledge Graph Tools”

1 # 5.5.2 LangGraph agent with Neo4j tool 2 from langgraph.prebuilt import create_react_agent 3 from langchain.tools import Tool

4

5 def cypher_tool(query: str) -> str: 6 result = graph.query(query) 7 return str(result)

8

9 tools = [ 10 Tool( 11 name=“knowledge_graph”, 12 func=cypher_tool, 13 description=“Useful for questions about companies, people, ownership, and biomedical entities” 14 ) 15 ]

16

17 agent = create_react_agent(ChatOpenAI(model=“gpt-4o”), tools)

18

19 result = agent.invoke({ 20 “messages”: [(“human”, “Who ultimately controls the entity with LEI 5493000IBP36HF4T0M88?”)] 21 })

Automated Knowledge Graph Construction from Unstructured Text

Section titled “Automated Knowledge Graph Construction from Unstructured Text”

1 # 5.5.3 Zero-shot entity and relation extraction with LLM

from langchain_openai import ChatOpenAI

from langchain.prompts import PromptTemplate

llm = ChatOpenAI(model=“gpt-4o-mini”, temperature=0)

prompt = PromptTemplate.from_template(""" Extract entities and relationships from the following text. Use only these types: Entities: Person, Organization, Drug, Condition, Technology Relationships: ACQUIRED, DEVELOPED, TREATS, INVESTED_IN

Text: {text}

Return valid JSON matching this schema: {schema} """)

chain = prompt | llm.with_structured_output(schema)

for entity in result.entities: graph.query(“MERGE (e:Entity {uri: uri}) SET e += props”, {“uri”: entity.uri, “props”: entity.props})

The knowledge graph is the only data structure that can simultaneously satisfies the requirements of classical symbolic reasoning, modern neural retrieval, and enterprise governance. The practitioner who has mastered this chapter can now:

  1. Design ontologies that survive decades of evolution without breaking existing queries.
  2. Ingest and resolve entities from dozens of source systems into a single source of truth.
  1. Write semantic queries that combine inference, full-text, and vector similarity in single statements.
  2. Position the knowledge graph as the reasoning backbone for retrieval-augmented generation and agentic AI systems.
  3. Automate the population and maintenance of the graph from unstructured text using contemporary LLM capabilities.

The knowledge graph is no longer the end goal. It is the beginning of truly intelligent systems that can explain why they reached a conclusion, correct themselves when new facts arrive, and serve as the permanent memory layer for every AI application in the enterprise.

The next chapters will show how to operate these knowledge graphs at global scale, secure them for regulatory compliance, and embed them into microservices and real-time decisioning platforms. The era of disconnected data is over. The era of connected, meaningful, and reasoning knowledge has arrived.