fluree¶
Fluree: a graph database with time travel, history, and fine-grained policy.
Open a database with connect(), create or open a ledger, then write
JSON-LD or Turtle and query it with SPARQL or JSON-LD:
import fluree
with fluree.connect(":memory:") as conn:
people = conn.create("people")
people.insert({
"@context": {"ex": "http://example.org/"},
"@id": "ex:alice", "ex:name": "Alice", "ex:age": 42,
})
for name, age in people.query(
"PREFIX ex: <http://example.org/> "
"SELECT ?name ?age WHERE { ?s ex:name ?name ; ex:age ?age }"
):
print(name, age)
Submodules¶
Package Contents¶
- class fluree.Connection(native: Connection)¶
A connection to a Fluree database. Create one with
connect().- close() None¶
Close the connection. Closing the last open connection to a directory in this process flushes pending writes and releases the directory, so another process can open it.
Afterwards the connection, and every ledger, snapshot, transaction and stream opened through it, raises
InvalidRequestError; an open transaction can still be rolled back. Closing again does nothing.
- create(ledger: str, *, source: str | os.PathLike[str] | None = None) Ledger¶
Create a ledger, optionally bulk-loading RDF files into it.
sourceis a file or a directory of Turtle, TriG, N-Triples, N-Quads, or JSON-LD files.
- ledger(ledger: str) Ledger¶
An existing ledger. Raises
NotFoundErrorif there is none.
- query(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Any¶
Run a query whose
FROMnames the ledgers to read.SPARQL
FROM <ledger>(andFROM NAMED) or a JSON-LD"from"picks the ledgers, so one query can span several; a ledger address can carry a time (<people@t:5>), and SPARQLFROM ... TO ...reads a range of history. Results, parameters,max_fuelandtimeoutare as forSnapshot.query(). Cypher has noFROM; run it on a ledger.
- select(query: str, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: SelectLanguage | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Result¶
A SPARQL
SELECTwhoseFROMnames the ledgers, as forquery(), returning itsResult; seeSnapshot.select().
- profile(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) QueryProfile¶
Run
query()and report the fuel and time it took.
- map_iceberg(name: str, mapping: str | os.PathLike[str], *, table_location: str | None = None, catalog_uri: str | None = None, glue: Glue | None = None, s3_tables: S3Tables | None = None, table: str | None = None, warehouse: str | None = None, auth: Auth | None = None, vended_credentials: bool | None = None, s3_region: str | None = None, s3_endpoint: str | None = None, s3_path_style: bool = False, order_by: str | None = None, branch: str | None = None, model: str | None = None, default_allow: bool | None = None) GraphSource¶
Register Iceberg tables as graph source
name, mapped to RDF bymapping(R2RML, as Turtle text or a path to a Turtle file).Give exactly one place the tables are found. Read one table directly from
table_location— ans3://prefix, or a localfile://path (local paths must lie under a directory named in theFLUREE_ICEBERG_LOCAL_ROOTSenvironment variable, set before the process first reads a table). Or find them through a catalog, where the mapping’s table names (ortable) name the tables: a REST catalog atcatalog_uri, withwarehouseandauth(BearerorOAuth2); an AWS Glue Data Catalog (Glue); or an AWS S3 Tables table bucket (S3Tables). A REST catalog’s vended credentials are used unlessvended_credentialsis false; otherwise, and always for Glue and S3 Tables, S3 access uses the usual AWS environment and thes3_*settings.warehouse,authand asking for vended credentials apply to a REST catalog only, and are refused otherwise.order_bynames the column that orders a key’s rows, latest winning, forGraphSource.materialize().modelnames a ledger whose policies and class hierarchy govern the source.
- map_delta(name: str, mapping: str | os.PathLike[str], *, root: str | None = None, tables: collections.abc.Mapping[str, str] | None = None, unity: Unity | None = None, s3_region: str | None = None, s3_endpoint: str | None = None, s3_path_style: bool = False, azure: AzureServicePrincipal | None = None, branch: str | None = None, model: str | None = None, default_allow: bool | None = None) GraphSource¶
Register Delta Lake tables as graph source
name, mapped to RDF bymapping(R2RML, as Turtle text or a path to a Turtle file).Each mapped
rr:tableNameis found beneathroot(a.bat<root>/a/b), at its location intables, or through aUnitycatalog. Storage credentials come from the usual AWS or Azure environment, thes3_*settings, orazure; local paths must lie under a directory named inFLUREE_ICEBERG_LOCAL_ROOTS.modelanddefault_alloware as formap_iceberg().
- map_sql(name: str, endpoint: str, mapping: str | os.PathLike[str], *, dialect: SqlDialect = 'trino', protocol: Literal['trino', 'presto'] = 'trino', catalog: str | None = None, schema: str | None = None, user: str | None = None, auth: Auth | None = None, session: collections.abc.Mapping[str, str] | None = None, allow_duplicate_subjects: bool = False, branch: str | None = None, model: str | None = None, default_allow: bool | None = None) GraphSource¶
Register tables behind a SQL engine that speaks the Trino HTTP protocol (Trino, Presto, or a bridge to another database) as graph source
name, mapped to RDF bymapping. Queries are pushed down toendpointas SQL indialect.A mapped table whose subject key is not unique is reported with a warning and refused at query time, unless
allow_duplicate_subjects.modelanddefault_alloware as formap_iceberg().
- graph_sources() list[GraphSource]¶
Every graph source, by id.
- graph_source(name: str) GraphSource¶
Graph source
name("name"or"name:branch"). RaisesNotFoundErrorif there is none.
- restore(path: str | os.PathLike[str], ledger: str) Ledger¶
Create
ledgerfrom a.flpackarchive (seeLedger.archive()).
- class fluree.Ledger(connection: Connection, ledger_id: str, policy: dict[str, Any] | None = None)¶
A ledger: write to it, and query its latest state or any past one.
- with_policy(*, identity: str | None = None, policy_class: str | list[str] | None = None, policy: dict[str, Any] | list[Any] | None = None, values: dict[str, Any] | None = None, default_allow: bool | None = None) Ledger¶
This ledger, governed: every read and write through the returned handle is subject to policy.
identity: the IRI (often a DID) to evaluate policy as; the policies attached to it in the ledger apply.policy_class: apply the ledger’s policies of these classes.policy: inline JSON-LD policy documents to apply.values: bindings for variables the policies reference, e.g.{"?$dept": "eng"}.default_allow: whether data no policy covers is visible and writable.Nonedefers to the ledger’s configured default, which is to deny.
Reads filter out what policy does not allow; a write that policy does not allow raises
PermissionDeniedError. So does what policy cannot filter: the commit log,info()andgraphs(), and maintenance, branch and export operations.
- insert(data: Data, *, format: Format | None = None, message: str | None = None) Commit¶
Add data: JSON-LD (a dict, list, or JSON text), Turtle, or TriG.
A path is read as a file, its format taken from the extension unless
formatis given.messageis recorded with the commit, andlog()shows it. Data with nothing to add, such as[], is refused.
- upsert(data: Data, *, format: Format | None = None, message: str | None = None) Commit¶
Add data, replacing existing values of the properties it sets.
- insert_rows(rows: Any, *, id: str | None = None, type: str | list[str] | None = None, vocab: str | None = None, columns: collections.abc.Mapping[str, str | None] | None = None, refs: collections.abc.Mapping[str, str] | None = None, message: str | None = None) Commit¶
Add one node per row of
rows: a pandas or polars DataFrame, or an iterable of dicts. Each column becomes a property of its row’s node; a missing value (None,NaN,NaT) adds nothing.id: the node’s IRI, as a template over the row’s columns —"ex:person/{id}"— whose values are percent-escaped. Without one each row is a new blank node.type: the class (or classes) every node gets.vocab: an IRI prefix for the column names; otherwise they are read against the ledger’s default context, like JSON-LD keys.columns: rename a column’s property (full or compact IRI), or drop the column withNone.refs: properties whose value is a reference to another node, each an IRI template —{"manager": "ex:person/{manager_id}"}.
Values convert as in
insert(), keeping the DataFrame’s types: a pandas integer column with a gap is a float column, unless it has the nullableInt64dtype. All rows commit together.
- upsert_rows(rows: Any, *, id: str | None = None, type: str | list[str] | None = None, vocab: str | None = None, columns: collections.abc.Mapping[str, str | None] | None = None, refs: collections.abc.Mapping[str, str] | None = None, message: str | None = None) Commit¶
insert_rows(), replacing existing values of the properties the rows set — to load a table again after it changed.
- update(transaction: str | dict[str, Any] | os.PathLike[str], parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, message: str | None = None, **kwparameters: Any) Commit¶
Apply a SPARQL UPDATE, a Cypher write, or a JSON-LD
where/delete/insert.The language is told from the text (
languageoverrides it); a path is read as a file,.rq/.ruas SPARQL and.cypher/.cyp/.cqlas Cypher. A Cypher write may be a;script, committed all or nothing — and mixes with the other languages inside atransaction(); its$nameparameters come fromparametersand keyword arguments, and the records aRETURNproduces are the commit’sresult.parametersand keyword arguments bind values by name: Cypher$name, and in SPARQL the variable?name(or$name) wherever it appears, as if the value were written in its place; seeSnapshot.query().
- sync(data: Data, *, graph: str | None = None, format: Format | None = None, allow_empty: bool = False, dry_run: bool = False, message: str | None = None) Commit¶
Make a graph hold exactly
data, committing only the difference: facts missing fromdataare retracted, new ones asserted, and unchanged ones left alone. History keeps every earlier state.graphis a named graph’s IRI; by default the default graph is synced.datais as forinsert(), and Turtle, N-Triples or TriG text.Empty
datawould clear the graph, so it is refused unlessallow_emptyis set. Withdry_runnothing is committed and the returnedCommit(idNone) counts what would change. Whendataalready matches, no commit is written either.
- transact(fn: collections.abc.Callable[..., _T], /, *args: Any, **kwargs: Any) _T¶
Run
fn(txn, *args, **kwargs)in aTransactionand commit it, runningfnagain in a fresh transaction if another commit lands first. Returns whatfnreturns.The way to read and then write safely: values
fnreads fromtxnare re-read on every attempt, so what it writes never rests on data another writer has since changed.fnmay committxnitself (to pass amessage); otherwise it is committed whenfnreturns. An exception fromfnrolls the transaction back and propagates.
- transaction(*, message: str | None = None) Transaction¶
Open a
Transaction: several writes, each seeing the ones before it, committed together as one commit, withmessage.Use it as a context manager to commit on a clean exit and roll back on an exception:
with ledger.transaction(message="onboard bob") as txn: txn.insert(...) txn.update(...) txn.committed # the Commit
- query(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Any¶
Query the latest state. See
Snapshot.query().
- select(query: str, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: SelectLanguage | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Result¶
Run a
SELECTon the latest state; seeSnapshot.select().
- profile(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) QueryProfile¶
Run
query()and report the fuel and time it took.
- stream(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, max_fuel: float | None = None, timeout: float | None = None, batch_size: int = 1000, **kwparameters: Any) RowStream¶
Run a SELECT and read its rows as they are produced; see
RowStream.max_fuelandtimeoutcover the whole stream.
- explain(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, **kwparameters: Any) dict[str, Any]¶
The plan the engine would run
querywith, without running it.
- at(t: int | None = None, *, time: datetime.datetime | str | None = None, commit: str | None = None) Snapshot¶
The ledger as it was at transaction
t, a wall-clocktime, or acommit. Give exactly one.commitis a full commit id (Commit.id), or its hexCommit.digestor a unique prefix of it (Commit.short_id).
- history(subject: str, predicate: str | None = None, *, from_t: int = 1, to_t: int | None = None) list[Change]¶
Every change to
subjectbetween transactionsfrom_tandto_t(default: the latest), oldest first; within one transaction, retractions come before assertions.subjectandpredicateare full IRIs. Givepredicateto follow one property.
- log(limit: int | None = None) list[Commit]¶
The ledger’s commits, newest first; at most
limitof them.
- changes(commit: CommitRef) list[Change]¶
The facts one commit asserted and retracted.
commitis itst, its id, a prefix of its hex digest (Commit.short_id), or aCommit. Underwith_policy(), facts the policy hides are left out.
- branch(name: str) Ledger¶
Create branch
namefrom this ledger’s latest state and return it. Branch from a past state withledger.at(...).branch(name).The new branch shares this one’s history up to that point; from then on each changes independently, until
merge()brings one’s commits into the other.
- merge(source: str | Ledger, *, strategy: MergeStrategy = 'take-both') MergeResult¶
Bring the commits of branch
source(a name like"dev", or itsLedger) into this branch.If this branch has no commits of its own since
sourcewas created from it, it moves forward tosource’s latest commit. Otherwise one merge commit appliessource’s changes, andstrategysettles properties both branches changed:"take-both": keep both values."abort": change nothing and raiseConflictError."take-source":source’s value wins."take-branch": this branch’s value wins.
Preview a merge with
merge_preview().
- merge_preview(source: str | Ledger, *, strategy: MergeStrategy = 'take-both', details: bool = False, changes: bool = False, changes_after: str | None = None, validate: bool = True, conflicts: bool = True, max_commits: int | None = 500, max_conflicts: int | None = 200, max_changes: int | None = 500) MergePreview¶
What
merge()ofsourcewould do, without doing it.strategy: the one to judgemergeableby.details: include what each side wrote to each conflict.changes: include the net facts the merge would bring in, at mostmax_changesof them per call; pass the result’schanges_afterback to read the next page.validate=Falseskips checking the merged state against the ledger’s SHACL shapes.conflicts=Falseskips finding conflicts, the costly part on branches that have drifted far apart.max_commitsandmax_conflictscap the lists returned, not the work;Nonelifts a cap.
- rebase(*, strategy: RebaseStrategy = 'take-both') RebaseResult¶
Replay this branch’s own commits on top of the latest commit of the branch it was created from, as if it had been created from there.
strategysettles properties both branches changed:"take-both"keeps both values,"abort"changes nothing and raisesConflictError,"take-source"lets the source branch’s value win,"take-branch"lets this branch’s win, and"skip"drops each of this branch’s commits that conflicts.
- revert(commits: CommitRef | list[CommitRef], *, strategy: RevertStrategy = 'abort') RevertResult¶
Undo one commit or several, in one new commit.
A commit is named by its
t, its id, a prefix of its hex digest, or aCommit.strategysettles properties that later commits changed again:"abort"changes nothing and raisesConflictError,"take-source"undoes them anyway, and"take-branch"keeps the later values. Merge commits cannot be reverted.Preview a revert with
revert_preview().
- revert_preview(commits: CommitRef | list[CommitRef], *, strategy: RevertStrategy = 'abort', validate: bool = True, conflicts: bool = True, max_commits: int | None = 500, max_conflicts: int | None = 200) RevertPreview¶
What
revert()would do, without doing it.strategyis the one to judgerevertableby; the other options are as formerge_preview().
- validate(shapes: Data | None = None, *, shapes_graph: str | None = None, graph: str | None = None, include_attached: bool = False, format: Format | None = None, max_fuel: float | None = None, timeout: float | None = None) ValidationReport¶
Check the data against SHACL shapes, without changing anything.
By default the shapes are the ledger’s own — the ones its writes are checked against. Give
shapes(JSON-LD, Turtle, or a path, as forinsert()) to check against other shapes, orshapes_graph, the IRI of a named graph that holds them;include_attachedadds the ledger’s own shapes to either.graphvalidates a named graph rather than the default graph.max_fuelandtimeoutbound the work, as forquery().
- index_status() IndexStatus¶
How far indexing has caught up with the ledger’s commits.
- index(*, timeout: float | None = None) int¶
Index everything committed so far, waiting up to
timeoutseconds; returns the indexedt. Queries do not need this — they read unindexed commits too — but it makes them faster sooner. Needs a connection with background indexing.
- verify(*, max_commits: int | None = None) VerifyReport¶
Check that every commit, back to the first (or the last
max_commits), and the index root are present and readable.
- sweep(*, dry_run: bool = False) SweepResult¶
Delete index files that no index of any branch of this ledger references any more — left behind as indexing replaces old index files.
dry_runcounts them without deleting.
- export(path: str | os.PathLike[str] | None = None, *, format: ExportFormat | None = None, graph: str | None = None, all_graphs: bool = False, context: dict[str, Any] | None = None) str | None¶
Export the ledger’s current data as RDF.
Writes to
pathand returnsNone, or returns the text when no path is given.formatis"turtle","trig","ntriples","nquads", or"jsonld"; by default it follows the path’s extension, else Turtle. The default graph is exported unlessgraphnames one orall_graphsasks for every named graph too (use TriG or N-Quads for that).contextsupplies prefixes for Turtle and JSON-LD. Export the past withledger.at(...).export(...).
- archive(path: str | os.PathLike[str], *, include_indexes: bool = True) None¶
Write the whole ledger, every commit, to a
.flpackarchive thatConnection.restore()loads back. Without indexes the archive is smaller but the restored ledger must reindex before it is fast.
- property context: dict[str, Any] | None¶
The ledger’s default JSON-LD context, or
None.Queries that omit
@context(JSON-LD) orPREFIX(SPARQL) resolve their prefixes against it. Replace it withset_context().
- set_context(context: dict[str, Any]) None¶
Replace the ledger’s default JSON-LD context: a
{prefix: IRI}map.
- graphs() list[IRI]¶
The IRIs of the ledger’s named graphs, in the order they were first written to. The default graph and Fluree’s own graphs (commit metadata, configuration) are left out.
A graph is created by writing to it — TriG, SPARQL
GRAPH, or a JSON-LD node’s"@graph"— and queried with SPARQLGRAPHor JSON-LD["graph", iri, pattern].
- drop_graph(graph: str) Commit¶
Retract everything in named graph
graph(its full IRI) in one commit. History keeps it, and the graph can be written to again. The default graph and Fluree’s own graphs cannot be dropped.
- set_full_text(properties: collections.abc.Iterable[str], *, language: str = 'en', reindex: bool = True) None¶
Make the plain-string values of
propertiessearchable withfulltext(), analyzed inlanguage(a BCP-47 tag; values tagged with their own language use it instead).propertiesare IRIs, full or compact against the ledger’s default context; they replace the ones configured before, and an empty list turns the configuration off. The data itself is not changed.reindexrebuilds the index so values already in the ledger are searchable. From then on, a property is searchable as values commit once an index build has seen values of it: a property configured before the ledger holds any of its values is searchable after the next index build (background indexing, orreindex()). Passreindex=Falseto defer the rebuild, for instance before a bulk load, and callreindex()when ready.
- class fluree.QueryProfile¶
A query’s result with what it cost:
fuel(the engine’s unit of work, the unitmax_fuellimits) and wall-clocktime.- result: Any¶
- time: datetime.timedelta | None¶
- class fluree.Snapshot(native: Snapshot, ledger: Ledger)¶
A ledger frozen at one point in time.
Get one from
Ledger.snapshot()orLedger.at().- export(path: str | os.PathLike[str] | None = None, *, format: ExportFormat | None = None, graph: str | None = None, all_graphs: bool = False, context: dict[str, Any] | None = None) str | None¶
Export the data as of this snapshot; see
Ledger.export().
- branch(name: str) Ledger¶
Create branch
namefrom this past state; seeLedger.branch().
- query(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Any¶
Run a SPARQL, Cypher, or JSON-LD query.
The language is told from the query — a dict or JSON text is JSON-LD, text that opens like SPARQL (
PREFIX,SELECT, …) is SPARQL, and text that opens like Cypher (MATCH,UNWIND, …) is Cypher — or set withlanguage.SPARQL
SELECTand every Cypher query return aResult; Cypher nodes, relationships and paths come back asNode,RelationshipandPath.SPARQL
ASKreturns abool;CONSTRUCT/DESCRIBEthe constructed graph as a JSON-LD document.A JSON-LD query returns its JSON result as Python objects.
parametersand keyword arguments bind values by name. In Cypher they are the$nameparameters. In SPARQL each names a variable —?nameor$name, the same variable — and the value stands in for it wherever it appears, as if written there:query("SELECT ?s WHERE { ?s ex:name $name }", name="Alice"). A value is anIRI,BlankNode,LangStringorLiteral, or a Pythonstr,int,float,bool,Decimal,datetime,dateortime; aNodestands for itselement_id. A SPARQL parameter the query never mentions is an error, since its misspelt variable would otherwise match anything; a JSON-LD query takes no parameters.A Cypher write is refused here; run it with
Ledger.update().max_fuelcaps the work the query may do (seeprofile()for what a query costs); past it the query stops withResourceLimitError.timeoutis in seconds; past it the query is cancelled withQueryTimeoutError.
- select(query: str, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: SelectLanguage | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Result¶
Run a SPARQL
SELECTor a Cypher query and return itsResult—query()for the queries whose result is a table, typed as one. Anything else (ASK,CONSTRUCT, JSON-LD) raisesInvalidRequestErrorwithout running. Parameters,max_fuelandtimeoutare as forquery().
- profile(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) QueryProfile¶
Run
query()and report the fuel and time it took.
- class fluree.Transaction(ledger: Ledger, native: Transaction, message: str | None)¶
Writes staged one at a time and committed together as one commit.
Get one from
Ledger.transaction(). Each write applies over the ones before it — anupdate’sWHEREsees an earlierinsert— and is checked as it is staged, so a write that is invalid or that policy does not allow raises at once and is left out; the transaction carries on without it. Queries on the transaction read the staged state; nothing is visible on the ledger untilcommit().A fact that one write adds and a later one removes (or the reverse) is left out of the commit, so the commit holds only the net change.
The writes stage against the ledger as it was when the transaction began. If another commit lands first:
a transaction that was only written to is staged again on top of it — each update’s
WHEREmatches the new data;a transaction that was also read (
query,explain, or theRETURNrecords of a Cypher write) raisesConflictErroroncommit(), since what was read may have decided what was written. Run it again, or useLedger.transact(), which does.
As a context manager it commits on a clean exit and rolls back on an exception;
committedholds the resultingCommit.- insert_rows(rows: Any, *, id: str | None = None, type: str | list[str] | None = None, vocab: str | None = None, columns: collections.abc.Mapping[str, str | None] | None = None, refs: collections.abc.Mapping[str, str] | None = None) None¶
Stage
Ledger.insert_rows().
- upsert_rows(rows: Any, *, id: str | None = None, type: str | list[str] | None = None, vocab: str | None = None, columns: collections.abc.Mapping[str, str | None] | None = None, refs: collections.abc.Mapping[str, str] | None = None) None¶
Stage
Ledger.upsert_rows().
- update(transaction: str | dict[str, Any] | os.PathLike[str], parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, **kwparameters: Any) Result | None¶
Stage an update — SPARQL UPDATE, a Cypher write, or JSON-LD; see
Ledger.update(). A Cypher write returns the records of itsRETURN(Nonewithout one); receiving them counts as reading the transaction.
- query(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Any¶
Query the staged state; see
Snapshot.query().
- select(query: str, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: SelectLanguage | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Result¶
Run a
SELECTon the staged state; seeSnapshot.select().
- explain(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, **kwparameters: Any) dict[str, Any]¶
The plan
querywould run with over the staged state.
- fluree.connect(path: str | os.PathLike[str] | None = None, *, config: dict[str, Any] | None = None, indexing: bool = True) Connection¶
Open a Fluree database, creating it if needed.
Give a directory
path, or":memory:"for a database that lives only as long as the connection.indexing=Falseturns off background indexing in this process.Connections in one process to the same directory share one engine, so threads may each open their own; they must agree on
indexing. While any of them is open, another process that opens the directory raisesDatabaseInUseError: runfluree serveron it to share it across processes. Aconfigconnection to file storage is not shared: while it is open, opening that storage again raisesDatabaseInUseError, in this process too.For anything else — S3 or split commit/index storage, a DynamoDB nameservice, encryption at rest, values read from environment variables — pass a JSON-LD connection
configinstead of a path; it is the same documentfluree servertakes with--connection-config.The connection is a context manager that closes it on exit:
with fluree.connect("./data") as conn: ledger = conn.create("people")
- class fluree.Node(element_id: IRI | BlankNode, labels: frozenset[str], properties: dict[str, Any])¶
Bases:
collections.abc.Mapping[str,Any]A node: its properties (read like a dict), its
labels— the node’s classes — andelement_id, its identity: the sameIRI(orBlankNode) a SPARQL query returns for it.- element_id¶
- labels¶
- class fluree.Path(nodes: tuple[Node, ...], relationships: tuple[Relationship, ...])¶
A walk through the graph:
nodesand therelationshipsbetween them, in order. Iterating a path yields its relationships.- nodes¶
- relationships¶
- class fluree.Relationship(element_id: IRI | BlankNode | None, type: str, start_node: Node, end_node: Node, properties: dict[str, Any])¶
Bases:
collections.abc.Mapping[str,Any]A relationship: its properties (read like a dict), its
type, and the nodes it runs from and to.element_idis its identity when it has one (every relationship a CypherCREATEmakes does).start_nodeandend_nodecarry their properties and labels when the same result returned those nodes; otherwise only theirelement_id.- element_id¶
- type¶
- start_node¶
- end_node¶
- class fluree.Branch¶
A branch of a ledger. Open it with
conn.ledger(branch.id).sourceis the branch it was created from,Nonefor the ledger’s first branch.tandheadare its latest commit’stand id.
- class fluree.Change¶
One fact asserted or retracted at transaction
t:subject’spredicategained (op == "assert") or lost (op == "retract")value, in the default graph or the namedgraph.tisNonefor the net changes a merge preview reports, which span several commits.- value: Any¶
- class fluree.Commit¶
The outcome of a transaction.
idis the commit’s content id (a CID).digestis its hex hash, the formfluree logshows: like a git SHA, a unique prefix of it (short_id, say) identifies the commit. A prefix ofiddoes not, since every CID starts with the same header characters.idanddigestareNonewhen the transaction changed nothing, in which case no commit was written andtis the ledger’s unchangedt.timeandmessageare filled in for commits read fromLedger.log()and the previews.resultholds the records a Cypher write’sRETURNproduced.- time: datetime.datetime | None = None¶
- class fluree.Conflict¶
A property of a subject that both sides changed.
sourceandtargetare what each side wrote to it, when the preview was asked fordetails; otherwiseNone.
- class fluree.FullText¶
A ledger’s full-text configuration (see
Ledger.set_full_text()): the properties whose plain-string valuesfulltext()scores, and the language untagged values are analyzed in.
- class fluree.IndexStatus¶
Where indexing of a ledger stands. Commits after
index_t(up tocommit_t) are queryable but not yet indexed.phaseis"idle","pending"or"in_progress";enabledis false on a connection without background indexing (":memory:", orindexing=False).
- class fluree.MergePreview¶
What merging
sourceintotargetwould do, without doing it.ahead: commits onsourcethattargetlacks, newest first;behind: the reverse. Each list may be capped;ahead_countandbehind_countare the full counts.ancestor_t: thetof the last commit the two share.fast_forward:targethas no commits of its own since, so the merge just moves it forward.conflicts: properties both sides changed (may be capped;conflict_countis the full count).mergeable: the merge would succeed under the previewed strategy, including the ledger’s SHACL shapes; when it would fail validation,violationsholds the report.changes: the net facts the merge would bring in, when asked for. Passchanges_afterback aschanges_after=to read the next page.
- class fluree.MergeResult¶
The outcome of
Ledger.merge().A
fast_forwardmerge movedtargettosource’s latest commit without writing one; otherwiseidis the new merge commit.tistarget’stafterwards.conflictscounts the propertiesstrategyresolved.
- class fluree.RebaseResult¶
The outcome of
Ledger.rebase().Of the branch’s
totalown commits,replayedwere rewritten on top of its source’s latest commit (source_t) andskippedwere dropped by the"skip"strategy.conflictslists(t, properties, resolution)for each commit that conflicted,tbeing the commit’s originalt;failureslists(t, error)for commits that failed validation once replayed. Afast_forwardrebase had no commits of its own to replay.
- class fluree.RevertPreview¶
What reverting would do, without doing it.
commitsare the commits that would be undone, newest first (may be capped;commit_countis the full count).conflictsare properties changed again since those commits.revertablesays whether the revert would succeed under the previewed strategy and the ledger’s SHACL shapes; when validation would fail,violationsholds the report.
- class fluree.RevertResult¶
The outcome of
Ledger.revert().revertedholds the ids of the undone commits, newest first. Whencommittedis false the commits had nothing left to undo, no commit was written, andt/iddescribe the unchanged head.conflictscounts the properties changed since thatstrategyresolved.
- class fluree.SweepResult¶
The outcome of
Ledger.sweep():orphansindex files no longer referenced, of whichreclaimedwere deleted (none on a dry run);failureslists(file, error)for those that could not be.
- class fluree.ValidationReport¶
The outcome of
Ledger.validate().conformsis false when any result is a violation.shape_countis how many shapes were checked —0means no shapes were found, so the data trivially conforms.tis the state that was validated.- results: list[ValidationResult]¶
- class fluree.ValidationResult¶
One way the data fails a SHACL shape.
focusis the node that failed andpaththe property, when the constraint is on one;valueis the offending value, when there is one.severityis"violation","warning"or"info".shapeis the node shape andcomponentthe SHACL constraint component (sh:MinCountConstraintComponent, …) that produced it.- focus: Any¶
- value: Any¶
- class fluree.VerifyReport¶
The outcome of
Ledger.verify().severityis"healthy","provenance"(a raw transaction is missing: the data is intact) or"chain"(a commit or the index root is missing or unreadable).problemsdescribes each one, as a dict with akind.truncatedmeansmax_commitsstopped the check early.
- fluree.set_log_level(level: str | int) None¶
Send the engine’s log events at
leveland above to thefluree.enginelogger: alogginglevel ("INFO",logging.DEBUG),"TRACE"for the most detail, or"OFF". Warnings and errors are sent by default.This sets what the engine produces; the logger’s own level and handlers still decide what is shown. Below the level, the engine skips the events entirely.
- class fluree.Record¶
Bases:
tupleOne result row: a tuple in the query’s column order that can also be read by column name —
record["name"]orrecord.name— withget,keys,values,itemsanddata.Attribute access gives way to the methods: a column named
dataorcountis read asrecord["data"]. Unbound values areNone.- get(key: str, default: Any = None) Any¶
The value of column
key(Nonewhen unbound), ordefaultwhen the result has no columnkey.
- values(*keys: str | int) list[Any]¶
The values of columns
keys(names or positions), or of every column.
- class fluree.Result(keys: list[str], records: list[Record])¶
Bases:
collections.abc.Sequence[Record]The records a SPARQL
SELECTor a Cypher statement returned, in order. Iterate it, index it, or read it as a whole:single()for the one record,first()for the first,value()for one column,data()for dicts,to_pandas()for a DataFrame.- single() Record¶
The one record;
InvalidRequestErrorunless there is exactly one. For “the first record, if any”, usefirst().
- value(key: str | int = 0, default: Any = None) list[Any]¶
One column’s values,
defaultwhere a record lacks it.
- data(*keys: str | int) list[dict[str, Any]]¶
Every record as a dict of plain values; see
Record.data().
- to_pandas() pandas.DataFrame¶
The records as a pandas DataFrame, one column per key. Nodes and relationships stay objects.
- to_df¶
- to_polars() polars.DataFrame¶
The records as a polars DataFrame, one column per key. Nodes and relationships become object columns.
- class fluree.RowStream(native: RowStream, batch_size: int)¶
Bases:
collections.abc.Iterator[Record]The records of a SELECT, read as the query produces them.
Iterate it like a
Result; memory stays flat however many records the query returns. The query runs until the stream ends,close()is called, or the stream is garbage-collected — so when reading may stop early, use it as a context manager, which closes it at the end of the block:with ledger.stream(query) as rows: for row in rows: if done(row): break
- class fluree.AzureServicePrincipal¶
Microsoft Entra service-principal credentials for Delta tables in ADLS Gen2 or OneLake.
- class fluree.EnvVar¶
A secret read from environment variable
namewhere the source is read, so the secret itself is never stored with the graph source.
- class fluree.Glue¶
An AWS Glue Data Catalog that Iceberg tables are found through: each mapped
rr:tableNameis a Glue<database>.<table>, whose current metadata file Glue names. The catalog call and the S3 reads use the usual AWS environment, never vended credentials.regionis the catalog’s region (elses3_region, else the AWS region chain);catalog_idreads another account’s catalog.
- class fluree.GraphSource(connection: Connection, raw: collections.abc.Mapping[str, Any])¶
A graph source: tables mapped to RDF and queried in place.
Create one with
Connection.map_iceberg(),Connection.map_delta()orConnection.map_sql(), or look one up withConnection.graph_source(). Query it on its own here, or with other graph sources and ledgers throughConnection.query(), naming it inFROM <name:main>(SPARQL) or"from"(JSON-LD).idisname:branch, andkindthe kind of source, such as"iceberg","delta"or"sql".- query(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Any¶
Run a SPARQL or JSON-LD query of this source; see
Snapshot.query(). Cypher reads ledgers only.
- select(query: str, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: SelectLanguage | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) Result¶
Run a SPARQL
SELECTof this source; seeSnapshot.select().
- profile(query: Query, parameters: collections.abc.Mapping[str, Any] | None = None, *, language: Language | None = None, max_fuel: float | None = None, timeout: float | None = None, **kwparameters: Any) QueryProfile¶
Run
query()and report the fuel and time it took.
- materialize(into: str, *, full: bool = False) MaterializeResult¶
Copy this source’s rows into ledger
into(created if missing) as ordinary ledger data, so they gain history, policy and indexes.Each pass reads only what the source has added since the last pass into
into, where the table’s history allows;fullre-reads everything. A row whose subject reappears replaces it. Iceberg sources only.
- class fluree.MaterializeResult¶
One
GraphSource.materialize()pass.snapshotis the source snapshot now reflected in the ledger (Nonefor a table with no snapshots yet).incrementalsays whether only what the source added since the last pass was read;committedwhether anything changed in the ledger.
- class fluree.OAuth2¶
Authenticate with OAuth2 client credentials, fetching (and refreshing) a token from
token_url(which aUnitycatalog can leave to its default).
- class fluree.S3Tables¶
An AWS S3 Tables table bucket that Iceberg tables are found in, named by its ARN (
arn:aws:s3tables:<region>:<account>:bucket/<name>): each mappedrr:tableNameis a<namespace>.<table>in the bucket. The region defaults to the ARN’s. Reads use the usual AWS environment.
- class fluree.Unity¶
A Databricks Unity Catalog that Delta tables are found and read through.
catalogandschemacomplete table names of fewer than three parts. AnOAuth2token_urldefaults to the workspace’s own endpoint.
- class fluree.LangString¶
Bases:
strA language-tagged string: a
strwith alanguagetag.It compares like a string: equal to a plain
strwith the same text, and to anotherLangStringwith the same text and the same tag (compared case-insensitively, as BCP 47 tags are).
- class fluree.Literal¶
A literal with no lossless Python type, as lexical form and datatype.
- class fluree.Vector¶
Bases:
tupleAn embedding vector: a tuple of floats, stored as
f:embeddingVector.Build one from any sequence of numbers or a numpy array. Insert it as a property value, pass it as a query parameter, and read it back from queries;
numpy.asarray(vector)gives afloat32array. Values are stored atfloat32precision. A one-dimensional numpy array is taken as a vector wherever aVectoris.
- exception fluree.ConflictError¶
Bases:
FlureeErrorA concurrent change won; retrying against the new state may succeed.
When a commit lost a race,
expected_tis the ledgertit was built on andhead_tthetanother commit had moved it to; both areNonefor other conflicts.
- exception fluree.DatabaseInUseError¶
Bases:
FlureeErrorThe database directory is open in another process.
One process opens a directory at a time, and its threads share that connection. To use the same data from several processes, run
fluree serveron the directory and send requests to it.pidis the other process’s id, orNonewhen it could not be read.
- exception fluree.FlureeError¶
Bases:
ExceptionBase class for all Fluree errors.
statusis the HTTP-style status code the engine assigned the error, orNonewhen the error did not come from the engine.
- exception fluree.InvalidRequestError¶
Bases:
FlureeError,ValueErrorThe query, transaction, or argument is malformed or invalid.
- exception fluree.NotFoundError¶
Bases:
FlureeError,LookupErrorA ledger, branch, commit, or graph does not exist.
- exception fluree.PermissionDeniedError¶
Bases:
FlureeError,PermissionErrorPolicy denied the operation.
- exception fluree.QueryTimeoutError¶
Bases:
FlureeError,TimeoutErrorThe operation ran past its time limit.
- exception fluree.ResourceLimitError¶
Bases:
FlureeErrorThe operation exceeded a fuel, memory, or size limit.
- exception fluree.ShaclViolationError¶
Bases:
InvalidRequestErrorA write that would leave data breaking the ledger’s SHACL shapes.
violationslists each way it would, as the sameValidationResultobjectsLedger.validate()reports, so a rejected write is handled like a failed validation.- property violations: list[ValidationResult]¶
Each way the write breaks the shapes, as
ValidationResultobjects.
- exception fluree.UniqueConstraintError¶
Bases:
InvalidRequestErrorA write that would give two subjects the same value of a property the ledger requires to be unique (
f:enforceUnique).valueis the value as text;graphis the named graph’s IRI, orNonefor the default graph.