Skip to main content
How to safely evolve the ontology (schema) of an already-populated knowledge graph — adding attributes, renaming labels, dropping types — without drifting away from the data graph. If you’re new to the ontology, start with Graph Schema. This page is about changing an existing ontology. If you don’t have one yet, see Ontology Discovery — Ontology.from_sources drafts one from a corpus and GraphRAG.suggest_schema_extensions proposes additions as new docs arrive.

The Invariant

GraphRAG SDK treats the ontology as a contract: every instance of a declared attribute’s owner entity type is queryable for that attribute. Values the LLM didn’t determine read as null — Cypher treats absent and explicit-null identically under WHERE n.attr IS NULL, so callers get a consistent view regardless of which one underlies a given entity. There is no API that can declare schema your data doesn’t match. This means one thing in practice: when you add an attribute, the SDK runs an LLM backfill across your existing chunks as part of the same call and only commits the schema change once the data is aligned. Adding an attribute is therefore expensive — pay attention to corpus size and use dry_run=True to preview before running for real. The invariant covers attributes only. Declaring a new entity type or relation pattern is cheap (no data implication — “this is allowed” is not “this exists”). For those, there are opt-in discovery tools that re-scan the corpus.

The API at a Glance

15 methods on GraphRAG, grouped by what they touch. All of them are async: call each with await (the listings below show the signatures).

Group 1 — Pure declarations (cheap, no LLM)

Return: Ontology.

Group 2 — Mechanical data migration (Cypher, no LLM)

Return: Ontology. Data migration runs first; the ontology graph is updated second. A crash between the two leaves the data graph ahead, and re-running the same call is idempotent.
rename_relation, drop_relation and drop_relation_pattern act on edges typed with the relation label itself, which is what backfill_relation_pattern() writes. Extracted and table facts are RELATES edges with a rel_type property; these calls leave them unchanged. Every call checks its labels first and raises ValueError for an unknown label, or for a rename onto a label (or attribute) that already exists: merging two types is not a rename.
  • rename_entity() follows through to the table mappings that name the label, as the type of their rows or the target of a Link, so the stored ontology stays valid and the table’s next re-sync finds its rows under the new label.
  • drop_entity() refuses (ValueError) a label a table mapping maps rows to or links to, naming the table. The mapping registers the label again on the next start, so the drop could only be undone. Drop the table first with drop_table(), or rename the label.
  • rename_relation() and drop_relation() refuse (ValueError) a type a relationship table writes, and rename_attribute() and drop_attribute() refuse an attribute a relationship table resolves an endpoint by: its stored mapping would go on using the old name. drop_table() that relationship table first, or redeclare it.
  • Both may run while finalize() deduplicates. A drop records the entities it deletes for the running dedup, and a rename changes the labels a planned merge was read with, so either way the merge is skipped or read again rather than applied to a changed node.

Group 3 — Atomic attribute evolution (LLM, invariant-enforcing)

add_attribute returns an EvolutionResult; drop_attribute returns the Ontology. The ontology graph write is the commit point — data first, schema change last.
Entity owners only. add_attribute, drop_attribute and rename_attribute on a relation owner raise NotImplementedError. add_attribute on an attribute the owner already declares raises ValueError; to change its type, see Type Changes.

Group 4 — Opportunistic discovery (opt-in, not invariant-enforcing)

Return: BackfillResult. Use after add_entity / add_relation_pattern if you want to populate instances from the existing corpus.
These don’t enforce anything. Declaring an entity type or relation pattern just says the schema allows this — zero instances is a valid state.
Provenance: backfill_relation_pattern does NOT write source_chunk_ids on the new edges. GraphStore.upsert_relationships only unions provenance for :RELATES edges; writing it on arbitrary-typed edges would be silently overwritten by future MERGE writes. If you need chunk-level traceability on these backfilled edges, query the underlying co-mentioned chunks via the source/target entities’ MENTIONED_IN edges instead.

Why add_attribute is Atomic

Two reasons. The invariant. If add_attribute were “declare cheap, fill later,” the schema would say “Person has role” while many Person nodes lacked the property. Querying MATCH (p:Person) WHERE p.role = "engineer" would silently miss data. The atomic shape guarantees consistency. Honest commit ordering. The data graph is mutated first. The ontology graph is updated last, as the commit point. If anything fails during backfill, the schema stays at its pre-call state — readers see a consistent (old) view of the world. There is no window in which the schema promises an attribute that isn’t there.

Failure & Retry

If a chunk hard-fails (LLM error / parse error beyond retries), the call raises OntologyEvolutionError and the ontology graph is not updated. The data graph may be partially mutated — some entities have the new property, some don’t. That’s safe because the schema doesn’t yet promise the property exists. To recover: fix the underlying cause (rate limits, malformed chunks, etc.), then call add_attribute again with the same arguments. The call is idempotent:
  • Already-processed chunks carry an extracted_ops marker; the LLM is not re-invoked for them.
  • Already-set entity values are not overwritten.

Type Changes

There is no retype_attribute. To change a type, drop the attribute and add it with the new type — the LLM re-derives values from the chunks.
The new type is what makes the second call re-scan: the chunk markers are keyed on the attribute’s owner, name and type, and drop_attribute leaves them on the chunks. Dropping an attribute and adding it back with the same type therefore scans no chunk and leaves the attribute unset on every entity. This is the only honest move when the source of truth is the corpus. A mechanical toInteger coercion of "around thirty" would either drop the value or fabricate one; the LLM can re-extract 30 from the surrounding text.

Concurrency

Evolution calls are not safe to run concurrently with ingest() or with each other on the same graph. Coordinate at the application level — treat evolution as a maintenance operation: pause new ingestion, run the evolution, resume. The constraint has two sources:
  • add_attribute / drop_attribute — the extractor reads the persisted ontology to decide what to extract from new chunks. While add_attribute is mid-flight, the ontology hasn’t been committed yet, and any concurrent ingest() would produce entities without the new attribute. The invariant would silently break the moment the schema commits.
  • Mechanical Group 2 calls and backfill_* — rename_relation, drop_entity, drop_relation and drop_relation_pattern count first and mutate in a second Cypher statement, and backfill_* lists its chunks before it writes. Concurrent writes can change the graph between those queries.
For multi-process deployments where this matters, gate evolution behind an application-level lock (Redis, etc.) that also blocks ingest(). Every evolution call reloads the stored ontology and hands it to the retrieval strategy (through the strategy’s set_ontology() hook, and its _ontology attribute when it has one), so text-to-Cypher retrieval sees a renamed label or a new attribute on the next question.

Changing the Ontology Outside the Evolution API

The evolution methods are the way to change a label that already exists. The other ways an ontology reaches the graph — GraphRAG(ontology=...), set_ontology() and ingest() — only add:
  • A new label or relation is registered with its properties and patterns.
  • An existing label may be re-declared with the same or fewer properties, which means “use what is stored”.
  • A stored label with no data yet (no node of that label, or no edge of that relation type, in the data graph, including a data graph that does not exist yet) may gain attributes and patterns this way. So the eleven default labels a new graph is seeded with can take a first declared ontology’s attributes. A pattern or attribute added to a stored relation is written the way add_relation_pattern writes one, so every pattern of the relation keeps the same properties.
  • A stored label that holds data cannot: adding a property or a relation pattern to it this way raises OntologyModificationNotAllowedError, whose message says to declare it without the additions and add them with add_attribute or add_relation_pattern. The data check ignores the SDK’s own structure edges (PART_OF, NEXT_CHUNK, MENTIONED_IN). When a declaration adds to a stored label and the data graph cannot be read (a timeout, an unreachable server), registration fails with that error and writes nothing.
  • A different type for a property that is already declared raises OntologyContradictionError.
  • Document and Chunk are reserved for the graph’s own nodes and refused as entity labels.
Both errors are raised before anything is stored.

Tables Extend the Ontology Additively

A table mapping declares types for its columns, and those types reach the ontology, which is how text-to-Cypher knows that age is an INTEGER. A table is the one source allowed to extend an existing label on the ingest path: prose usually creates Organization first with only a name and a description, and a CSV then contributes employee_count. Registration is additive:
  • A label the table introduces is registered whole. A label that already exists is extended through the same primitives the evolution API uses, and its description is kept: the table’s generated description fills a gap but never replaces one you wrote.
  • Each column is stored signed with its table, employees__age rather than age, and reaches the ontology as Attribute(structured=True). The signed properties are left out of the extraction prompt, so a document cannot write under a table’s name. The flag survives a reload, on relation properties too.
  • A table that declares a property already registered with another type raises OntologyContradictionError before anything is written. Change a type deliberately with drop_attribute() then add_attribute().
  • A label a Link points at may have only one key column. Two tables may key Person by different columns, but a link to Person could not tell which one it means, so the declaration that completes that shape is refused with OntologyContradictionError.
  • A redeclared mapping that drops a column takes the column off the nodes as well as out of the ontology, and is reported in FinalizeResult.mapping_changed.
Because the mapping lives in the ontology you pass to GraphRAG(ontology=...), its labels exist before any document is extracted, and the extractor uses the real labels instead of guessing from the built-in list. If a document was extracted first anyway, finalize() lets the declared type beat the guessed one: a Concept the extractor guessed for a name is absorbed by the MitigationPractice a mapping declared for it. This applies only to custom declared labels: a built-in label such as Organization was always on the extractor’s list, so nothing is adopted into it. Two declared labels sharing a name also stay apart (see Storage). drop_table(source) is the evolution counterpart for a table: it removes the table’s rows, the columns it signed, the identity it gave, and its stored mapping. The label stays, since a document or another table may still use it; drop_entity() removes a label nothing else uses.

Relation Patterns and Descriptions

A relation with several (source, target) patterns keeps its first description: when the patterns carry different descriptions, the oldest one is reported, so a description a table derived never replaces the one you declared. A new pattern added with add_relation_pattern copies its properties’ type and description from the oldest sibling pattern, and marks a property structured when any sibling has it so.

Cost Preview (dry_run=True)

add_attribute, backfill_entity, and backfill_relation_pattern accept a dry_run keyword. When True, the scope query runs but the LLM is not invoked and no writes happen. The returned result carries chunks_in_scope — the number of chunks this run would scan.
The count reflects what this run would scan: chunks already marked from a prior partial run are already filtered out, so the preview is accurate for the work that remains, not a hypothetical clean slate.

End-to-End Example

A more comprehensive walkthrough lives in examples/09_ontology_evolution.py.

EvolutionResult Reference

Returned by add_attribute. On a successful (non-dry-run) return, all counters are populated; hard failures raise OntologyEvolutionError instead of returning.

OntologyEvolutionError Reference

Raised by add_attribute when one or more chunks hard-fail. The ontology graph is not updated. The exception subclasses RuntimeError so it propagates through await paths cleanly.

What’s Not in the API (and Why)

Relation-attribute mutation (add_attribute("WORKS_AT", ...) etc.) raises NotImplementedError. The workaround is delete_all() followed by a fresh ingest() with the updated ontology — that’s a heavy hammer, but it’s the only way to keep edge properties aligned without an edge-property migration primitive.