> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Ontologies

> Enrich your knowledge graph with external vocabularies.

## What is an ontology in Cognee?

An **ontology** is an optional RDF/OWL file you can provide to Cognee.
It acts as a **reference vocabulary**, making sure that entity types ("classes") and entity mentions ("individuals") extracted from your data are linked to canonical, well-defined concepts.

## How it works

* You supply an ontology when running [Cognify](https://docs.cognee.ai/core-concepts/main-operations/legacy-operations/cognify.md) in one of three ways (see the [practical example](#additional-details-and-examples) below):
  * Set the `ONTOLOGY_FILE_PATH` environment variable and call `cognee.cognify()` normally.
  * Pass an ontology resolver through the `config` argument.
  * Pass `cognify()`'s `ontology_file_path` argument (a path, or comma-separated paths). `remember()` has no such argument.
* Cognee parses the file with [RDFLib](https://rdflib.dev/) and loads its classes and relationships.
* Once the LLM has extracted a graph from a chunk, its entities and types are checked against the ontology before any graph nodes are built from it:
  * If a match is found, the node is marked `ontology_valid=True`.
  * Parent classes and object-property links from the ontology are attached as extra edges.
* By default grounding only *annotates*: entities the ontology does not recognize are kept verbatim. Set `ONTOLOGY_MODE=strict` (or `ontology_mode` inside `ontology_config`) to have grounding drop them instead — see [Grounding modes](#grounding-modes).
* If no ontology is provided, extraction still works, just without validation or enrichment.

## Grounding modes

`ONTOLOGY_MODE` controls what grounding is allowed to do with entities the ontology does **not** recognize:

| Value | Behavior |
| - | - |
| `annotate` *(default)* | Annotation only. Matched entities are canonicalized and enriched; unmatched entities are kept verbatim with `ontology_valid = False`. Nothing is dropped. |
| `strict` | Grounding also filters. An extracted node is **dropped** unless the ontology matched *either* its `type` against a class *or* its `name` against an individual, and every edge touching a dropped node is dropped with it. |

The default is `annotate`, so a pipeline that never sets the variable behaves exactly as it did before the option existed. Set it per deployment through the environment:

```bash theme={null}
ONTOLOGY_FILE_PATH=/path/to/subset.owl
ONTOLOGY_MODE=strict
```

…or per call inside `ontology_config`, where it overrides the environment value:

```python theme={null}
config: Config = {
    "ontology_config": {
        "ontology_resolver": RDFLibOntologyResolver(ontology_file="subset.owl"),
        "ontology_mode": "strict",
    }
}

await cognee.cognify(datasets=["my_dataset"], config=config)
```

The value is trimmed and lowercased before it is read, so `Strict` and `STRICT` work. An unrecognized value never fails a run: Cognee logs a warning naming the valid values and falls back to `annotate`. Since `config` is forwarded to Cognify, the same `ontology_config` works in [`remember()`](https://docs.cognee.ai/python-api/remember).

> [!NOTE]
>
> Grounding — and therefore the mode — only runs when an ontology resolver exists. Passing `config` replaces environment-based resolver lookup for that call, so a `config` carrying `ontology_mode` but no `ontology_resolver` (and no `ontology_file_path` argument) runs with no ontology at all and the mode has no effect. Pass both keys together, pass `ontology_file_path` alongside, or configure both through the environment.

### What strict mode checks

Strict mode is **entity grounding only** — it is not an OWL validator:

* **Either match is enough.** An entity name the ontology has never heard of still survives if its *type* matches a declared class. This is deliberate: a recognized type is evidence the entity belongs to your domain.
* **Relationship names are never checked** against the ontology's object properties, so no edge is dropped for its own sake — only for having a dropped endpoint.
* **No axioms are evaluated.** Strict mode itself does no domain/range, cardinality, or disjointness checking. By default no reasoner runs either; with [`ONTOLOGY_REASONING=owl_rl`](#reasoning) the OWL 2 RL closure is expanded first, so strict mode matches against inferred classes and individuals too — but it still never rejects an entity for violating an axiom.

Collapsing is unchanged: nodes matched to the same ontology individual are still merged onto a single survivor and their edges rewired, in both modes.

### What strict mode does not prune

Strict mode prunes **only the extracted graph**. Chunks have already been stored and embedded by the time grounding runs, so `CHUNKS`, `CHUNKS_LEXICAL`, and `RAG_COMPLETION` still retrieve chunk text that mentions dropped entities. Only graph-based search types see the pruned view.

### Strict mode over an empty ontology is a hard error

A mistyped `ONTOLOGY_FILE_PATH` produces a resolver whose lookup is empty — the resolver itself only warns — and strict mode over an empty ontology would drop every extracted entity while the run still reported success. Cognee refuses instead, raising `EmptyOntologyInStrictModeError`. When both the mode and the resolver come from the environment, the check runs while the resolver is being configured, before any pipeline work; when either comes from a per-call `ontology_config`, it runs at canonicalization. Custom resolvers that expose no `lookup` dictionary are not checked.

### Reading the drop summary

A strict run that dropped anything logs an aggregate warning per chunk batch — dropped and total nodes, the retained percentage, dropped and total edges, and the number of graphs in that batch — rather than one warning per chunk. A high drop ratio is the signal that the ontology does not cover your corpus's vocabulary; strict mode expects an ontology broad enough for the text you are ingesting, so check that summary on a small run before enabling it over a large corpus.

## Reasoning

`ONTOLOGY_REASONING` controls whether grounding sees only the triples written in your ontology file or also the triples OWL entails from them:

| Value | Behavior |
| - | - |
| `none` *(default)* | Asserted triples only. Grounding reads exactly what the file says. |
| `owl_rl` | After parsing, Cognee expands the ontology's **OWL 2 RL closure** in memory (with the [`owlrl`](https://pypi.org/project/owlrl/) package) before building the class/individual lookup. The inferred triples take part in matching and in the subgraph walk, so `owl:inverseOf`, transitive properties, `rdfs:domain` / `rdfs:range` typing, `owl:equivalentClass`, and `owl:sameAs` are honoured. |

For example, with `owl_rl` an individual that only appears as the subject of a property whose `rdfs:domain` is `CarManufacturer` is inferred to be a `CarManufacturer`, so it enters the individuals lookup; and for a property declared `owl:inverseOf` another, each assertion's inverse is materialised too, so both directions can be attached as edges.

Reasoning is opt-in because the closure is materialised in memory and its cost grows with ontology size. Each run logs the effect, e.g. `OWL-RL reasoning expanded the ontology from 120 to 410 triples`. The closure's bookkeeping triples are pruned afterwards: reflexive `rdfs:subClassOf`, `rdfs:subPropertyOf`, `owl:equivalentClass`, `owl:equivalentProperty`, and `owl:sameAs` statements (`A subClassOf A`), and every triple with `owl:Thing` or `owl:Nothing` as subject or object, so they never become `is_a` self-loops or let a fuzzy match ground a type to `owl:Thing`.

`owl_rl` needs the optional `ontology` extra:

```bash theme={null}
pip install "cognee[ontology]"
```

Without it, constructing an `owl_rl` resolver raises `OntologyReasoningDependencyError` (a `CogneeConfigurationError`) once its ontology file has parsed, naming that install command. It is raised as-is, not wrapped in the generic `OntologyInitializationError` used for files that fail to load.

Set it per deployment through the environment:

```bash theme={null}
ONTOLOGY_FILE_PATH=/path/to/subset.owl
ONTOLOGY_REASONING=owl_rl
```

The value is trimmed and lowercased; an unrecognized value logs a warning naming the valid values and falls back to `none` rather than failing the run.

Reasoning is applied when the resolver is **built**, so where you set it depends on who builds it:

* **Cognee builds it** — from `ONTOLOGY_FILE_PATH`, or from `cognify()`'s `ontology_file_path` argument. A resolver built from `ONTOLOGY_FILE_PATH` always uses `ONTOLOGY_REASONING`, because passing any `config` turns that environment lookup off. The `ontology_file_path` argument takes precedence over `config`: when you pass it, an `ontology_resolver` in `ontology_config` is ignored, and a per-call `ontology_reasoning` key there overrides the environment value:

  ```python theme={null}
  await cognee.cognify(
      datasets=["my_dataset"],
      ontology_file_path="subset.owl",
      config={"ontology_config": {"ontology_reasoning": "owl_rl"}},
  )
  ```

* **You build it** — an `ontology_resolver` instance in `ontology_config` keeps the reasoning it was constructed with, and an `ontology_reasoning` key next to it is ignored. Pass the setting to the constructor instead; when omitted, the constructor reads `ONTOLOGY_REASONING`:

  ```python theme={null}
  config: Config = {
      "ontology_config": {
          "ontology_resolver": RDFLibOntologyResolver(
              ontology_file="subset.owl", ontology_reasoning="owl_rl"
          ),
      }
  }
  ```

As with [`ontology_mode`](#grounding-modes), a `config` holding only `ontology_reasoning` — no `ontology_resolver` and no `ontology_file_path` — runs with no ontology at all. `remember()` has no `ontology_file_path` argument, so there use a pre-built resolver or the environment.

## Query grounding

The ontology is also used when you query memory, not only at Cognify time. With `ONTOLOGY_FILE_PATH` set, graph-completion searches (`GRAPH_COMPLETION` and its COT, context-extension, summary and decomposition variants, and `AGENTIC_COMPLETION`) and hybrid searches (`HYBRID_COMPLETION`, the default `recall()` route, `HYBRID_COMPLETION_DECOMPOSITION`, which grounds the question and each subquery, and `TEMPORAL`) ground the words of the question in the ontology:

* **Lookup.** Runs of query words are looked up by exact key in the ontology's classes, then its individuals, longest run first. The last word is also tried in singular form, so `credit exposures` finds `CreditExposure`. A single stopword such as `will` or `may` is not looked up on its own. There is no fuzzy matching here, so a misspelled word does not ground.
* **Seeds.** Each matched class or individual is pinned as an exact-score seed under the id Cognify wrote it with, so retrieval reaches it even when vector search misses it. Graph completion pins seeds only for a single query without `neighborhood_depth`; batch queries and neighborhood expansion pin nothing. In the hybrid entity lane, pinned concepts come first and count against `entities_top_k`, and a pinned concept that the dataset's graph does not hold is dropped from the lane.
* **Context block.** An `## Ontology grounding` block is added in front of the retrieved context, for example `- "credit exposure" refers to CreditExposure (class); is a RiskMetric`. It is added only when the retrieved context is not empty, so "nothing found" can still be detected.

Grounding makes no LLM or embedding call. The resolver is built as Cognify builds it from the environment, including `ONTOLOGY_REASONING`. Cognee parses it on a dedicated worker thread and parses it again when the file changes. A malformed ontology file raises instead of being skipped. Only `ONTOLOGY_FILE_PATH` is used: ontologies passed per call to `cognify()` and uploaded ontologies referenced by `ontology_key` are not used at query time.

Grounding is on by default whenever `ONTOLOGY_FILE_PATH` is set. Turn it off with:

```bash theme={null}
ONTOLOGY_QUERY_GROUNDING=false
```

Without `ONTOLOGY_FILE_PATH`, or with grounding turned off, search runs as it did before.

## Schema alignment and authoritative sources

Relational ingestion links the technical schema to your ontology. This covers [`migrate_relational_database`](https://docs.cognee.ai/examples/relational-db-migration), in both full and schema-only mode, and the schema graph Cognify builds for DLT database sources. Each table node whose name is the exact key of an ontology class gets a `realizes` edge to that class's `EntityType` node. The class's ontology subgraph (its `is_a` parents and related classes) is written with it, under the same ids Cognify uses, so both paths meet on one node.

Table names are matched the way a question is grounded: the schema or database prefix is stripped, and the last word is also tried in singular form, so `crm.customers` realizes `Customer`. There is no fuzzy matching, so `production` is not a `Product`. Tables the ontology does not know are left alone.

Every `realizes` edge carries two properties: `authoritative` (whether the table is the system of record for the concept) and `owner`. Both come from the authoritative sources, a map from table name to owner in which every listed table is authoritative. A table is listed in one of three ways:

* bare (`customers`), which matches that table name in every source;
* `schema.table` for a non-`public` table of `migrate_relational_database`;
* `database.table` for a table of a DLT database source (the SQLite file's name with its extension, such as `shop.db.orders`, or the server database's name).

Set them for the deployment with `ONTOLOGY_AUTHORITATIVE_SOURCES` as comma-separated `table[=owner]` entries. An entry with no table name raises.

```bash theme={null}
ONTOLOGY_FILE_PATH=/path/to/business.owl
ONTOLOGY_AUTHORITATIVE_SOURCES=crm.customers=sales-ops,billing.invoices=finance,products
```

Or set them per call with `ontology_config["authoritative_sources"]` on `cognify()` / `remember()`, or with the `authoritative_sources` argument of `migrate_relational_database`. A per-call value replaces the environment value, and `{}` means "no authoritative tables". A per-call `ontology_config` without `ontology_resolver` turns the ontology off for that call, so no table is aligned. Pass the resolver with the sources:

```python theme={null}
config: Config = {
    "ontology_config": {
        "ontology_resolver": RDFLibOntologyResolver(ontology_file="business.owl"),
        "authoritative_sources": {"crm.customers": "sales-ops", "products": None},
    }
}
```

In hybrid search, an authoritative edge sorts ahead of the other edges of the same rank, and the edge text gets a suffix such as `(authoritative source, owner: sales-ops)`. So when several tables realize one concept, the LLM sees the system of record first. A grounded class is read with its `realizes` edges only: the tables that realize it, not every entity of its type.

A malformed ontology file makes ingestion raise.

## Why use an ontology

* **Consistency**: standardize how entities and types are represented
* **Enrichment**: bring in inherited relationships from a domain schema
* **Control**: align Cognee's graph with existing enterprise or scientific vocabularies

## Where to get ontologies

Cognee works best with **manually curated, focused ontologies** that fit your dataset. Ontology design itself is outside the scope of Cognee, so if you need to create or model an ontology from scratch, use dedicated ontology tools and references first, then bring the resulting RDF/OWL file into Cognee.

Public resources like **Wikidata** or **DBpedia** define millions of classes and entities, which makes them too big to use directly in Cognee. If you start from a public ontology, always work with a subset, not the full ontology:

* **Select only the pieces you need** (specific classes, properties, or individuals)
* **Save the subset** in a format Cognee can parse with [`rdflib`](https://rdflib.readthedocs.io/)
* **If needed, enrich the subset manually** by adding extra classes or relationships relevant to your domain
* **Keep it small and relevant** so matching stays precise and performance remains fast

> [accordion] Common sources
>
> * **General vocabularies**: schema.org, Dublin Core Terms (DC/Terms), SKOS, PROV-O, FOAF
> * **Knowledge graph backbones**: DBpedia Ontology, Wikidata (Wikibase RDF ontology)
> * **Domain examples**:
>   * Healthcare: SNOMED CT (licensed), ICD, UMLS, MeSH, HL7/FHIR RDF
>   * Finance: FIBO (Financial Industry Business Ontology)
>   * Geo/IoT: GeoSPARQL, SOSA/SSN, GeoNames
>   * Units: QUDT

> [accordion] Why subsetting is essential
>
> Every public ontology is **too broad to ingest wholesale**. Creating a subset is what makes them usable in Cognee:
>
> * Improves matching precision (fewer false matches when mapping LLM output)
> * Keeps performance acceptable (smaller graphs → faster resolution)
> * Lets you curate only the relevant parts of a domain

> [accordion] How subsetting works
>
> Different communities provide different ways to extract subsets (e.g., "slims" in OBO ontologies, WDumper for Wikidata, module extraction in Protégé). The details vary, but the general principle is the same:
>
> 1. Pick the terms (classes or properties) you care about
> 2. Extract those terms plus their immediate context (e.g. parent classes, related properties)
> 3. Save the result in an `rdflib`-readable RDF format

## Supported formats

Any format [RDFLib](https://rdflib.readthedocs.io/) can parse:

* RDF/XML (`.owl`, `.rdf`)
* Turtle (`.ttl`)
* N-Triples, JSON-LD, and others

The [upload endpoint](https://docs.cognee.ai/cognee-cloud/functionality/configuration-and-ontologies.md#ontologies) (`POST /api/v1/ontologies`) accepts RDF/XML, Turtle, N3, JSON-LD, N-Triples, N-Quads and TriG. It takes the format from the filename extension (`.owl`, `.rdf`, `.xml`, `.ttl`, `.n3`, `.jsonld`, `.nt`, `.nq`, `.trig`). For any other extension the upload's Content-Type decides (for example `text/turtle` or `application/ld+json`). A file that matches neither is rejected with `400`. The upload does not parse the file, so content that is not valid RDF is accepted and only fails when cognify, remember or export loads it. The detected format is stored with the upload and tried first whenever the ontology is loaded.

A local file passed through `ONTOLOGY_FILE_PATH` or `RDFLibOntologyResolver(ontology_file=...)` has no such check. A file path is parsed once, in the format rdflib guesses from its extension (Turtle when the extension is unknown), with no retry in other syntaxes. An open file object is tried first in the format its name or Content-Type suggests, and then in each of the other RDF syntaxes.

JSON-LD must carry its `@context` inline. A `@context` or `@import` given as a URL, a relative path or a `file:` path is refused rather than fetched, so the ontology fails to load (and the export endpoint returns `422`). Inline the context, or expand the document, before using it.

An ontology uploaded through the API can be downloaded again as Turtle, RDF/XML, JSON-LD or N-Triples with the [export endpoint](https://docs.cognee.ai/cognee-cloud/functionality/configuration-and-ontologies.md#ontologies). The file is re-serialized, so its formatting can differ from the upload. Uploads are stored in Cognee's file storage, so they follow `DATA_ROOT_DIRECTORY` (S3 included) and file encryption; see the [API page](https://docs.cognee.ai/cognee-cloud/functionality/configuration-and-ontologies.md#ontologies).

## RDF read/write surface

Beyond consuming an ontology as extraction scaffolding, Cognee can preserve external IRIs end-to-end and treat the memory graph as RDF. This is aimed at teams that maintain knowledge natively as RDF and want Cognee as a complementary agentic-memory layer over their RDF knowledge base. The export direction — serializing the memory graph to RDF or querying it with SPARQL — is covered under [Additional details and examples](#additional-details-and-examples).

> [!NOTE]
>
> The RDF surface relies on [`rdflib`](https://rdflib.dev/), which ships with Cognee's ontology support. Everything here is **backward compatible**: `ontology_uri` defaults to `None` and existing text-extraction ingestion is unchanged — nothing is required for existing workflows.

### URI preservation

When an extracted entity or type matches your ontology, Cognee now keeps the matched IRI on the persisted node in [`DataPoint.ontology_uri`](https://docs.cognee.ai/core-concepts/building-blocks/datapoints#core-structure) instead of flattening it to a local label. Grounded `Entity`/`EntityType` nodes carry their stable external IRI; ungrounded nodes keep `ontology_uri = None`. The field never affects node identity.

### Ingesting RDF into datapoints

The `cognee.modules.ontology.rdf_xml.rdf_ingest` module ingests an RDF T-Box + A-Box directly into Cognee datapoints, keeping the external IRIs verbatim rather than canonicalizing entities into a local vocabulary.

```python theme={null}
from cognee.modules.ontology.rdf_xml.rdf_ingest import ingest_rdf

# Accepts a file path, list of paths, file-like object, or a parsed rdflib.Graph.
data_points = await ingest_rdf("knowledge_base.ttl")
```

* **OWL classes** become `EntityType` nodes; **individuals** typed by a known class become `Entity` nodes. `rdf:type` and `rdfs:subClassOf` are kept as `is_a` relationships.
* **Node identity is derived from the IRI** (not the label), so distinct IRIs stay distinct and **re-ingesting the same RDF is idempotent** — this is an open-world model with no fuzzy canonicalization.
* **Object-property assertions** between two ingested individuals become explicit graph edges that preserve the original RDF predicate IRI as `predicate_uri`, so they round-trip back out on export.
* Parsing reuses the ontology resolver, so any RDF syntax RDFLib understands (RDF/XML, Turtle, N-Triples, JSON-LD, …) is supported.

Lower-level helpers are available when you need them: `load_rdf_graph(source)` parses a source into an `rdflib.Graph`, and `build_datapoints_from_rdf(graph)` / `build_graph_from_rdf(graph)` turn a parsed graph into datapoints (and custom edges) without persisting.

> [!NOTE]
>
> **Scope / limits.** RDF ingestion preserves object-property assertions only when both endpoints are ingested individuals. Blank nodes, arbitrary literal/data-property round-trip, and RDF reasoning/entailment (e.g. OWL RL) are out of scope — no inference is applied to the ingested graph. `ONTOLOGY_REASONING` does not change this: `ingest_rdf` always parses with reasoning off and ingests the asserted triples only, since [reasoning](#reasoning) is for grounding.

## Additional details and examples

> [accordion] Practical example
>
> Supply the ontology through the `config` argument or the `ONTOLOGY_FILE_PATH` environment variable. `cognee.cognify()` also takes an `ontology_file_path` argument (a path, or comma-separated paths); `remember()` does not.
>
> > [tab] Python API
> >
> > ```python theme={null}
> > import cognee
> > from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntologyResolver
> > from cognee.modules.ontology.ontology_config import Config
> >
> > config: Config = {
> >     "ontology_config": {
> >         "ontology_resolver": RDFLibOntologyResolver(ontology_file="subset.owl"),  # your curated subset here
> >         # Optional: "strict" drops entities the ontology does not ground.
> >         # Omit to inherit ONTOLOGY_MODE (default "annotate").
> >         "ontology_mode": "annotate",
> >     }
> > }
> >
> > await cognee.cognify(datasets=["my_dataset"], config=config)
> > ```
>
> > [tab] Environment variable
> >
> > ```bash theme={null}
> > ONTOLOGY_FILE_PATH=/path/to/subset.owl
> > # Optional: annotate (default) or strict — see "Grounding modes" above.
> > ONTOLOGY_MODE=annotate
> > # Optional: none (default) or owl_rl — see "Reasoning" above.
> > ONTOLOGY_REASONING=none
> > # Optional: true (default) or false — see "Query grounding" above.
> > ONTOLOGY_QUERY_GROUNDING=true
> > # Optional: table[=owner],… — see "Schema alignment and authoritative sources" above.
> > ONTOLOGY_AUTHORITATIVE_SOURCES=crm.customers=sales-ops
> > ```
> >
> > ```python theme={null}
> > import cognee
> >
> > # With ONTOLOGY_FILE_PATH set, cognify picks up the ontology automatically.
> > await cognee.cognify(datasets=["my_dataset"])
> > ```

> [accordion] Default behavior without an ontology
>
> Cognee does **not** ship with or apply a built-in default ontology. When you don't set `ONTOLOGY_FILE_PATH` (or pass an ontology resolver via `config`), no ontology resolver is constructed at all: the grounding step is skipped entirely and extracted graphs go straight through the ontology-free construction path. There is no reference vocabulary to validate or enrich against, and no per-entity ontology lookups are performed.
>
> In that mode, node labels and relationship names are produced **directly by the LLM** during graph extraction. There is no fixed, predefined list of relationship types — the model infers them from your text. Consistency is *guided* by the extraction prompt rather than *enforced*, so the same concept may occasionally surface under slightly different labels across chunks. The prompt asks the model to:
>
> * Use **basic node types** (e.g. label a person as `Person`, not `Mathematician` or `Scientist` — the profession goes in the node's description).
> * Keep **numbers in descriptions**: counts, amounts, and measurements go in the description of the node or edge they qualify, not in a node of their own.
> * Use **snake\_case relationship names** (e.g. `acted_in`).
> * Apply **coreference resolution** so an entity referred to by different names or pronouns maps to a single, consistent node.
>
> Typical relationship names the model produces are plain, real-world verbs and roles derived from the text, for example:
>
> * People: `married_to`, `parent_of`, `friend_of`, `works_at`, `colleague_of`
> * Ownership and roles: `owns`, `owned_by`, `member_of`, `founder_of`, `employed_by`
> * Things and places: `produces`, `located_in`, `part_of`, `created_by`, `acted_in`
>
> Provide an ontology when you need these labels to be **standardized and validated** against a fixed vocabulary instead of inferred per document.

> [accordion] Using multiple ontology files
>
> Cognee can load several OWL files and merge them into one in-memory graph, which is useful when you split a large ontology into focused modules.
>
> **Environment variable — comma-separated paths:**
>
> ```bash theme={null}
> ONTOLOGY_FILE_PATH=/path/to/domain.owl,/path/to/entities.owl
> ```
>
> **Python API — list of paths:**
>
> ```python theme={null}
> from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntologyResolver
> from cognee.modules.ontology.ontology_config import Config
>
> resolver = RDFLibOntologyResolver(
>     ontology_file=["/path/to/domain.owl", "/path/to/entities.owl"]
> )
>
> config: Config = {"ontology_config": {"ontology_resolver": resolver}}
> await cognee.cognify(config=config)
> ```
>
> Files that cannot be found are skipped with a warning; at least one valid file is required for ontology grounding to take effect. A file that exists but fails to parse raises `OntologyInitializationError` instead of being skipped.
>
> **How the merge works.**
>
> `RDFLibOntologyResolver` parses each file with RDFLib and adds all triples to the same in-memory `rdflib.Graph`. The result is a single unified graph — Cognee does not create disjoint subgraphs, even when the ontologies share no classes or properties. There is no explicit conflict-resolution step: RDFLib performs an additive merge of triples, and any classes or properties that happen to share IRIs across files naturally coexist in the same graph.
>
> **One ontology per `cognify()` run.**
>
> The ontology resolver is configured at the `cognify()` call level (via `ONTOLOGY_FILE_PATH` or the `ontology_config` in the `Config` payload), not per dataset or per document. If you need different vocabularies for different data, run `cognify()` separately for each dataset with its own resolver instance.

> [accordion] Creating or editing ontologies
>
> Cognee does not provide ontology-authoring features. If you need to create, edit, or validate an ontology, use dedicated RDF/OWL tooling such as Protégé or your team's existing ontology workflow, then load the resulting file into Cognee.
>
> When preparing a file for Cognee:
>
> * Keep the ontology focused on the classes, properties, and individuals relevant to your dataset
> * Prefer a curated subset over a large general-purpose ontology
> * Save it in a format RDFLib can parse, such as RDF/XML (`.owl`, `.rdf`) or Turtle (`.ttl`)

> [accordion] How does an ontology relate to a custom graph?
>
> An ontology **extends** the graph Cognee builds — it never replaces it. The LLM extracts a graph from each chunk first, and grounding then runs as a **canonicalize-first pre-pass**: it rewrites the extracted graph *before* any graph nodes are constructed from it, rather than validating nodes one by one as they are built. For every extracted entity and entity type, Cognee looks the name up in the ontology. Then:
>
> * **On a match**, the node is *canonicalized* in place: its `name` and `type` are rewritten to the ontology term, so the id derived from that name makes different surface forms collapse into one node. When several nodes in the same extracted graph resolve to the same ontology individual, only one of them survives and the edges of the collapsed nodes are rewired onto the survivor. The surviving node gets `ontology_valid = True` and the matched IRI in `ontology_uri`.
> * Cognee then walks the matched term's neighbourhood in the OWL file and **adds** those classes and individuals as extra nodes, along with their `is_a` (`rdf:type` / `rdfs:subClassOf`) and object-property edges. An ontology edge is attached only when **both** of its endpoints are part of the matched subgraph; an edge pointing at a term outside it is skipped rather than inventing a node for that endpoint. This is how parent classes and related individuals show up in your graph even when the text never mentioned them.
> * **When the type finds no class**, Cognee also checks the entity's *name*. If the head noun phrase of the name (everything before the first `of`, `to`, `for`, … ) ends with an ontology class, the entity is grounded in that class with an `is_a` edge. For example, `Credit exposure to Acme Corporation` typed `financial metric` becomes an `is_a CreditExposure`. The class must be the head noun, so `customer feedback form` is not a `Customer`. A class whose name contains one of those words, such as `LineOfCredit`, is never found inside an entity name this way. Under [`ONTOLOGY_MODE=strict`](#grounding-modes), a class found this way counts as a class match, so the entity is kept.
> * **On no match**, the node is kept exactly as the LLM produced it, with `ontology_valid = False`. In the default `annotate` mode nothing is rejected or discarded; under [`ONTOLOGY_MODE=strict`](#grounding-modes) a node with neither a class match on its type nor an individual match on its name is dropped instead, together with its edges.
>
> So an OWL file layers a curated skeleton on top of the extracted graph. In the default `annotate` mode it cannot remove nodes — [strict mode](#grounding-modes) is the opt-in that lets it — and attaching one later does not retro-fit data that has already been processed — re-run [Cognify](https://docs.cognee.ai/core-concepts/main-operations/legacy-operations/cognify.md) for that.
>
> The other way to shape the graph is a [custom graph model](https://docs.cognee.ai/guides/custom-graph-model.md). Neither of them is where entities come from: the entities are always read out of **your data** by the LLM. A `graph_model` constrains which shapes that extraction may return, and an ontology renames and extends what it did return — so an ontology is *not* "the graph model", and a graph model is *not* an ontology. Both shape the graph, but they act at different stages and are not alternatives to one another:
>
> | | [Custom graph model](https://docs.cognee.ai/guides/custom-graph-model.md) | Ontology |
> | - | - | - |
> | **What it is** | A Pydantic `DataPoint` schema passed as `graph_model` | An RDF/OWL file passed via `ontology_config` or `ONTOLOGY_FILE_PATH` |
> | **When it acts** | *Before* extraction — it **is** the LLM's structured-output schema | *After* extraction — extracted names are matched against the vocabulary |
> | **What it controls** | Which node types, fields, and relationships the LLM may produce at all | Which of the produced entities and types get canonical names, IRIs, and inherited edges |
> | **How strict** | Hard: the LLM cannot return anything outside the schema | Soft by default (`annotate`): unmatched entities are kept as-is. [`ONTOLOGY_MODE=strict`](#grounding-modes) opts into dropping them |
> | **Reach for it when** | You know the exact *shape* you want (invoices, tickets, people → activities) | You already own a domain vocabulary and want *naming and typing* aligned to it |
>
> **Combining the two.**
>
> Grounding runs only inside the default `KnowledgeGraph` extraction path. If you pass a `graph_model` that is not a `KnowledgeGraph` subclass, Cognee stores your model's output directly and skips grounding, so **the two do not stack within a single `cognify()` / `remember()` call**. A [`custom_prompt`](https://docs.cognee.ai/guides/custom-prompts) is independent of this: it replaces the extraction system prompt and works with either mode. Practical ways to get both worlds:
>
> * **Ontology + [custom prompt](https://docs.cognee.ai/guides/custom-prompts.md).** Keep the default schema and ontology grounding, and use `custom_prompt` to steer the LLM toward your ontology's class names so more entities match. This is the closest thing to "both" in one run.
> * **Two passes over the same data.** Run one `cognify()` with your custom `graph_model` for the strictly-shaped part of the graph, and another with the default schema plus an ontology for the grounded part. Both write into the same graph.
> * **Ingest the vocabulary directly.** If your ontology already contains the individuals you care about, [`ingest_rdf`](#ingesting-rdf-into-datapoints) loads its classes and individuals as datapoints with IRIs preserved, alongside anything extracted from text.

> [accordion] Which OWL constructs grounding actually reads
>
> Grounding uses a deliberately small slice of OWL. RDFLib parses the whole file, but `RDFLibOntologyResolver` only ever queries these triples:
>
> | Construct | How it is used |
> | - | - |
> | `rdf:type owl:Class` | Builds the **classes** lookup — matched against an extracted node's `type`, materialized as an `EntityType` |
> | `rdf:type <SomeClass>` | Builds the **individuals** lookup (only for classes already in the lookup) — matched against an extracted node's `name`, materialized as an `Entity`; also re-emitted as an `is_a` edge |
> | `rdfs:subClassOf` | Followed upward from the matched term and emitted as `is_a` edges, so parent classes come along |
> | `rdf:type owl:ObjectProperty` | Any assertion whose predicate is a declared object property becomes an edge named after the predicate's local name — but only between two terms inside the matched subgraph |
>
> Everything else is ignored:
>
> * **`owl:DatatypeProperty` is never queried.** Literal-valued attributes in the OWL file are not copied onto graph nodes; an attached ontology node is created with only its `name`, a `description` mirroring it, `ontology_valid`, and `ontology_uri` — no attribute from the OWL file is copied over. Node properties come from extraction or from your [custom graph model](https://docs.cognee.ai/guides/custom-graph-model.md)'s fields, never from the ontology.
> * **No axioms are enforced.** By default (`ONTOLOGY_REASONING=none`) `rdfs:domain` / `rdfs:range`, `owl:equivalentClass`, `owl:sameAs`, `owl:Restriction`, and cardinality all land in the in-memory graph but are never consulted — no reasoner runs. With [`ONTOLOGY_REASONING=owl_rl`](#reasoning) they are not queried directly either, but the triples they entail (inferred `rdf:type`, `rdfs:subClassOf`, and property assertions) are added before the lookup is built, so they shape what the rows above find. Nothing is ever rejected for violating an axiom.
> * **`rdfs:label` is not used for matching.** Grounding keys on the **IRI local name** (the fragment after `#`, or the last path segment), lowercased with spaces replaced by underscores. A term with a readable label but an opaque IRI (e.g. `…#C0004096`) will never match text, so give your terms readable IRIs. ([`ingest_rdf`](#ingesting-rdf-into-datapoints) does read `rdfs:label`; grounding does not.)
>
> A practical consequence of the lookup rules: a class must be declared `rdf:type owl:Class` to be findable at all. A class that only ever appears as the object of an `rdfs:subClassOf`, or an individual declared only as `owl:NamedIndividual` without a type from a declared class, never enters the lookup. The resolver still traverses such terms when walking a matched term's neighbourhood, but they are dropped when the subgraph is materialized: only declared classes and their typed individuals become nodes, and any edge touching an undeclared term is discarded with it. So declare every term you want in the graph as an `owl:Class`, or type it with one.

> [accordion] What ontology\_valid actually means
>
> `ontology_valid` is a boolean marker on every [`DataPoint`](https://docs.cognee.ai/core-concepts/building-blocks/datapoints#core-structure), defaulting to `False`. It records **whether grounding found a match** — nothing more:
>
> * **It is not a gate in the default `annotate` mode.** Nodes with `ontology_valid = False` are stored, embedded, and returned by search exactly like grounded ones. [`ONTOLOGY_MODE=strict`](#grounding-modes) is the opt-in that does reject them: entities with neither a class match on their type nor an individual match on their name are dropped before any node is built. Note that strict mode does not make the flag redundant — an entity retained only because its *type* matched still carries `ontology_valid = False`. In either mode no node is auto-created in your `.owl` file — Cognee never writes back to the ontology.
> * **It is not schema validation.** Matching is purely name-based: names are lowercased with spaces replaced by underscores, then compared using `difflib` fuzzy matching at a `0.8` similarity cutoff (`FuzzyMatchingStrategy` — the only strategy Cognee ships, `MATCHING_STRATEGY=fuzzy`). A fuzzy match on a multi-word name is rejected unless every content word (stopwords aside, plural stripped) appears in the matched term, so `enterprise customer acme` no longer collapses into `EnterpriseCustomer`. An entity whose type matches no class can still be grounded through its name (see *How does an ontology relate to a custom graph?* above). Only `owl:Class` terms (as *classes*) and individuals typed by one of those classes (as *individuals*) are candidates. OWL `rdfs:domain` / `rdfs:range` axioms are **not** enforced, and by default no reasoning or entailment is applied — with [`ONTOLOGY_REASONING=owl_rl`](#reasoning), names are matched against the OWL 2 RL closure instead of the asserted triples alone.
> * **It is a node-level flag.** Only `Entity` and `EntityType` nodes carry `ontology_valid`. The edges Cognify writes do not have the property at all, whether they were copied in from the ontology subgraph or extracted by the LLM: relationship names are never matched against the ontology's object properties, so there is no edge-level grounding verdict to record. Filter on the endpoints, not the edge. The exception is the `realizes` edges that [schema alignment](#schema-alignment-and-authoritative-sources) writes from a table to an ontology class, which carry `ontology_valid = True`.
> * **What it is good for.** It is provenance you can filter on: [`visualize_graph`](https://docs.cognee.ai/guides/graph-visualization) colors grounded nodes differently, and you can select on the property in your own graph queries.

> [accordion] Exporting the memory graph to RDF
>
> The `cognee.modules.graph.rdf` module builds an RDF view over the live memory graph so you can serialize it or query it with SPARQL, decoupled from the underlying graph engine's query language.
>
> ```python theme={null}
> from cognee.modules.graph.rdf import (
>     serialize_memory_graph,
>     query_memory_graph_sparql,
>     export_memory_graph_to_rdf,   # returns an rdflib.Graph
>     graph_data_to_rdf,            # pure builder over (nodes, edges) tuples
> )
>
> # Serialize the whole memory graph to RDF (Turtle by default).
> turtle = await serialize_memory_graph(rdf_format="turtle")
>
> # Or run SPARQL directly over an RDF view of the graph.
> rows = await query_memory_graph_sparql(
>     "SELECT ?s WHERE { ?s a <http://example.org/mm#CNCMachine> }"
> )
> ```
>
> How nodes and edges map to RDF:
>
> * **Grounded nodes** are emitted under their preserved `ontology_uri`. **Ungrounded nodes** get a minted IRI under `DEFAULT_BASE_IRI` (`https://cognee.ai/graph/…`) so the RDF stays well-formed and nothing is dropped.
>
> * A node's `name` becomes an `rdfs:label`.
>
> * The `is_a` relationship resolves to `rdf:type` for an individual→class link and to `rdfs:subClassOf` for a class→class link. Other relationships become predicate IRIs — a minted `…/prop/<name>` IRI, or, for RDF-ingested edges that carry a `predicate_uri`, that original RDF predicate IRI.
>
> > [!NOTE]
> >
> > `export_memory_graph_to_rdf` / `serialize_memory_graph` / `query_memory_graph_sparql` materialize the whole graph into an in-memory `rdflib` store on each call. This is convenient for querying and export but costs memory proportional to graph size — keep that in mind for very large graphs.
>
> To query one dataset's graph with access control applied, use [`cognee.datasets.sparql()`](https://docs.cognee.ai/python-api/datasets#datasets-sparql) or the [`POST /api/v1/datasets/{dataset_id}/sparql`](https://docs.cognee.ai/cognee-cloud/functionality/dataset-management#query-the-graph-with-sparql) endpoint. They build the same RDF view, scoped to that dataset, and check that you can read it. They only run read-only forms (`SELECT`, `ASK`, `CONSTRUCT`, `DESCRIBE`), refuse SPARQL Update, and refuse `SERVICE`, `FROM` and `FROM NAMED`, which would read other graphs or endpoints.
>
> This per-dataset path also bounds the materialization cost. It refuses graphs with more nodes than `SPARQL_MAX_GRAPH_NODES` (default `200000`) before loading them, and stops waiting for a query after `SPARQL_QUERY_TIMEOUT_SECONDS` (default `30`). These limits do not apply to `query_memory_graph_sparql` or the export functions above. `query_memory_graph_sparql` does refuse the same queries, though: SPARQL Update, `SERVICE`, `FROM` and `FROM NAMED` raise the same `Sparql*Error` types before the graph is read. For graphs over the ceiling, serialize with `serialize_memory_graph` and query the result in a triple store.

For more detailed examples of working with ontologies in Cognee, check out the demo scripts in the repository:

* [Basic ontology demo](https://github.com/topoteretes/cognee/tree/main/examples/guides) - Shows fundamental ontology integration
* [Advanced ontology demo](https://github.com/topoteretes/cognee/tree/dev/examples/advanced_guides/ontology_reference_vocabulary) - Demonstrates more complex ontology workflows


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.