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 asnull — 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 onGraphRAG, 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 aLink, 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 withdrop_table(), or rename the label.rename_relation()anddrop_relation()refuse (ValueError) a type a relationship table writes, andrename_attribute()anddrop_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.
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.
Provenance:backfill_relation_patterndoes NOT writesource_chunk_idson the new edges.GraphStore.upsert_relationshipsonly unions provenance for:RELATESedges; 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_INedges 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 raisesOntologyEvolutionError 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_opsmarker; the LLM is not re-invoked for them. - Already-set entity values are not overwritten.
Type Changes
There is noretype_attribute. To change a type, drop the attribute and add it with the new type — the LLM re-derives values from the chunks.
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 withingest() 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. Whileadd_attributeis mid-flight, the ontology hasn’t been committed yet, and any concurrentingest()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_relationanddrop_relation_patterncount first and mutate in a second Cypher statement, andbackfill_*lists its chunks before it writes. Concurrent writes can change the graph between those queries.
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_patternwrites 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 withadd_attributeoradd_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. DocumentandChunkare reserved for the graph’s own nodes and refused as entity labels.
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 thatage 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__agerather thanage, and reaches the ontology asAttribute(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
OntologyContradictionErrorbefore anything is written. Change a type deliberately withdrop_attribute()thenadd_attribute(). - A label a
Linkpoints at may have only one key column. Two tables may keyPersonby different columns, but a link toPersoncould not tell which one it means, so the declaration that completes that shape is refused withOntologyContradictionError. - 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.
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.
End-to-End Example
examples/09_ontology_evolution.py.
EvolutionResult Reference
Returned byadd_attribute. On a successful (non-dry-run) return, all counters are populated; hard failures raise OntologyEvolutionError instead of returning.
OntologyEvolutionError Reference
Raised byadd_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.