# How to Use Ontologies with Cognee: OWL/RDF Integration Guide

> Learn to integrate OWL/RDF ontologies with Cognee using RDFLibOntologyResolver. Enrich entities and validate data effectively. Get started in this guide.

- Repository: [Topoteretes/cognee](https://github.com/topoteretes/cognee)
- Tags: how-to-guide
- Published: 2026-03-16

---

**Cognee validates and enriches extracted entities against OWL/RDF ontologies using the `RDFLibOntologyResolver` class, configurable via environment variables or programmatic `Config` objects.**

Cognee is an open-source knowledge graph construction framework that supports ontology-driven entity validation. By integrating OWL or RDF vocabularies, you can ensure that entities extracted from your documents align with predefined semantic concepts, resulting in cleaner, more structured graph data.

## Architecture Overview

Cognee’s ontology subsystem is built around two core abstractions that separate interface from implementation.

### BaseOntologyResolver Interface

All ontology resolvers must implement the abstract class defined in [`cognee/modules/ontology/base_ontology_resolver.py`](https://github.com/topoteretes/cognee/blob/main/cognee/modules/ontology/base_ontology_resolver.py). This interface mandates three key capabilities: looking up normalized entity names, finding closest matches via fuzzy search, and extracting subgraphs for specific concepts.

### RDFLibOntologyResolver Implementation

The concrete implementation `RDFLibOntologyResolver` (located in [`cognee/modules/ontology/rdf_xml/RDFLibOntologyResolver.py`](https://github.com/topoteretes/cognee/blob/main/cognee/modules/ontology/rdf_xml/RDFLibOntologyResolver.py)) uses the **RDFLib** library to parse OWL files. During initialization, it constructs two internal lookup tables—`classes` and `individuals`—that map normalized names to their RDF URIs. These tables enable O(1) entity resolution during graph construction.

## Configuring the Ontology Resolver

You can supply ontology configuration via environment variables for declarative setups, or construct a `Config` dict programmatically for dynamic scenarios.

### Environment Variable Configuration

Create a `.env` file in your project root with the following variables (read by `OntologyEnvConfig` in [`cognee/modules/ontology/ontology_env_config.py`](https://github.com/topoteretes/cognee/blob/main/cognee/modules/ontology/ontology_env_config.py)):

```dotenv
ONTOLOGY_RESOLVER=rdflib
ONTOLOGY_MATCHING=fuzzy
ONTOLOGY_FILE_PATH=examples/ontologies/scientific_ontology.owl

```

**Variable reference:**
- `ONTOLOGY_RESOLVER`: Resolver backend (currently only `"rdflib"`)
- `ONTOLOGY_MATCHING`: Matching strategy (`"fuzzy"` is supported)
- `ONTOLOGY_FILE_PATH`: Path (or comma-separated paths) to OWL/RDF files

### Programmatic Configuration

For dynamic pipeline construction, instantiate the resolver directly and pass it via the `Config` TypedDict:

```python
from cognee.modules.ontology.get_default_ontology_resolver import get_ontology_resolver_from_env
from cognee.modules.ontology.ontology_config import Config

resolver = get_ontology_resolver_from_env(
    ontology_resolver="rdflib",
    matching_strategy="fuzzy",
    ontology_file_path="examples/ontologies/scientific_ontology.owl"
)

cfg: Config = {"ontology_config": {"ontology_resolver": resolver}}

```

This approach bypasses environment variables entirely, allowing runtime selection of ontology files.

## Entity Matching Strategies

The resolver uses a pluggable matching strategy to map raw entity strings to ontology terms.

### Fuzzy Matching Implementation

By default, `RDFLibOntologyResolver` uses `FuzzyMatchingStrategy` (configured via the `matching_strategy` parameter). When the pipeline encounters an entity like `"Neural Network"`, the resolver’s `find_closest_match` method (lines 59-66 of [`RDFLibOntologyResolver.py`](https://github.com/topoteretes/cognee/blob/main/RDFLibOntologyResolver.py)) compares it against the loaded vocabulary using fuzzy string matching and returns the closest URI match above a similarity threshold.

## Integrating with the Cognify Pipeline

The high-level `cognify()` pipeline accepts your ontology configuration through the `config` parameter, applying validation during graph construction.

### Pipeline Execution

In [`examples/pocs/single_add_datapoints/single_add_datapoints_pipeline.py`](https://github.com/topoteretes/cognee/blob/main/examples/pocs/single_add_datapoints/single_add_datapoints_pipeline.py) (lines 98-113), the pipeline merges the ontology configuration into the processing context. The task `poc_extract_graph_from_data` receives this config and validates extracted entities against the resolver’s vocabulary before adding nodes to the knowledge graph.

```python
import asyncio
import cognee

async def run():
    # Uses .env configuration automatically

    await cognee.cognify(
        datasets=["research_papers"],
        run_in_background=False
    )

asyncio.run(run())

```

### Programmatic Pipeline Example

To bypass `.env` and supply the resolver directly:

```python
import asyncio
from cognee.modules.ontology.get_default_ontology_resolver import get_ontology_resolver_from_env
from cognee.modules.ontology.ontology_config import Config
import cognee

async def run():
    resolver = get_ontology_resolver_from_env(
        ontology_resolver="rdflib",
        matching_strategy="fuzzy",
        ontology_file_path="examples/ontologies/scientific_ontology.owl"
    )
    cfg: Config = {"ontology_config": {"ontology_resolver": resolver}}

    await cognee.cognify(
        datasets=["research_papers"],
        config=cfg,
        run_in_background=False,
    )

asyncio.run(run())

```

## Querying Ontology Subgraphs

Beyond validation, you can extract hierarchical subgraphs directly from the loaded ontology using the `get_subgraph` method. This performs a BFS traversal starting from a named concept, returning its ancestors and object-property relations.

```python
from cognee.modules.ontology.get_default_ontology_resolver import get_ontology_resolver_from_env

resolver = get_ontology_resolver_from_env(
    ontology_resolver="rdflib",
    matching_strategy="fuzzy",
    ontology_file_path="examples/ontologies/scientific_ontology.owl"
)

# Retrieve "NeuralNetwork" class hierarchy

nodes, edges, root = resolver.get_subgraph(
    node_name="NeuralNetwork",
    node_type="classes"
)

print("Found nodes:", [n.uri for n in nodes])
print("Edges:", edges)

```

As implemented in [`RDFLibOntologyResolver.py`](https://github.com/topoteretes/cognee/blob/main/RDFLibOntologyResolver.py) (lines 76-95), this method is useful for visualizing concept hierarchies or validating that specific domain terms exist in your ontology before processing documents.

## Summary

- **Abstract Interface**: All resolvers implement `BaseOntologyResolver`, ensuring consistent lookup, matching, and subgraph extraction APIs.
- **RDFLib Backend**: The `RDFLibOntologyResolver` parses OWL/RDF files and maintains `classes` and `individuals` lookup tables for fast entity resolution.
- **Configuration Flexibility**: Supply ontologies via `.env` variables (`ONTOLOGY_FILE_PATH`) or programmatic `Config` objects passed to `cognify()`.
- **Fuzzy Matching**: The default `FuzzyMatchingStrategy` maps extracted entities to ontology terms even with minor string variations.
- **Subgraph Extraction**: Use `get_subgraph()` to retrieve concept hierarchies directly from the ontology for validation or visualization.

## Frequently Asked Questions

### What file formats does Cognee support for ontologies?

Cognee supports standard OWL and RDF files through the `RDFLibOntologyResolver`. Any format readable by RDFLib—including RDF/XML, Turtle, and N-Triples—can be loaded via the `ONTOLOGY_FILE_PATH` environment variable or passed directly to the resolver constructor.

### Can I use a custom matching strategy instead of fuzzy matching?

Yes. The `BaseOntologyResolver` accepts any class implementing the `MatchingStrategy` interface. You can implement your own strategy (e.g., exact matching, vector similarity) and pass it to `get_ontology_resolver_from_env()` via the `matching_strategy` parameter to override the default fuzzy matcher.

### How does the ontology resolver handle multiple ontology files?

The `ONTOLOGY_FILE_PATH` environment variable accepts comma-separated paths, and the programmatic API accepts a list of file-like objects. The `RDFLibOntologyResolver` merges these into a single graph namespace, allowing entities to be validated against multiple vocabularies simultaneously.

### Where in the pipeline does entity validation actually occur?

Entity validation happens during the graph construction phase in the `poc_extract_graph_from_data` task. This task receives the resolver from the pipeline config (as seen in [`single_add_datapoints_pipeline.py`](https://github.com/topoteretes/cognee/blob/main/single_add_datapoints_pipeline.py)) and calls the resolver’s lookup methods before finalizing node creation in the knowledge graph.