Learn how to build knowledge graphs using the Cognee framework together with your own custom ontology. This guide will walk you through adding text data, integrating an OWL-based ontology to enrich your graph, and querying for insights.
Ontologies in Cognee provide external ground truth that enriches your knowledge graphs with predefined semantic relationships, improving entity matching and knowledge representation quality.

What You’ll Accomplish

By following this guide, you will:

Add Rich Text Data

Company InformationIngest raw text data about car manufacturers and technology companies.

Integrate Custom Ontology

Semantic StructureUse an OWL file that defines semantic relationships between entities.

Build Knowledge Graph

Graph GenerationRun the Cognee pipeline to generate an ontology-enriched knowledge graph.

Query & Visualize

Extract InsightsSearch the graph and visualize the results with semantic relationships.

What You’ll Learn

1

Environment Setup

Installing Cognee and preparing your workspace for ontology processing.
2

Data Ingestion

Adding raw text data for processing with semantic structure.
3

Ontology Integration

Using a custom ontology to structure your data with domain knowledge.
4

Graph Creation

Running the pipeline to build your ontology-enhanced knowledge graph.
5

Query & Visualization

Searching the graph and visualizing the results with rich semantic context.

Prerequisites

Before starting, ensure you have:

Technical Requirements

Step 1: Install Cognee

Set Up Development Environment

Navigate to the Cognee repository and install with all dependencies:
cd cognee
uv sync --dev --all-extras --reinstall
This installs Cognee with all necessary dependencies for ontology processing and graph generation.

Step 2: Prepare Your Text Data

Create Sample Data

Create a Python script and define your text data. We’ll use information about car manufacturers and technology companies:
Automotive Industry Data
text_1 = '''
1. Audi
Audi is known for its modern designs and advanced technology. Founded in the early 1900s, the brand has earned a reputation for precision engineering and innovation. With features like the Quattro all-wheel-drive system, Audi offers a range of vehicles from stylish sedans to high-performance sports cars.

2. BMW
BMW, short for Bayerische Motoren Werke, is celebrated for its focus on performance and driving pleasure. The company's vehicles are designed to provide a dynamic and engaging driving experience, and their slogan, "The Ultimate Driving Machine," reflects that commitment. BMW produces a variety of cars that combine luxury with sporty performance.

3. Mercedes-Benz
Mercedes-Benz is synonymous with luxury and quality. With a history dating back to the early 20th century, the brand is known for its elegant designs, innovative safety features, and high-quality engineering. Mercedes-Benz manufactures not only luxury sedans but also SUVs, sports cars, and commercial vehicles, catering to a wide range of needs.

4. Porsche
Porsche is a name that stands for high-performance sports cars. Founded in 1931, the brand has become famous for models like the iconic Porsche 911. Porsche cars are celebrated for their speed, precision, and distinctive design, appealing to car enthusiasts who value both performance and style.

5. Volkswagen
Volkswagen, which means "people's car" in German, was established with the idea of making affordable and reliable vehicles accessible to everyone. Over the years, Volkswagen has produced several iconic models, such as the Beetle and the Golf. Today, it remains one of the largest car manufacturers in the world, offering a wide range of vehicles that balance practicality with quality.
'''
This sample data provides rich information about companies that will be structured using our custom ontology.

Step 3: Create Your Custom Ontology

Define Ontology Structure

Create a custom ontology file in OWL format. You can find a complete example at: Ontology file example Here’s the sample structure for basic_ontology.owl:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:ns1="http://example.org/ontology#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
>
  <rdf:Description rdf:about="http://example.org/ontology#Volkswagen">
    <rdfs:comment>Created for making cars accessible to everyone.</rdfs:comment>
    <ns1:produces rdf:resource="http://example.org/ontology#VW_Golf"/>
    <ns1:produces rdf:resource="http://example.org/ontology#VW_ID4"/>
    <ns1:produces rdf:resource="http://example.org/ontology#VW_Touareg"/>
    <rdf:type rdf:resource="http://example.org/ontology#CarManufacturer"/>
    <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/>
  </rdf:Description>
  <!-- Additional ontology definitions follow -->
</rdf:RDF>
This ontology defines relationships between car manufacturers and their products, providing semantic structure to our knowledge graph.

Step 4: Build the Complete Pipeline

Create Main Script

Create your main Python script with the complete pipeline. You can find a working demo at: Ontology demo example
import cognee
import asyncio
import logging
import os

from cognee.api.v1.search import SearchType
from cognee.api.v1.visualize.visualize import visualize_graph
from cognee.shared.utils import setup_logging

# Define your text data (insert your full texts for text_1 and text_2)
text_1 = """insert full text_1 here"""
text_2 = """insert full text_2 here"""

async def main():
    # Step 1: Reset data and system state
    await cognee.prune.prune_data()
    await cognee.prune.prune_system(metadata=True)

    # Step 2: Add text data
    text_list = [text_1, text_2]
    await cognee.add(text_list)

    # Step 3: Create knowledge graph using the custom ontology
    ontology_path = os.path.join(
        os.path.dirname(os.path.abspath(__name__)), "ontology_input_example/basic_ontology.owl"
    )
    pipeline_run = await cognee.cognify(ontology_file_path=ontology_path)
    print("Knowledge with ontology created.")

    # Step 4: Calculate descriptive metrics
    await cognee.get_pipeline_run_metrics(pipeline_run, include_optional=True)
    print("Descriptive graph metrics saved to database.")

    # Step 5: Query insights from the graph
    search_results = await cognee.search(
        query_type=SearchType.GRAPH_COMPLETION,
        query_text="What are the exact cars and their types produced by Audi?",
    )
    print(search_results)

    # Step 6: Visualize the knowledge graph and save it to HTML
    await visualize_graph()

if __name__ == "__main__":
    setup_logging(logging.INFO)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(main())
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())

Step 5: Execute Your Pipeline

Run the Script

Execute your script from the terminal:
python your_script.py
The script will process your data through the ontology-enhanced pipeline and generate visualizations and insights.

Expected Output

You should see output similar to:
Output
Knowledge with ontology created.
Descriptive graph metrics saved to database.
[Search results about Audi cars and their types]

Visualization

The script generates an HTML visualization file that you can open in your browser:
Check for graph_visualization.html in your working directory. This file contains an interactive visualization of your ontology-enhanced knowledge graph.

Ontology Matching Algorithm

Cognee uses a sophisticated matching algorithm to integrate ontologies with extracted knowledge:

Entity Extraction

Advanced Usage Examples

Domain-specific Queries
# Query car manufacturers
car_results = await cognee.search(
    query_type=SearchType.GRAPH_COMPLETION,
    query_text="What are the exact cars and their types produced by Audi?"
)

# Query technology companies
tech_results = await cognee.search(
    query_type=SearchType.GRAPH_COMPLETION,
    query_text="What products does Apple develop and how do they relate?"
)

# Query relationships across domains
cross_domain = await cognee.search(
    query_type=SearchType.INSIGHTS,
    query_text="Compare innovation approaches between car manufacturers and tech companies"
)

print("Car manufacturer insights:", car_results)
print("Technology company insights:", tech_results)
print("Cross-domain analysis:", cross_domain)

Technical Implementation

For developers interested in the implementation details:

OntologyResolver Class

Summary

In this tutorial, you learned how to:

Set Up Environment

Development SetupInstall Cognee and prepare your workspace for ontology processing.

Ingest Data

Data ProcessingAdd raw text data about car manufacturers and technology companies.

Integrate Ontology

Semantic StructureUse a custom OWL ontology to define relationships and enhance data structure.

Generate Insights

Knowledge DiscoveryBuild the graph, query for insights, and visualize the semantic relationships.
This method not only helps you organize complex data but also leverages semantic relationships to enhance your data insights through structured ontological knowledge.

Next Steps

Now that you’ve mastered ontology integration, you can:
1

Create Complex Ontologies

Advanced StructuresBuild more complex ontologies with additional relationship types and domain-specific classes.
2

Multiple Ontologies

Multi-domain IntegrationIntegrate multiple ontologies for richer semantic structures across different domains.
3

Domain-specific Graphs

Specialized Use CasesBuild domain-specific knowledge graphs for specialized applications (medical, legal, financial).
4

Advanced Querying

Sophisticated AnalysisExplore advanced querying techniques with your ontology-enhanced graphs.

Additional Resources