Start With Entities and Triples in Python

printed knowledge graph diagram on white paper

Start a Python knowledge graph with entities and triples

To create a Python knowledge graph, start with the things you want to track, give each one a unique ID, and connect them with labeled relationships. Write each connection as a triple: subject, relationship, object. For example, “Store 1, sells, Product 7” links a store to a product. Add details such as names or dates as properties, then store the data in a graph tool so you can query those connections.

If your starting point is text, Python tools can help find entities and suggest relationships. Check those results before adding them to the graph: two names may refer to the same thing, and a sentence may not support the relationship a tool suggests.

I’m Clayton Johnson, founder of SmallBizSEO, where my work focuses on organizing useful information for search and AI-driven discovery. I bring that focus on clear, verifiable connections to this python knowledge graph guide.

How to build a Python knowledge graph: identify entities, assign IDs, create triples, check facts, and query connections

Simple guide to python knowledge graph:

Model, build, and connect your graph

A knowledge graph models entities and relationships, then connects them to a graph database. The same design thinking helps when you supercharge large language models with knowledge graph architecture, because the model gets structured facts instead of loose text.

Entities, Relationships, and Properties

An entity is a real-world object, concept, or event, such as a person, building, or vehicle. In the graph it is a node. A relationship is an edge that says how two entities connect, such as knows, worksat, or drives. Properties are key-value pairs on either one, such as name, startdate, make, or model.

Three habits keep the graph clean:

  • Give every entity a canonical ID so "JWST" and "James Webb Space Telescope" become one node.
  • Store facts as subject-predicate-object triples.
  • Keep relationship direction consistent, so "Person works_at Company" never flips.

Defining a Schema and Connecting to ArcGIS Knowledge

A schema (or ontology) lists the allowed node labels, relationship types, property types, and unique identifiers before data is loaded. Define it before you load data. It keeps extraction focused and makes the graph easier to validate and trace back to its sources.

ArcGIS Knowledge is one enterprise option, and it handles both spatial and nonspatial entities. It needs an ArcGIS Enterprise portal configured for ArcGIS Knowledge. Relationships are always nonspatial. The steps:

  1. Connect with GIS('home').
  2. Open an existing graph with KnowledgeGraph(url=url, gis=gis).
  3. Or create one with gis.content.createservice(), using servicetype='KnowledgeGraph' and capabilities such as Query, Editing, Create, Update, and Delete. Then initialize KnowledgeGraph with result.url.
  4. Inspect the model with querydatamodel(as_dict=False), which returns a GraphDataModel.

Knowledge graph schema showing entity types, relationship types, and properties

The data model reports the spatial reference (for example WKID 4326), strictness, the unique identifier property, search indexes, and constraint rules. In the documentation's example, a Vehicle entity type has objectid, globalid, and make properties with field indexes. A constraint rule can also limit a relationship, such as allowing HasDocument links only to Document entities.

If you work with files and command-line pipelines instead, the Knowledge Graph Toolkit (KGTK) uses TSV as its main format. It supports N-Triples and Neo4j imports and chains operations such as filtering, validation, PageRank, and embeddings through Unix pipes.

Building a Knowledge Graph From Unstructured Text

Building a Python knowledge graph from text requires cleaning the copy, extracting entities, mapping relationships, normalizing names, and loading the resulting triples into a graph database. A good pipeline combines classic NLP with an LLM.

  1. Preprocess: remove tabs, newlines, and stray bracketed content.
  2. Run spaCy named entity recognition to label PERSON, ORG, and GPE entities.
  3. Use syntactic parsing to pull subject-verb-object triples.
  4. Ask an LLM to extract relationships using your schema, and return only JSON with nodes and edges. Using NER and an LLM together catches more than either alone.
  5. Resolve duplicates by mapping variants to short canonical names.
  6. Add source metadata to every relation so you can trace it.

Event detection and co-occurrence analysis make the graph better. "Company A acquired Company B" says far more than "A and B are related," and co-occurrence reveals hidden links and improves connectivity. Treat co-occurrence as a hint, though, since it adds noise.

Text-to-graph extraction workflow from raw text to entities, triples, and a graph database

For chunked documents, the Neo4j SimpleKGPipeline handles loading, splitting, embedding, schema, extraction, and writing. Its User Guide: Knowledge Graph Builder recommends an explicit schema, or an automatically extracted one, and structured output where the LLM supports it. It keeps Document and Chunk nodes linked, and entity resolution merges nodes with the same label and name by default. Chunks of roughly 500 to 1,200 tokens are common, and chunk size should match your model's context window.

Expect errors: LLMs can invent relations or miss entities. Also remember that sending text to an LLM API raises privacy questions, so review what you share.

Use Python knowledge graphs for retrieval and prediction

Python knowledge graphs support retrieval and prediction by connecting text to entities and relationships. Two common uses are GraphRAG and link prediction.

Vector and Cypher Retrieval for GraphRAG

Vector and Cypher retrieval improve GraphRAG by combining similarity search with relationship traversal across connected entities. Vector search finds similar chunks, while adding Cypher traversal returns the entities and relationship paths around those chunks. The GraphRAG for Python package covers the full flow: build the graph, create a vector index, retrieve, and run GraphRAG. It offers Vector, Vector Cypher, Hybrid, Hybrid Cypher, and Text2Cypher retrievers. Vector search is approximate nearest-neighbor, so results may not be exact, and the index dimensions must match your embeddings.

Vector retrieval versus graph-expanded retrieval

Feature Vector retrieval Vector plus Cypher
Finds Similar text chunks Chunks plus connected entities
Context Isolated passages Relationship paths across documents
Answers Broader, more generic More domain-specific
Setup Vector index Index plus traversal query

In a medical PDF example, the Cypher version produced more technical answers. A custom prompt template that tells the LLM to answer only from the supplied context keeps responses grounded and easier to cite.

Training Knowledge Graph Embeddings With PyKEEN

PyKEEN learns numerical representations of graph nodes and relationship types, then scores plausible links that are absent from the data. Start with the official PyKEEN first-steps tutorial and run its stable Nations example:

Use the documentation for the installed PyKEEN release to confirm compatible Python versions. The tutorial’s pipeline runs standard training and evaluates ranked predictions; when moving to a custom graph, load its triples with a TriplesFactory.

It includes 37 built-in datasets, 5 inductive datasets, 40 models, and 22 representation types. The largest dataset, the Clinical Knowledge Graph, has 7,617,419 entities and 26,691,525 triples. Nations is tiny, with 14 entities and 1,992 triples, so it is ideal for a first run.

Infographic of PyKEEN scale: 37 datasets, 40 models, 22 representation types infographic

Goal Embedding training Graph retrieval
Main task Predict missing links Fetch facts for answers
Tool PyKEEN GraphRAG retrievers
Output Ranked candidate triples Context for an LLM
Check Rank-based metrics Answer accuracy and citations

Validating a Graph and Making It a Trusted Resource

A trusted knowledge graph needs accurate entities and relationships, validated data, and clear provenance. Build these checks in:

  • Measure precision and recall on a sample you review by hand.
  • Run duplicate detection and entity resolution regularly.
  • Validate against the schema and check relationship direction.
  • Verify events and treat co-occurrence links as lower confidence.
  • Keep a source and confidence score on every relation.
  • Update incrementally and test RAG answers against known questions.

At SmallBizSEO, this is how we think about structured information for search, and our knowledge graph work follows the same discipline. Using structured data such as JSON-LD helps machines read those entities cleanly.

Your first triple is the hardest one

Start small: pick ten entities, define a schema, add triples, and check each fact. Once that works, add text extraction, then retrieval, then embeddings. A graph you can trust beats a large one you cannot.