# Fluree DB documentation (v4.2): Getting started

> A temporal graph database with built-in search, policy, and verifiable data. Source: https://labs.flur.ee/docs/db. Each page is also at its URL plus .md. Design notes and contributing guides are left out here.

## Getting Started

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started

Welcome to Fluree! This section will guide you through the essential steps to start using Fluree for your graph database needs.

## Quick Navigation

### [Fluree for SQL Developers](https://labs.flur.ee/docs/db/getting-started/fluree-for-sql-developers)

Coming from PostgreSQL, MySQL, or SQL Server? This guide maps SQL concepts to Fluree equivalents, shows the same operations in both languages, and highlights where Fluree gives you capabilities that relational databases don't have.

### [Quickstart: Run the Server](https://labs.flur.ee/docs/db/getting-started/quickstart-server)

Get Fluree up and running in minutes. Learn how to:
- Install and run the Fluree server
- Configure basic settings
- Verify the server is running
- Access the HTTP API

### [Quickstart: Create a Ledger](https://labs.flur.ee/docs/db/getting-started/quickstart-ledger)

Create your first ledger to store data. Learn how to:
- Create a new ledger using the API
- Understand ledger IDs and branching
- Set up initial configuration
- Verify ledger creation

### [Quickstart: Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write)

Start writing data to your ledger. Learn how to:
- Insert new entities (basic inserts)
- Upsert data (idempotent transactions; predicate-level replacement for supplied predicates)
- Update existing data (WHERE/DELETE/INSERT pattern)
- Understand JSON-LD transaction format

### [Quickstart: Query Data](https://labs.flur.ee/docs/db/getting-started/quickstart-query)

Query your data using Fluree's powerful query languages. Learn how to:
- Write basic JSON-LD queries
- Write basic SPARQL queries
- Filter and select data
- Understand query results

### [Tutorial: End-to-End](https://labs.flur.ee/docs/db/getting-started/tutorial-end-to-end)

Build a knowledge base that combines Fluree's differentiating features in one workflow:
- Full-text search with BM25 relevance ranking
- Time travel to compare current and historical state
- Branching to experiment safely
- Policies for role-based access control

### [Using Fluree as a Rust Library](https://labs.flur.ee/docs/db/getting-started/rust-api)

Embed Fluree directly in your Rust applications. Learn how to:
- Add Fluree as a dependency in Cargo.toml
- Use the Rust API programmatically
- Implement common patterns (insert, query, update)
- Integrate BM25 and vector search
- Handle errors and configuration
- Write tests with Fluree

### [Using Fluree from Python](https://labs.flur.ee/docs/db/getting-started/python)

Run Fluree inside your Python process with `pip install fluree`. Learn how to:
- Install the package and open a ledger
- Read this book's queries and transactions from Python
- Use transactions, time travel, policy and asyncio from Python

## What is Fluree?

Fluree is a temporal graph database that stores data as RDF triples with built-in support for:

- **Time Travel**: Query data as it existed at any point in time
- **Full-Text Search**: Integrated BM25 indexing for powerful text search
- **Vector Search**: Approximate nearest neighbor (ANN) queries
- **Policy Enforcement**: Fine-grained, data-level access control
- **Verifiable Data**: Cryptographically signed transactions
- **Graph Sources**: Integration with external data sources (Iceberg, R2RML)

## Learning Path

**For HTTP API users (server-based):**

1. **Bridge the gap**: [Fluree for SQL Developers](https://labs.flur.ee/docs/db/getting-started/fluree-for-sql-developers) if coming from relational databases
2. **Start with the Server**: [Run the Server](https://labs.flur.ee/docs/db/getting-started/quickstart-server) to get Fluree running
3. **Create Your First Ledger**: [Create a Ledger](https://labs.flur.ee/docs/db/getting-started/quickstart-ledger) to set up your database
4. **Add Data**: [Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write) to insert your first entities
5. **Query Your Data**: [Query Data](https://labs.flur.ee/docs/db/getting-started/quickstart-query) to retrieve and explore
6. **See it all together**: [End-to-End Tutorial](https://labs.flur.ee/docs/db/getting-started/tutorial-end-to-end) — search, time travel, branching, and policies in one workflow
7. **Core Concepts**: Read [Concepts](https://labs.flur.ee/docs/db/concepts) to understand Fluree's architecture
8. **Practical Guides**: Explore [Cookbooks](https://labs.flur.ee/docs/db/guides) for search, time travel, branching, policies, and SHACL validation
9. **Deep Dive**: Explore [Query](https://labs.flur.ee/docs/db/query), [Transactions](https://labs.flur.ee/docs/db/transactions), and [Security](https://labs.flur.ee/docs/db/security)
10. **Production Ready**: Review [Operations](https://labs.flur.ee/docs/db/operations) for deployment guidance

**For Rust developers (embedded library):**

1. **Rust API Guide**: [Using Fluree as a Rust Library](https://labs.flur.ee/docs/db/getting-started/rust-api) for embedding Fluree in your application
2. **Core Concepts**: [Concepts](https://labs.flur.ee/docs/db/concepts) to understand how Fluree works
3. **Practical Guides**: [Cookbooks](https://labs.flur.ee/docs/db/guides) for search, time travel, branching, policies, and validation
4. **Advanced Queries**: [Query](https://labs.flur.ee/docs/db/query) for complex query patterns
5. **Transactions**: [Transactions](https://labs.flur.ee/docs/db/transactions) for data modification patterns
6. **Production Ready**: [Operations](https://labs.flur.ee/docs/db/operations) and [Dev Setup](https://labs.flur.ee/docs/db/contributing/dev-setup)

**For Python developers (embedded package):**

1. **Python Guide**: [Using Fluree from Python](https://labs.flur.ee/docs/db/getting-started/python) to install the package and map this book to its API
2. **Core Concepts**: [Concepts](https://labs.flur.ee/docs/db/concepts) to understand how Fluree works
3. **Practical Guides**: [Cookbooks](https://labs.flur.ee/docs/db/guides); their queries run unchanged through `ledger.query()`
4. **Queries and writes**: [Query](https://labs.flur.ee/docs/db/query) and [Transactions](https://labs.flur.ee/docs/db/transactions)

## Prerequisites

- Familiarity with JSON format
- HTTP client (curl, Postman, or your programming language's HTTP library)
- No graph database or RDF experience required — [Fluree for SQL Developers](https://labs.flur.ee/docs/db/getting-started/fluree-for-sql-developers) bridges the gap from relational databases

## Support and Resources

- **Documentation**: This documentation provides comprehensive coverage
- **API Reference**: See [HTTP API](https://labs.flur.ee/docs/db/api) for endpoint details
- **Troubleshooting**: Check [Troubleshooting](https://labs.flur.ee/docs/db/troubleshooting) for common issues

Let's get started!


## Fluree for SQL Developers

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/fluree-for-sql-developers

If you've spent years with PostgreSQL, MySQL, or SQL Server and are encountering a graph database for the first time, this guide bridges the gap. It maps SQL concepts you already know to their Fluree equivalents, shows you the same operations in both languages, and highlights where Fluree gives you capabilities that relational databases simply don't have.

## The mental model shift

In SQL, you design tables with fixed columns, then insert rows. In Fluree, you make statements about things — and those statements can describe anything, with any properties, at any time.

| SQL Concept | Fluree Equivalent | Key Difference |
|---|---|---|
| Database | Ledger | Immutable — every change is preserved |
| Table | Type (via `rdf:type`) | No fixed schema required; types are just labels |
| Row | Entity (identified by IRI) | An entity can have any properties, not just those in a "table" |
| Column | Predicate (property) | Not tied to a single type; any entity can use any property |
| Foreign key | Reference (IRI link) | Relationships are first-class, bidirectional, and traversable |
| Value | Object (literal or reference) | Typed values (string, integer, date, etc.) |
| Row (one fact) | Flake | A triple + provenance (graph, transaction time, assert/retract) |
| `NULL` | Absence | Properties simply don't exist if not set — no nulls |

### The flake: Fluree's atomic unit

Every fact in Fluree is stored as a **flake** — an extended triple that adds provenance. At its core, a flake is a statement: `subject → predicate → object`, plus metadata about *when* it was asserted, *which graph* it belongs to, and *whether it's an assertion or retraction*.

```
ex:alice  schema:name  "Alice"       (graph: default, t: 1, op: assert)
ex:alice  schema:age   30            (graph: default, t: 1, op: assert)
ex:alice  schema:knows ex:bob        (graph: default, t: 1, op: assert)
```

Think of it as: "Alice's name is Alice (added in transaction 1)." The provenance is what makes time travel and immutability possible — every change is a new flake, and retractions are recorded alongside assertions.

In SQL terms, imagine a universal table with columns `entity_id`, `attribute`, `value`, `graph`, `transaction`, `operation` — that can represent any data structure without DDL and preserves complete history.

> **Terminology note:** In RDF standards, the core unit is called a "triple" (subject-predicate-object). Fluree's "flake" extends the triple with temporal and provenance metadata. You'll see both terms in the documentation — "triple" when discussing the RDF data model, "flake" when discussing Fluree's storage and history.

## Side by side: common operations

### Creating structure

**SQL — Define a table:**
```sql
CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE,
  department VARCHAR(100),
  salary DECIMAL(10,2),
  manager_id INTEGER REFERENCES employees(id)
);
```

**Fluree — Just insert data:**
```bash
fluree insert '
@prefix schema: <http://schema.org/> .
@prefix ex:     <http://example.org/> .

ex:alice  a schema:Person ;
  schema:name        "Alice Smith" ;
  schema:email       "alice@example.com" ;
  ex:department      "Engineering" ;
  ex:salary          125000 ;
  ex:reportsTo       ex:bob .

ex:bob  a schema:Person ;
  schema:name        "Bob Jones" ;
  schema:email       "bob@example.com" ;
  ex:department      "Engineering" .
'
```

There's no `CREATE TABLE`. Types and properties emerge from the data itself. You can add new properties to any entity at any time without migrations.

### Inserting data

**SQL:**
```sql
INSERT INTO employees (name, email, department, salary)
VALUES ('Carol Davis', 'carol@example.com', 'Marketing', 95000);
```

**Fluree (CLI):**
```bash
fluree insert '
@prefix schema: <http://schema.org/> .
@prefix ex:     <http://example.org/> .

ex:carol  a schema:Person ;
  schema:name        "Carol Davis" ;
  schema:email       "carol@example.com" ;
  ex:department      "Marketing" ;
  ex:salary          95000 .
'
```

**Fluree (HTTP API):**
```bash
curl -X POST http://localhost:8090/v1/fluree/insert?ledger=mydb:main \
  -H "Content-Type: application/ld+json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/",
      "ex": "http://example.org/"
    },
    "@id": "ex:carol",
    "@type": "schema:Person",
    "schema:name": "Carol Davis",
    "schema:email": "carol@example.com",
    "ex:department": "Marketing",
    "ex:salary": 95000
  }'
```

### Basic queries

**SQL:**
```sql
SELECT name, email FROM employees WHERE department = 'Engineering';
```

**Fluree (SPARQL):**
```sparql
PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?name ?email
WHERE {
  ?person a schema:Person ;
          schema:name ?name ;
          schema:email ?email ;
          ex:department "Engineering" .
}
```

**Fluree (JSON-LD Query):**
```json
{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?name", "?email"],
  "where": [
    {
      "@id": "?person", "@type": "schema:Person",
      "schema:name": "?name",
      "schema:email": "?email",
      "ex:department": "Engineering"
    }
  ]
}
```

### Joins

In SQL, joins are explicit operations. In Fluree, relationships are just triples — "joining" is following a link.

**SQL — Find employees and their managers:**
```sql
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id;
```

**Fluree (SPARQL):**
```sparql
PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?employee ?manager
WHERE {
  ?e schema:name ?employee ;
     ex:reportsTo ?m .
  ?m schema:name ?manager .
}
```

No `JOIN` keyword — you just follow the `ex:reportsTo` link from one entity to another. The database traverses relationships natively.

### Multi-hop relationships

This is where graphs shine. "Find everyone in Alice's reporting chain" requires recursive CTEs in SQL but is natural in a graph.

**SQL (recursive CTE):**
```sql
WITH RECURSIVE chain AS (
  SELECT id, name, manager_id FROM employees WHERE name = 'Alice Smith'
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e JOIN chain c ON e.id = c.manager_id
)
SELECT name FROM chain;
```

**Fluree (SPARQL — property path):**
```sparql
PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?name
WHERE {
  ex:alice ex:reportsTo+ ?manager .
  ?manager schema:name ?name .
}
```

The `+` after `ex:reportsTo` means "follow this relationship one or more times." No recursion needed.

### Aggregation

**SQL:**
```sql
SELECT department, COUNT(*) as count, AVG(salary) as avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;
```

**Fluree (SPARQL):**
```sparql
PREFIX ex: <http://example.org/>

SELECT ?dept (COUNT(?person) AS ?count) (AVG(?salary) AS ?avg_salary)
WHERE {
  ?person ex:department ?dept ;
          ex:salary ?salary .
}
GROUP BY ?dept
ORDER BY DESC(?avg_salary)
```

### Updates

**SQL:**
```sql
UPDATE employees SET salary = 130000 WHERE name = 'Alice Smith';
```

**Fluree (SPARQL UPDATE):**
```sparql
PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

DELETE { ?person ex:salary ?oldSalary }
INSERT { ?person ex:salary 130000 }
WHERE  { ?person schema:name "Alice Smith" ; ex:salary ?oldSalary }
```

The `WHERE` finds Alice, `DELETE` removes the old salary, and `INSERT` adds the new one. This is atomic.

**Fluree (CLI — upsert for simpler cases):**
```bash
fluree upsert '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "@id": "ex:alice",
  "ex:salary": 130000
}'
```

Upsert replaces the salary value if Alice already exists, or creates the entity if she doesn't.

### Deletes

**SQL:**
```sql
DELETE FROM employees WHERE name = 'Carol Davis';
```

**Fluree (SPARQL UPDATE):**
```sparql
PREFIX schema: <http://schema.org/>

DELETE { ?person ?p ?o }
WHERE  { ?person schema:name "Carol Davis" ; ?p ?o }
```

But here's the key difference: in SQL, the row is gone. In Fluree, the retraction is recorded — you can still query Carol's data at any previous point in time.

## What SQL can't do

These features have no relational equivalent:

### Time travel

Query data as it existed at any point in the past:

```bash
# What was Alice's salary before the raise?
fluree query --at 1 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?salary WHERE {
  ?person schema:name "Alice Smith" ; ex:salary ?salary .
}'
```

```bash
# Show the full history of salary changes
fluree history 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?salary ?t ?op WHERE {
  ?person schema:name "Alice Smith" ; ex:salary ?salary .
}'
```

In SQL, you'd need audit tables, temporal extensions, or trigger-based logging. In Fluree, every change is automatically preserved.

### Schema flexibility

Add new properties to any entity without `ALTER TABLE`:

```bash
# Alice now has a phone number — no migration needed
fluree insert '
@prefix schema: <http://schema.org/> .
@prefix ex:     <http://example.org/> .

ex:alice schema:telephone "+1-555-0100" .
'
```

Different entities of the same "type" can have different properties. There's no fixed set of columns.

### Branching

Fork your data to experiment without affecting production:

```bash
fluree branch create experiment
fluree use mydb:experiment

# Try risky changes on the branch
fluree update 'PREFIX ex: <http://example.org/>
DELETE { ?p ex:salary ?s }
INSERT { ?p ex:salary 200000 }
WHERE  { ?p ex:salary ?s }'

# Main branch is untouched
fluree query --ledger mydb:main 'SELECT ?name ?salary WHERE {
  ?p <http://schema.org/name> ?name ; <http://example.org/salary> ?salary
}'
```

### Triple-level access control

SQL databases give you table-level or row-level security. Fluree policies control access to individual facts:

```json
{
  "@id": "ex:hide-salary",
  "f:action": "query",
  "f:resource": { "f:predicate": "ex:salary" },
  "f:allow": false
}
```

This hides salary data from everyone unless another policy explicitly grants access. The same query returns different results for different users, automatically.

### Integrated full-text search

No need for Elasticsearch or Solr alongside your database:

```bash
fluree insert '{
  "@context": {"ex": "http://example.org/"},
  "@id": "ex:doc1",
  "ex:content": {
    "@value": "Fluree is a graph database with time travel and integrated search",
    "@type": "@fulltext"
  }
}'

fluree query '{
  "@context": {"ex": "http://example.org/"},
  "select": ["?id", "?score"],
  "where": [
    {"@id": "?id", "ex:content": "?text"},
    ["bind", "?score", "(fulltext ?text \"graph database search\")"],
    ["filter", "(> ?score 0)"]
  ],
  "orderBy": [["desc", "?score"]]
}'
```

## Common "but in SQL I would..." questions

**"How do I enforce NOT NULL?"**
Use [SHACL shapes](https://labs.flur.ee/docs/db/guides/cookbook-shacl) to define constraints like required properties, value types, and cardinality.

**"How do I enforce UNIQUE?"**
Fluree supports [unique constraints](https://labs.flur.ee/docs/db/ledger-config/unique-constraints) in the ledger configuration.

**"How do I do transactions?"**
Every Fluree transaction is atomic. Multiple operations in a single request either all succeed or all fail.

**"How do I create indexes?"**
Fluree automatically maintains four indexes (SPOT, POST, OPST, PSOT) that cover all query patterns. You don't need to create indexes manually.

**"How do I paginate?"**
Use `LIMIT` and `OFFSET`, just like SQL:
```sparql
SELECT ?name WHERE { ?p schema:name ?name }
ORDER BY ?name LIMIT 20 OFFSET 40
```

**"How do I do subqueries?"**
SPARQL supports subqueries natively:
```sparql
SELECT ?name ?avgSalary WHERE {
  ?person schema:name ?name ; ex:department ?dept .
  { SELECT ?dept (AVG(?s) AS ?avgSalary) WHERE { ?p ex:department ?dept ; ex:salary ?s } GROUP BY ?dept }
}
```

## Next steps

- [Quickstart: Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write) — Start writing data with the HTTP API
- [SPARQL Reference](https://labs.flur.ee/docs/db/query/sparql) — Full SPARQL 1.1 query reference
- [JSON-LD Query](https://labs.flur.ee/docs/db/query/jsonld-query) — Fluree's JSON-native query language
- [Concepts](https://labs.flur.ee/docs/db/concepts) — Deeper understanding of Fluree's architecture
- [Time Travel](https://labs.flur.ee/docs/db/concepts/time-travel) — Full guide to temporal queries


## Quickstart: Run the Server

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/quickstart-server

This guide will get the Fluree server running on your machine in minutes.

## Installation

The macOS builds are for Apple silicon and need macOS 14 (Sonoma) or later.

### Option 1: Shell Installer (macOS / Linux)

```bash
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/fluree/db/releases/latest/download/fluree-db-cli-installer.sh | sh
```

### Option 2: Homebrew (macOS / Linux)

```bash
brew install fluree/tap/fluree
```

`fluree` installs stable releases only. To try a pre-release, install `fluree-beta`, which follows the newest release, pre-release or stable. It installs beside `fluree` without replacing the `fluree` on your `PATH`, so you run it by its path:

```bash
brew install fluree/tap/fluree-beta
"$(brew --prefix fluree/tap/fluree-beta)/bin/fluree" --version
```

To make the beta your default `fluree`, put `$(brew --prefix fluree/tap/fluree-beta)/bin` first in your `PATH`; take it out to go back to the stable release. When a stable release supersedes the beta, `brew upgrade` moves `fluree-beta` to it.

### Option 3: PowerShell (Windows)

Open PowerShell and run:

```powershell
irm https://github.com/fluree/db/releases/latest/download/fluree-db-cli-installer.ps1 | iex
```

Then open a **new** PowerShell session and verify `fluree --version`. The installer adds `%USERPROFILE%\bin` to your `PATH`. The binary is unsigned, so Windows SmartScreen may prompt on first run — click **More info → Run anyway**.

### Option 4: Download Pre-built Binary

Download the latest release for your platform from [GitHub Releases](https://github.com/fluree/db/releases):

```bash
# Linux (x86_64)
curl -L https://github.com/fluree/db/releases/latest/download/fluree-db-cli-x86_64-unknown-linux-gnu.tar.xz | tar xJ
chmod +x fluree-db-cli-x86_64-unknown-linux-gnu/fluree

# macOS 14 or later (Apple Silicon)
curl -L https://github.com/fluree/db/releases/latest/download/fluree-db-cli-aarch64-apple-darwin.tar.xz | tar xJ
chmod +x fluree-db-cli-aarch64-apple-darwin/fluree
```

### Option 5: Build from Source

If you have Rust installed:

```bash
# Clone the repository
git clone https://github.com/fluree/db.git
cd db

# Build the CLI (includes embedded server)
cargo build --release -p fluree-db-cli

# Binary will be at target/release/fluree
```

### Option 6: Docker

```bash
# Pull the image
docker pull fluree/server:latest

# Run the container
docker run -p 8090:8090 fluree/server:latest
```

For configuration (mounted JSON-LD/TOML config files, env vars, persistent volumes, S3+DynamoDB, query peers, full Compose example), see [Running with Docker](https://labs.flur.ee/docs/db/operations/docker).

## Start the Server

### Default Storage (Development)

`fluree server run` needs a Fluree project directory; create one with `fluree init` if you
haven't. By default the server stores data in the project's `.fluree/storage` directory:

```bash
fluree init
fluree server run
```

You should see output like:

```text
INFO fluree_db_cli::commands::server: Starting Fluree server (foreground) version="…" addr=0.0.0.0:8090 storage="file"
```

### Memory Storage (Throwaway)

To try the server without creating a project, keep the data in memory. Nothing is written to the
current directory, and the data is gone when the server stops:

```bash
fluree server run --memory
```

### File Storage (Persistent)

For persistent storage, specify a storage path:

```bash
fluree server run --storage-path /var/lib/fluree
```

### Custom Port

```bash
fluree server run --listen-addr 0.0.0.0:9090
```

### Debug Logging

```bash
fluree server run --log-level debug
```

## Verify Installation

### Check Server Health

```bash
curl http://localhost:8090/health
```

Expected response:

```json
{
  "status": "ok",
  "version": "4.0.4"
}
```

### Create a Ledger

```bash
curl -X POST http://localhost:8090/v1/fluree/create \
  -H "Content-Type: application/json" \
  -d '{"ledger": "test:main"}'
```

### Insert Data

```bash
curl -X POST "http://localhost:8090/v1/fluree/insert" \
  -H "Content-Type: application/json" \
  -H "fluree-ledger: test:main" \
  -d '{
    "@context": {"ex": "http://example.org/"},
    "@id": "ex:alice",
    "ex:name": "Alice"
  }'
```

### Query Data

```bash
curl -X POST "http://localhost:8090/v1/fluree/query" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "test:main",
    "select": {"?s": ["*"]},
    "where": [["?s", "ex:name", "?name"]]
  }'
```

## Understanding the Server

### Endpoints

Default server endpoints:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/health` | GET | Health check |
| `/v1/fluree/create` | POST | Create a ledger |
| `/v1/fluree/drop` | POST | Drop a ledger |
| `/v1/fluree/query` | GET/POST | Execute queries |
| `/v1/fluree/insert` | POST | Insert data |
| `/v1/fluree/update` | POST | Update with WHERE/DELETE/INSERT |
| `/v1/fluree/events` | GET | SSE event stream |

See the [API Reference](https://labs.flur.ee/docs/db/api/endpoints) for complete endpoint documentation.

### Storage Modes

**File** (default; `.fluree/storage`, or set with `--storage-path`):
- Persistent local file storage
- Data survives restarts
- Best for single-server deployments

**Memory** (`--memory`; see [Storage Modes](https://labs.flur.ee/docs/db/operations/storage#memory-storage)):
- Fast, in-process storage
- Data lost on restart
- Best for development, testing, and CI

### Configuration

All options can be set via CLI flags or environment variables. `fluree server run` takes the
most common server flags directly; pass any other server flag after `--`
(for example `fluree server run -- --cache-max-mb 4096`):

```bash
# CLI flag
fluree server run --storage-path /data --log-level debug

# Environment variables
export FLUREE_LISTEN_ADDR=0.0.0.0:9090
export FLUREE_LOG_LEVEL=debug
fluree server run
```

See [Configuration](https://labs.flur.ee/docs/db/operations/configuration) for all options.

## Common Configurations

### Development

```bash
fluree server run --log-level debug
```

### Production (Single Server)

```bash
fluree server run \
  --storage-path /var/lib/fluree \
  -- \
  --indexing-enabled \
  --events-auth-mode required \
  --events-auth-trusted-issuer did:key:z6Mk...
```

### With Background Indexing

```bash
fluree server run \
  --storage-path /var/lib/fluree \
  -- \
  --indexing-enabled
```

## Docker Deployment

For the full Docker guide — image internals, configuration via env vars vs mounted JSON-LD/TOML config files, persistent volumes, LRU cache and indexing tuning, S3+DynamoDB connection configs, query peers, and a production-ready Compose example — see [Running with Docker](https://labs.flur.ee/docs/db/operations/docker).

Minimal persistent run:

```bash
docker run -d --name fluree \
  -p 8090:8090 \
  -v fluree-data:/var/lib/fluree \
  fluree/server:latest
```

## Troubleshooting

### Port Already in Use

```bash
# Use a different port
fluree server run --listen-addr 0.0.0.0:9090
```

### Permission Denied (File Storage)

```bash
sudo chown -R $USER:$USER /var/lib/fluree
chmod -R 755 /var/lib/fluree
```

### Server Won't Start

Check logs with debug level:

```bash
fluree server run --log-level debug
```

### Connection Refused

Verify the server is running and check the listen address:

```bash
# Listen on all interfaces (not just localhost)
fluree server run --listen-addr 0.0.0.0:8090
```

## Next Steps

Now that your server is running:

1. [Create a Ledger](https://labs.flur.ee/docs/db/getting-started/quickstart-ledger) - Set up your first database
2. [Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write) - Insert your first records
3. [Query Data](https://labs.flur.ee/docs/db/getting-started/quickstart-query) - Retrieve and explore your data

For production deployments:

- [Configuration](https://labs.flur.ee/docs/db/operations/configuration) - All server options
- [Query Peers](https://labs.flur.ee/docs/db/operations/query-peers) - Horizontal scaling
- [Admin Authentication](https://labs.flur.ee/docs/db/api/endpoints#admin-authentication) - Protect admin endpoints


## Quickstart: Create a Ledger

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/quickstart-ledger

Ledgers are Fluree's fundamental unit of data organization—similar to databases in traditional systems. This guide shows you how to create your first ledger.

## Understanding Ledger IDs

Ledgers are identified by **ledger IDs** with the format `ledger-name:branch`:

- `mydb:main` - Primary branch of the "mydb" ledger
- `customers:dev` - Development branch of the "customers" ledger
- `inventory:prod` - Production branch

The default branch is `main`, so `mydb` is equivalent to `mydb:main`.

## Creating a Ledger

### Rust API (Library Usage)

When using Fluree as a Rust library, create ledgers explicitly with `create_ledger`:

```rust
let fluree = FlureeBuilder::memory().build_memory();

// Create a new ledger (returns LedgerState at t=0)
let ledger = fluree.create_ledger("mydb").await?;

// Now insert data
let result = fluree.graph("mydb:main")
    .transact()
    .insert(&data)
    .commit()
    .await?;
```

`create_ledger` registers the ledger in the nameservice and returns a genesis `LedgerState` ready for transactions. It returns `ApiError::LedgerExists` (HTTP 409) if the ledger already exists.

To load an existing ledger, use `ledger`:

```rust
let ledger = fluree.ledger("mydb:main").await?;
```

### HTTP API (Server Usage)

Via the HTTP API, create a ledger explicitly with `POST /v1/fluree/create`, then write data with `POST /v1/fluree/insert`.

#### Step 1: Create the Ledger

```bash
curl -X POST http://localhost:8090/v1/fluree/create \
  -H "Content-Type: application/json" \
  -d '{"ledger": "mydb:main"}'
```

Response:

```json
{
  "ledger_id": "mydb:main",
  "t": 0,
  "tx-id": "fluree:tx:sha256:...",
  "commit": {"hash": ""}
}
```

#### Step 2: Insert Data

```bash
curl -X POST http://localhost:8090/v1/fluree/insert \
  -H "Content-Type: application/json" \
  -H "fluree-ledger: mydb:main" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:alice",
        "@type": "schema:Person",
        "schema:name": "Alice",
        "schema:email": "alice@example.org"
      }
    ]
  }'
```

Response:

```json
{
  "ledger_id": "mydb:main",
  "t": 1,
  "tx-id": "fluree:tx:sha256:...",
  "commit": {"hash": "bagaybqab..."}
}
```

The ledger `mydb:main` now has data!

## Verifying Ledger Creation

### Check Ledger Exists

```bash
curl http://localhost:8090/v1/fluree/exists/mydb:main
```

Response:

```json
{
  "ledger_id": "mydb:main",
  "exists": true
}
```

### Query the Ledger

Verify you can query the new ledger:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?name"],
    "where": [
      { "@id": "?person", "schema:name": "?name" }
    ]
  }'
```

Response:

```json
[
  { "name": "Alice" }
]
```

## Ledger Naming Best Practices

### Descriptive Names

Choose names that clearly indicate purpose:

Good examples:
- `customers:main`
- `inventory:prod`
- `analytics:warehouse`

Bad examples:
- `db1:main`
- `test:main`
- `data:main`

### Hierarchical Organization

Use slashes for logical grouping:

```text
tenant/app:main
tenant/app:dev
department/project:feature-x
```

### Branch Naming

Establish consistent branch naming conventions:

```text
mydb:main              - Production branch
mydb:dev               - Development branch
mydb:staging           - Staging branch
mydb:feature-auth      - Feature branch
mydb:bugfix-login      - Bug fix branch
```

## Working with Branches

### Creating a New Branch

Branches are independent ledgers. First create the branch, then transact data into it:

```bash
# Create the branch
curl -X POST http://localhost:8090/v1/fluree/create \
  -H "Content-Type: application/json" \
  -d '{"ledger": "mydb:dev"}'

# Insert data into the branch
curl -X POST http://localhost:8090/v1/fluree/insert?ledger=mydb:dev \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:bob",
        "@type": "schema:Person",
          "schema:name": "Bob"
      }
    ]
  }'
```

Now you have two independent ledgers:
- `mydb:main` (with Alice)
- `mydb:dev` (with Bob)

### Understanding Branch Independence

Branches are completely independent—changes in one don't affect the other:

```bash
# Query main branch
curl -X POST http://localhost:8090/v1/fluree/query \
  -d '{"from": "mydb:main", "select": ["?name"], "where": [{"@id": "?person", "schema:name": "?name"}]}'
# Returns: [{"name": "Alice"}]

# Query dev branch
curl -X POST http://localhost:8090/v1/fluree/query \
  -d '{"from": "mydb:dev", "select": ["?name"], "where": [{"@id": "?person", "schema:name": "?name"}]}'
# Returns: [{"name": "Bob"}]
```

## Ledger Metadata

Each ledger maintains metadata accessible via the nameservice:

- **commit_t**: Latest transaction time
- **index_t**: Latest indexed transaction time
- **commit_id**: ContentId (CID) of the latest commit
- **index_id**: ContentId (CID) of the latest index
- **default_context**: Default JSON-LD @context for the ledger

### Checking Ledger Status

```bash
curl http://localhost:8090/v1/fluree/info/mydb:main
```

Response:

```json
{
  "ledger_id": "mydb:main",
  "branch": "main",
  "commit_t": 1,
  "index_t": 1,
  "commit_id": "bafybeig...commitT1",
  "index_id": "bafybeig...indexT1",
  "created": "2024-01-22T10:30:00.000Z",
  "last_updated": "2024-01-22T10:30:05.000Z"
}
```

### Understanding Commit vs Index

- **commit_t**: Most recent transaction (always up-to-date)
- **index_t**: Most recent indexed snapshot (may lag behind commits)
- **Gap**: If `commit_t > index_t`, there's a "novelty layer" being indexed

See [Ledgers and Nameservice](https://labs.flur.ee/docs/db/concepts/ledgers-and-nameservice) for details.

## Multi-Tenant Scenarios

For multi-tenant applications, use hierarchical naming:

```text
tenant1/app:main
tenant1/app:dev
tenant2/app:main
tenant2/app:dev
```

Or use separate ledgers per tenant:

```text
tenant1-customers:main
tenant1-orders:main
tenant2-customers:main
tenant2-orders:main
```

## Setting Default Context

A ledger may have a stored default JSON-LD `@context` that the **CLI** and **HTTP server** can auto-inject into queries that omit `@context` / `PREFIX`. Two ways to set it:

1. **At import time:** `fluree create --from data.ttl` captures `@prefix` declarations from the Turtle source and stores them as the default.
2. **Explicitly:** `fluree context set <ledger> <ctx.json>`, or `PUT /v1/fluree/context/{ledger...}` over HTTP.

Regular JSON-LD transactions (insert/update) do **not** update the default context — only the two paths above do.

```json
// One-time setup via the CLI:
// fluree context set mydb context.json
{
  "@context": {
    "ex": "http://example.org/ns/",
    "schema": "http://schema.org/",
    "xsd": "http://www.w3.org/2001/XMLSchema#"
  }
}
```

After this, the CLI (`fluree query`) and the HTTP server query endpoint will inject the stored context into queries that don't supply their own `@context` / `PREFIX`. Direct `fluree-db-api` consumers do **not** get auto-injection — they must opt in via `Fluree::db_with_default_context(...)` or include `@context` in each query. See `docs/concepts/iri-and-context.md` for the full opt-in story.

## Common Patterns

### Development Workflow

```text
1. Create main branch: mydb:main
2. Create dev branch: mydb:dev
3. Develop and test in dev
4. Copy desired state to main (application logic)
5. Repeat
```

### Feature Branching

```text
1. Create feature branch: mydb:feature-x
2. Develop feature in isolation
3. Test thoroughly
4. Merge to main (via application logic)
5. Optionally retract feature branch
```

### Environment Separation

```text
mydb:dev      - Development environment
mydb:staging  - Staging environment
mydb:prod     - Production environment
```

## Troubleshooting

### Ledger Already Exists

If you try to query a ledger before it exists:

```text
Error: Ledger not found: mydb:main
```

Solution: Create the ledger with a transaction first.

### Permission Issues (File Storage)

If using file storage, ensure the server has write permissions:

```bash
# Check data directory permissions
ls -la /path/to/data

# Fix permissions if needed
sudo chown -R fluree:fluree /path/to/data
chmod -R 755 /path/to/data
```

### AWS Storage Issues

For AWS storage, verify credentials and bucket access:

```bash
# Test S3 access
aws s3 ls s3://your-fluree-bucket/

# Test DynamoDB access
aws dynamodb describe-table --table-name fluree-nameservice
```

## Next Steps

Now that you have a ledger:

1. [Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write) - Learn how to insert, upsert, and update data
2. [Query Data](https://labs.flur.ee/docs/db/getting-started/quickstart-query) - Explore your data with queries
3. [Concepts: Ledgers](https://labs.flur.ee/docs/db/concepts/ledgers-and-nameservice) - Deep dive into ledger architecture

## Related Documentation

- [Ledgers and Nameservice](https://labs.flur.ee/docs/db/concepts/ledgers-and-nameservice) - Architectural details
- [Transactions](https://labs.flur.ee/docs/db/transactions) - Writing data to ledgers
- [Storage Modes](https://labs.flur.ee/docs/db/operations/storage) - Storage backend options


## Quickstart: Write Data

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/quickstart-write

This guide shows you how to write data to Fluree using three main patterns: insert, upsert, and update.

## Prerequisites

- Fluree server running (see [Run the Server](https://labs.flur.ee/docs/db/getting-started/quickstart-server))
- A ledger created (see [Create a Ledger](https://labs.flur.ee/docs/db/getting-started/quickstart-ledger))

## Understanding Fluree Transactions

Fluree stores data as RDF triples (subject-predicate-object). Transactions are submitted as JSON-LD documents that get converted to triples internally.

This guide uses JSON-LD. The same writes can also be expressed in **SPARQL UPDATE** or **openCypher** (`CREATE`/`MERGE`/`SET`/`DELETE`) — all three land in the same ledger. See the [Cypher reference](https://labs.flur.ee/docs/db/query/cypher) for the property-graph write surface.

### Basic Transaction Structure

```json
{
  "@context": {
    "ex": "http://example.org/ns/",
    "schema": "http://schema.org/"
  },
  "@graph": [
    {
      "@id": "ex:alice",
      "@type": "schema:Person",
      "schema:name": "Alice"
    }
  ]
}
```

This creates triples like:
```text
ex:alice  rdf:type        schema:Person
ex:alice  schema:name     "Alice"
```

## Insert: Adding New Data

The simplest operation is inserting new entities.

### Insert a Single Entity

```bash
curl -X POST http://localhost:8090/v1/fluree/insert?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:alice",
        "@type": "schema:Person",
        "schema:name": "Alice",
        "schema:email": "alice@example.org",
        "schema:age": 30
      }
    ]
  }'
```

Response:

```json
{
  "t": 1,
  "timestamp": "2024-01-22T10:30:00.000Z",
  "commit_id": "bafybeig...commitT1",
  "flakes_added": 4,
  "flakes_retracted": 0
}
```

### Insert Multiple Entities

```bash
curl -X POST http://localhost:8090/v1/fluree/insert?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:bob",
        "@type": "schema:Person",
        "schema:name": "Bob",
        "schema:email": "bob@example.org"
      },
      {
        "@id": "ex:carol",
        "@type": "schema:Person",
        "schema:name": "Carol",
        "schema:email": "carol@example.org"
      }
    ]
  }'
```

### Insert with Relationships

```bash
curl -X POST http://localhost:8090/v1/fluree/insert?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:company-a",
        "@type": "schema:Organization",
        "schema:name": "Acme Corp"
      },
      {
        "@id": "ex:alice",
        "@type": "schema:Person",
        "schema:name": "Alice",
        "schema:worksFor": {"@id": "ex:company-a"}
      }
    ]
  }'
```

## Upsert: Idempotent Transactions

Upsert (update/insert) replaces values for the predicates you supply on an entity. If the entity doesn't exist, it's created.

### Basic Upsert

Use the dedicated `/upsert` endpoint:

```bash
curl -X POST "http://localhost:8090/v1/fluree/upsert?ledger=mydb:main" \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "@graph": [
      {
        "@id": "ex:alice",
        "@type": "schema:Person",
        "schema:name": "Alice Smith",
        "schema:email": "alice.smith@example.org",
        "schema:age": 31
      }
    ]
  }'
```

This replaces existing values for the predicates included in the payload (for `ex:alice`, those are `@type`, `schema:name`, `schema:email`, `schema:age`).

### Upsert Behavior

**First transaction** (entity doesn't exist):
- Creates the entity with all specified properties

**Subsequent transactions** (entity exists):
- Retracts existing values for the supplied predicates
- Asserts new values for those predicates
- Leaves other predicates unchanged

### Use Cases for Upsert

Good for:
- Idempotent transactions (can retry safely)
- Syncing from external systems
- Replacing values for the predicates you supply
- Avoiding duplicate checks

Not good for:
- Conditional/targeted changes (use UPDATE instead)

## Update: Targeted Changes (WHERE/DELETE/INSERT)

For targeted changes to existing data, use the UPDATE pattern with WHERE/DELETE/INSERT.

### Basic Update

```bash
curl -X POST http://localhost:8090/v1/fluree/update?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "where": [
      { "@id": "ex:alice", "schema:age": "?oldAge" }
    ],
    "delete": [
      { "@id": "ex:alice", "schema:age": "?oldAge" }
    ],
    "insert": [
      { "@id": "ex:alice", "schema:age": 32 }
    ]
  }'
```

This pattern:
1. **WHERE**: Finds matching data
2. **DELETE**: Retracts specific triples
3. **INSERT**: Asserts new triples

### Update Multiple Properties

```bash
curl -X POST http://localhost:8090/v1/fluree/update?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "where": [
      { "@id": "ex:alice", "schema:name": "?name", "schema:email": "?email" }
    ],
    "delete": [
      { "@id": "ex:alice", "schema:name": "?name", "schema:email": "?email" }
    ],
    "insert": [
      { "@id": "ex:alice", "schema:name": "Alice Johnson", "schema:email": "alice.j@example.org" }
    ]
  }'
```

### Conditional Update

Only update if condition is met:

```bash
curl -X POST http://localhost:8090/v1/fluree/update?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "where": [
      { "@id": "ex:alice", "schema:age": "?age" },
      { "@id": "?age", "@type": "xsd:integer" }
    ],
    "delete": [
      { "@id": "ex:alice", "schema:age": "?age" }
    ],
    "insert": [
      { "@id": "ex:alice", "schema:age": { "@value": "32", "@type": "xsd:integer" } }
    ]
  }'
```

### Adding Properties (Not Replacing)

To add a property without removing existing ones, use INSERT only:

```bash
curl -X POST http://localhost:8090/v1/fluree/update?ledger=mydb:main \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "insert": [
      { "@id": "ex:alice", "schema:telephone": "+1-555-0100" }
    ]
  }'
```

This adds the telephone property without affecting other properties.

## Data Types

Fluree supports various data types through JSON-LD typing:

### Strings (Default)

```json
{
  "@id": "ex:alice",
  "schema:name": "Alice"
}
```

### Numbers

```json
{
  "@id": "ex:alice",
  "schema:age": 30,
  "schema:height": 1.68
}
```

### Booleans

```json
{
  "@id": "ex:alice",
  "schema:active": true
}
```

### Dates

```json
{
  "@id": "ex:alice",
  "schema:birthDate": {
    "@value": "1994-05-15",
    "@type": "xsd:date"
  }
}
```

### Timestamps

```json
{
  "@id": "ex:alice",
  "schema:lastLogin": {
    "@value": "2024-01-22T10:30:00Z",
    "@type": "xsd:dateTime"
  }
}
```

### References (Links to Other Entities)

```json
{
  "@id": "ex:alice",
  "schema:worksFor": { "@id": "ex:company-a" }
}
```

## Transaction Receipts

Every successful transaction returns a receipt with metadata:

```json
{
  "t": 5,
  "timestamp": "2024-01-22T10:30:00.000Z",
  "commit_id": "bafybeig...commitT5",
  "flakes_added": 3,
  "flakes_retracted": 2,
  "previous_commit_id": "bafybeig...commitT4"
}
```

Key fields:
- **t**: Transaction time (monotonically increasing)
- **timestamp**: ISO 8601 timestamp
- **commit_id**: Content-addressed identifier (CID) for the commit
- **flakes_added**: Number of triples added
- **flakes_retracted**: Number of triples removed
- **previous_commit_id**: ContentId of the previous commit (present when t > 1)

See [Commit Receipts](https://labs.flur.ee/docs/db/transactions/commit-receipts) for details.

## Error Handling

### Transaction Errors

If a transaction fails, you'll receive an error response:

```json
{
  "error": "TransactionError",
  "message": "Invalid IRI: not a valid URI",
  "code": "INVALID_IRI"
}
```

Common errors:
- **INVALID_IRI**: Malformed IRIs
- **PARSE_ERROR**: Invalid JSON-LD syntax
- **TYPE_ERROR**: Type mismatch
- **CONSTRAINT_VIOLATION**: Data constraint violated

### Validation

Transactions are validated before being applied:
- JSON-LD syntax must be valid
- IRIs must be well-formed
- Types must be compatible
- References must resolve (optional)

## Best Practices

### 1. Use Appropriate Transaction Pattern

- **Insert**: New entities, no duplication concerns
- **Upsert**: Idempotent transactions, predicate-level replacement for supplied predicates
- **Update**: Targeted changes, preserve other properties

### 2. Choose Meaningful IRIs

Good:
```json
{"@id": "ex:user-12345"}
{"@id": "ex:product-widget-2024"}
```

Bad:
```json
{"@id": "ex:1"}
{"@id": "ex:thing"}
```

### 3. Use Consistent Namespaces

Define a clear namespace strategy:

```json
{
  "@context": {
    "app": "https://myapp.com/ns/",
    "schema": "http://schema.org/",
    "xsd": "http://www.w3.org/2001/XMLSchema#"
  }
}
```

### 4. Batch Related Changes

Include related entities in a single transaction:

```json
{
  "@graph": [
    {"@id": "ex:order-123", "ex:customer": {"@id": "ex:alice"}},
    {"@id": "ex:order-123", "ex:product": {"@id": "ex:widget"}},
    {"@id": "ex:order-123", "ex:quantity": 5}
  ]
}
```

### 5. Use Typed Literals

Be explicit about types for dates, numbers, etc.:

```json
{
  "@id": "ex:alice",
  "ex:birthDate": {
    "@value": "1994-05-15",
    "@type": "xsd:date"
  }
}
```

## Transaction Size Limits

Be aware of transaction size constraints:

- **Recommended**: < 1000 triples per transaction
- **Maximum**: Configurable (default: 10,000 triples)
- **Large imports**: Use batch processing

See [Indexing Side-Effects](https://labs.flur.ee/docs/db/transactions/indexing-side-effects) for performance considerations.

## Next Steps

Now that you can write data:

1. [Query Data](https://labs.flur.ee/docs/db/getting-started/quickstart-query) - Learn how to retrieve your data
2. [Transactions Overview](https://labs.flur.ee/docs/db/transactions/overview) - Detailed transaction documentation
3. [JSON-LD Context](https://labs.flur.ee/docs/db/concepts/iri-and-context) - Understanding @context

## Related Documentation

- [Insert](https://labs.flur.ee/docs/db/transactions/insert) - Detailed insert documentation
- [Upsert](https://labs.flur.ee/docs/db/transactions/upsert) - Detailed upsert documentation
- [Update](https://labs.flur.ee/docs/db/transactions/update-where-delete-insert) - Detailed update documentation
- [Cypher](https://labs.flur.ee/docs/db/query/cypher) - openCypher reads and writes
- [Data Types](https://labs.flur.ee/docs/db/concepts/datatypes) - Comprehensive type system guide


## Quickstart: Query Data

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/quickstart-query

This guide introduces you to querying data in Fluree using JSON-LD Query, SPARQL, and Cypher.

## Prerequisites

- Fluree server running with data (complete previous quickstarts)
- Sample data from [Write Data](https://labs.flur.ee/docs/db/getting-started/quickstart-write) guide

## Query Languages

Fluree supports three query languages:

- **JSON-LD Query**: Fluree's native JSON-based query language
- **SPARQL**: W3C standard RDF query language
- **Cypher**: openCypher for property-graph reads and writes

All three run against the same data and engine. This guide focuses on JSON-LD Query and SPARQL; see [Cypher](#cypher) below and the [Cypher reference](https://labs.flur.ee/docs/db/query/cypher) for the property-graph surface.

## JSON-LD Query

### Basic SELECT Query

Retrieve all person names:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?name"],
    "where": [
      { "@id": "?person", "schema:name": "?name" }
    ]
  }'
```

Response:

```json
[
  { "name": "Alice" },
  { "name": "Bob" },
  { "name": "Carol" }
]
```

### Query Multiple Properties

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?name", "?email"],
    "where": [
      { "@id": "?person", "schema:name": "?name" },
      { "@id": "?person", "schema:email": "?email" }
    ]
  }'
```

Response:

```json
[
  { "name": "Alice", "email": "alice@example.org" },
  { "name": "Bob", "email": "bob@example.org" },
  { "name": "Carol", "email": "carol@example.org" }
]
```

### Filter Results

Query with a specific filter:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?name", "?age"],
    "where": [
      { "@id": "?person", "schema:name": "?name" },
      { "@id": "?person", "schema:age": "?age" }
    ],
    "filter": "?age > 25"
  }'
```

### Query Specific Entity

Query a specific entity by IRI:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?name", "?email", "?age"],
    "where": [
      { "@id": "ex:alice", "schema:name": "?name" },
      { "@id": "ex:alice", "schema:email": "?email" },
      { "@id": "ex:alice", "schema:age": "?age" }
    ]
  }'
```

### Query with Relationships

Follow links between entities:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main",
    "select": ["?personName", "?companyName"],
    "where": [
      { "@id": "?person", "schema:name": "?personName" },
      { "@id": "?person", "schema:worksFor": "?company" },
      { "@id": "?company", "schema:name": "?companyName" }
    ]
  }'
```

Response:

```json
[
  { "personName": "Alice", "companyName": "Acme Corp" }
]
```

## SPARQL

### Basic SELECT Query

The same queries in SPARQL syntax:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT ?name
    FROM <mydb:main>
    WHERE {
      ?person schema:name ?name .
    }
  '
```

### Query Multiple Properties

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT ?name ?email
    FROM <mydb:main>
    WHERE {
      ?person schema:name ?name .
      ?person schema:email ?email .
    }
  '
```

### Filter Results

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT ?name ?age
    FROM <mydb:main>
    WHERE {
      ?person schema:name ?name .
      ?person schema:age ?age .
      FILTER (?age > 25)
    }
  '
```

### Query with Relationships

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT ?personName ?companyName
    FROM <mydb:main>
    WHERE {
      ?person schema:name ?personName .
      ?person schema:worksFor ?company .
      ?company schema:name ?companyName .
    }
  '
```

## Cypher

Cypher targets a ledger directly (no `FROM`/dataset clause) — send the statement
with `Content-Type: application/cypher` to the ledger-scoped query endpoint:

```bash
curl -X POST http://localhost:8090/v1/fluree/query/mydb:main \
  -H "Content-Type: application/cypher" \
  --data 'MATCH (person:Person) RETURN person.name'
```

Results default to `cypher-json` (a Neo4j-compatible tabular envelope); request
RDF JSON-LD with `Accept: application/ld+json`. Cypher is read/write — `CREATE` /
`MERGE` / `SET` / `DELETE` statements go to the ledger-scoped `/update` endpoint.
See the [Cypher reference](https://labs.flur.ee/docs/db/query/cypher) and the
[Cypher cookbook](https://labs.flur.ee/docs/db/guides/cookbook-cypher) for the full surface.

## Time Travel Queries

Query historical data using time specifiers.

### Query at Specific Transaction

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main@t:1",
    "select": ["?name"],
    "where": [
      { "@id": "?person", "schema:name": "?name" }
    ]
  }'
```

This shows data as it existed at transaction 1.

### Query at ISO Timestamp

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main@time:2024-01-22T10:00:00Z",
    "select": ["?name"],
    "where": [
      { "@id": "?person", "schema:name": "?name" }
    ]
  }'
```

### Query at Commit ContentId

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": "mydb:main@commit:bafybeig...",
    "select": ["?name"],
    "where": [
      { "@id": "?person", "schema:name": "?name" }
    ]
  }'
```

See [Time Travel](https://labs.flur.ee/docs/db/concepts/time-travel) for comprehensive details.

## History Queries

Track changes to entities over time by specifying a time range in the `from` clause.

### Entity History

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "from": "mydb:main@t:1",
    "to": "mydb:main@t:latest",
    "select": ["?name", "?age", "?t", "?op"],
    "where": [
      { "@id": "ex:alice", "schema:name": { "@value": "?name", "@t": "?t", "@op": "?op" } },
      { "@id": "ex:alice", "schema:age": "?age" }
    ],
    "orderBy": "?t"
  }'
```

The `@t` annotation binds the transaction time, and `@op` binds the operation type as a boolean (`true` = assert, `false` = retract).

Response shows all changes:

```json
[
  ["Alice", 30, 1, true],
  ["Alice", 30, 5, false],
  ["Alicia", 31, 5, true]
]
```

### Property History

Track changes to a specific property:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "ex": "http://example.org/ns/",
      "schema": "http://schema.org/"
    },
    "from": "mydb:main@t:1",
    "to": "mydb:main@t:latest",
    "select": ["?age", "?t", "?op"],
    "where": [
      { "@id": "ex:alice", "schema:age": { "@value": "?age", "@t": "?t", "@op": "?op" } }
    ],
    "orderBy": "?t"
  }'
```

Response:

```json
[
  [30, 1, true],
  [30, 5, false],
  [31, 5, true]
]
```

## Aggregations

### Count Results

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT (COUNT(?person) AS ?count)
    FROM <mydb:main>
    WHERE {
      ?person schema:name ?name .
    }
  '
```

### Average, Min, Max

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/sparql-query" \
  -d '
    PREFIX schema: <http://schema.org/>
    
    SELECT (AVG(?age) AS ?avgAge) (MIN(?age) AS ?minAge) (MAX(?age) AS ?maxAge)
    FROM <mydb:main>
    WHERE {
      ?person schema:age ?age .
    }
  '
```

## Limiting Results

### JSON-LD Query Limit

```json
{
  "@context": {
    "schema": "http://schema.org/"
  },
  "from": "mydb:main",
  "select": ["?name"],
  "where": [
    { "@id": "?person", "schema:name": "?name" }
  ],
  "limit": 10
}
```

### SPARQL Limit and Offset

```sparql
PREFIX schema: <http://schema.org/>

SELECT ?name
FROM <mydb:main>
WHERE {
  ?person schema:name ?name .
}
ORDER BY ?name
LIMIT 10
OFFSET 20
```

## Ordering Results

### JSON-LD Query Order

```json
{
  "@context": {
    "schema": "http://schema.org/"
  },
  "from": "mydb:main",
  "select": ["?name", "?age"],
  "where": [
    { "@id": "?person", "schema:name": "?name" },
    { "@id": "?person", "schema:age": "?age" }
  ],
  "orderBy": ["?age"]
}
```

### SPARQL Order

```sparql
PREFIX schema: <http://schema.org/>

SELECT ?name ?age
FROM <mydb:main>
WHERE {
  ?person schema:name ?name .
  ?person schema:age ?age .
}
ORDER BY DESC(?age)
```

## Multi-Ledger Queries

Query across multiple ledgers:

```bash
curl -X POST http://localhost:8090/v1/fluree/query \
  -H "Content-Type: application/json" \
  -d '{
    "@context": {
      "schema": "http://schema.org/"
    },
    "from": ["customers:main", "orders:main"],
    "select": ["?customerName", "?orderTotal"],
    "where": [
      { "@id": "?customer", "schema:name": "?customerName" },
      { "@id": "?order", "schema:customer": "?customer" },
      { "@id": "?order", "schema:totalPrice": "?orderTotal" }
    ]
  }'
```

See [Datasets](https://labs.flur.ee/docs/db/query/datasets) for comprehensive multi-graph query documentation.

## Understanding Query Results

### JSON-LD Query Results

Results are returned as an array of objects:

```json
[
  { "name": "Alice", "age": 30 },
  { "name": "Bob", "age": 25 }
]
```

### SPARQL Results

SPARQL returns results in SPARQL JSON format:

```json
{
  "head": {
    "vars": ["name", "age"]
  },
  "results": {
    "bindings": [
      {
        "name": { "type": "literal", "value": "Alice" },
        "age": { "type": "literal", "value": "30", "datatype": "http://www.w3.org/2001/XMLSchema#integer" }
      },
      {
        "name": { "type": "literal", "value": "Bob" },
        "age": { "type": "literal", "value": "25", "datatype": "http://www.w3.org/2001/XMLSchema#integer" }
      }
    ]
  }
}
```

See [Output Formats](https://labs.flur.ee/docs/db/query/output-formats) for format details.

## Query Performance Tips

### 1. Use Specific Patterns

More specific patterns are faster:

Good:
```json
{ "@id": "ex:alice", "schema:name": "?name" }
```

Less efficient:
```json
{ "@id": "?person", "?predicate": "?value" }
```

### 2. Filter Early

Apply filters in WHERE clauses when possible:

```json
"where": [
  { "@id": "?person", "schema:age": "?age" }
],
"filter": "?age > 25"
```

### 3. Limit Results

Always use LIMIT for large result sets:

```json
"limit": 100
```

### 4. Use Indexes

Queries leverage automatic indexes. Structure queries to take advantage:
- Subject-based lookups are fast
- Predicate-based lookups are fast
- Complex graph patterns may be slower

See [Explain Plans](https://labs.flur.ee/docs/db/query/explain) for query optimization.

## Common Query Patterns

### Find All Types

```sparql
SELECT DISTINCT ?type
FROM <mydb:main>
WHERE {
  ?entity a ?type .
}
```

### Find All Predicates

```sparql
SELECT DISTINCT ?predicate
FROM <mydb:main>
WHERE {
  ?subject ?predicate ?object .
}
```

### Inverse Relationships

Find what points to an entity:

```sparql
SELECT ?source ?predicate
FROM <mydb:main>
WHERE {
  ?source ?predicate <http://example.org/ns/alice> .
}
```

### Optional Properties

Query with optional values:

```sparql
PREFIX schema: <http://schema.org/>

SELECT ?name ?email ?phone
FROM <mydb:main>
WHERE {
  ?person schema:name ?name .
  ?person schema:email ?email .
  OPTIONAL { ?person schema:telephone ?phone }
}
```

## Error Handling

### Query Errors

Common query errors:

```json
{
  "error": "QueryError",
  "message": "Ledger not found: mydb:main",
  "code": "LEDGER_NOT_FOUND"
}
```

```json
{
  "error": "ParseError",
  "message": "Invalid JSON-LD: unexpected token",
  "code": "PARSE_ERROR"
}
```

### Empty Results

Empty result set (not an error):

```json
[]
```

## Next Steps

Now that you can query data:

1. **Learn Advanced Queries**: Explore [JSON-LD Query](https://labs.flur.ee/docs/db/query/jsonld-query), [SPARQL](https://labs.flur.ee/docs/db/query/sparql), and [Cypher](https://labs.flur.ee/docs/db/query/cypher) documentation
2. **Understand Time Travel**: Deep dive into [Time Travel](https://labs.flur.ee/docs/db/concepts/time-travel)
3. **Optimize Queries**: Read about [Explain Plans](https://labs.flur.ee/docs/db/query/explain)
4. **Multi-Graph Queries**: Learn about [Datasets](https://labs.flur.ee/docs/db/query/datasets)

## Related Documentation

- [JSON-LD Query](https://labs.flur.ee/docs/db/query/jsonld-query) - Complete JSON-LD query reference
- [SPARQL](https://labs.flur.ee/docs/db/query/sparql) - Complete SPARQL reference
- [Cypher](https://labs.flur.ee/docs/db/query/cypher) - openCypher reads and writes
- [Output Formats](https://labs.flur.ee/docs/db/query/output-formats) - Result format options
- [Time Travel](https://labs.flur.ee/docs/db/concepts/time-travel) - Historical queries
- [Graph Crawl](https://labs.flur.ee/docs/db/query/graph-crawl) - Graph traversal


## Tutorial: Building a Knowledge Base with Fluree

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/tutorial-end-to-end

This tutorial walks through a realistic scenario — building a team knowledge base — to show how Fluree's differentiating features work together. You'll use time travel, full-text search, branching, and access control in a single workflow.

**Time:** ~20 minutes
**Prerequisites:** Fluree installed and running (`fluree init && fluree server run`)

## Step 1: Create the ledger and add data

```bash
fluree create knowledge-base
fluree use knowledge-base
```

Insert some articles and team members:

```bash
fluree insert '
@prefix schema: <http://schema.org/> .
@prefix ex:     <http://example.org/> .
@prefix f:      <https://ns.flur.ee/db#> .

ex:alice  a schema:Person ;
  schema:name "Alice Chen" ;
  ex:role     "engineer" ;
  ex:team     "platform" .

ex:bob  a schema:Person ;
  schema:name "Bob Martinez" ;
  ex:role     "engineer" ;
  ex:team     "platform" .

ex:carol  a schema:Person ;
  schema:name "Carol White" ;
  ex:role     "manager" ;
  ex:team     "platform" .

ex:doc1  a ex:Article ;
  schema:name    "Deployment Runbook" ;
  schema:author  ex:alice ;
  ex:team        "platform" ;
  ex:visibility  "internal" ;
  ex:content     "Step 1: Check the monitoring dashboard. Step 2: Run the database migration script. Step 3: Deploy the new container image using the CI pipeline."^^f:fullText .

ex:doc2  a ex:Article ;
  schema:name    "Onboarding Guide" ;
  schema:author  ex:bob ;
  ex:team        "platform" ;
  ex:visibility  "public" ;
  ex:content     "Welcome to the platform team. This guide covers setting up your development environment, accessing the database, and deploying your first service."^^f:fullText .

ex:doc3  a ex:Article ;
  schema:name    "Incident Response Playbook" ;
  schema:author  ex:carol ;
  ex:team        "platform" ;
  ex:visibility  "confidential" ;
  ex:content     "During a production incident, the on-call engineer should check database health, review recent deployments, and escalate if the service is not recovering within 15 minutes."^^f:fullText .
'
```

Verify the data is there:

```bash
fluree query --format table 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?title ?author_name ?visibility
WHERE {
  ?doc a ex:Article ;
       schema:name ?title ;
       schema:author ?author ;
       ex:visibility ?visibility .
  ?author schema:name ?author_name .
}
ORDER BY ?title'
```

```
┌─────────────────────────────┬───────────────┬──────────────┐
│ title                       │ author_name   │ visibility   │
├─────────────────────────────┼───────────────┼──────────────┤
│ Deployment Runbook          │ Alice Chen    │ internal     │
│ Incident Response Playbook  │ Carol White   │ confidential │
│ Onboarding Guide            │ Bob Martinez  │ public       │
└─────────────────────────────┴───────────────┴──────────────┘
```

This is transaction `t=1`. Remember this — we'll come back to it.

## Step 2: Full-text search

The article content was inserted with the `@fulltext` datatype, so it's automatically indexed for BM25 relevance scoring. Search for articles about deployments:

```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?title", "?score"],
  "where": [
    {
      "@id": "?doc", "@type": "ex:Article",
      "ex:content": "?content",
      "schema:name": "?title"
    },
    ["bind", "?score", "(fulltext ?content \"database deployment\")"],
    ["filter", "(> ?score 0)"]
  ],
  "orderBy": [["desc", "?score"]],
  "limit": 10
}'
```

Results are ranked by relevance — the deployment runbook and incident playbook both mention deployments and databases, while the onboarding guide has a weaker match.

You can combine search with graph filters. Find only **public** articles matching the search:

```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?title", "?score"],
  "where": [
    {
      "@id": "?doc", "@type": "ex:Article",
      "ex:content": "?content",
      "schema:name": "?title",
      "ex:visibility": "public"
    },
    ["bind", "?score", "(fulltext ?content \"database deployment\")"],
    ["filter", "(> ?score 0)"]
  ],
  "orderBy": [["desc", "?score"]]
}'
```

Search results participate in standard graph joins and filters — no separate search service needed.

## Step 3: Update data and use time travel

Let's update the deployment runbook with a new version:

```bash
fluree update 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>
PREFIX f: <https://ns.flur.ee/db#>

DELETE { ex:doc1 ex:content ?old }
INSERT { ex:doc1 ex:content "Step 1: Check the monitoring dashboard and verify all health checks pass. Step 2: Run the database migration script with --dry-run first. Step 3: Deploy the new container image. Step 4: Verify the deployment in staging before promoting to production."^^f:fullText }
WHERE  { ex:doc1 ex:content ?old }'
```

Now query the **current** version:

```bash
fluree query 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?content WHERE { ex:doc1 ex:content ?content }'
```

And query the **original** version using time travel:

```bash
fluree query --at 1 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?content WHERE { ex:doc1 ex:content ?content }'
```

The `--at 1` flag queries the data as it was after transaction 1 — before the update. Both versions coexist in the same ledger.

You can also see the full change history:

```bash
fluree history 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?content ?t ?op WHERE { ex:doc1 ex:content ?content }'
```

Each result includes `?t` (the transaction number) and `?op` (whether it was an assertion or retraction). You see the original content retracted and the new content asserted, with exact timestamps.

**Use cases this enables:**
- **Audit trails** — Who changed what, when?
- **Rollback** — See what the data looked like before a bad change
- **Compliance** — Prove what was known at a specific point in time
- **Debugging** — Compare current vs. historical state to find when a problem was introduced

## Step 4: Branch to experiment safely

Suppose you want to reorganize the knowledge base — maybe split articles into categories, or restructure ownership. You don't want to affect the production data while experimenting.

Create a branch:

```bash
fluree branch create reorganize
fluree use knowledge-base:reorganize
```

On the branch, add categories and reorganize:

```bash
fluree insert '
@prefix schema: <http://schema.org/> .
@prefix ex:     <http://example.org/> .

ex:doc1 ex:category "operations" .
ex:doc2 ex:category "onboarding" .
ex:doc3 ex:category "operations" .
'
```

```bash
fluree update 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

DELETE { ex:doc3 ex:visibility "confidential" }
INSERT { ex:doc3 ex:visibility "internal" }
WHERE  { ex:doc3 ex:visibility "confidential" }'
```

Verify the branch has the changes:

```bash
fluree query --format table 'PREFIX schema: <http://schema.org/>
PREFIX ex: <http://example.org/>

SELECT ?title ?category ?visibility
WHERE {
  ?doc a ex:Article ;
       schema:name ?title ;
       ex:category ?category ;
       ex:visibility ?visibility .
}
ORDER BY ?title'
```

The main branch is untouched:

```bash
fluree query --ledger knowledge-base:main 'PREFIX ex: <http://example.org/>
PREFIX schema: <http://schema.org/>

SELECT ?title ?visibility
WHERE {
  ?doc a ex:Article ; schema:name ?title ; ex:visibility ?visibility .
  OPTIONAL { ?doc ex:category ?cat }
  FILTER(!BOUND(?cat))
}
ORDER BY ?title'
```

No categories on main — the branch is fully isolated.

When you're happy with the changes, merge back:

```bash
fluree branch merge reorganize
fluree use knowledge-base:main
```

Now main has the categories and the visibility change. The branch can continue for future experiments or be dropped:

```bash
fluree branch drop reorganize
```

## Step 5: Add access control

Now let's add policies so that different users see different articles based on their role and team.

Insert policies into the ledger:

```bash
fluree insert '{
  "@context": {
    "f": "https://ns.flur.ee/db#",
    "ex": "http://example.org/",
    "schema": "http://schema.org/"
  },
  "@graph": [
    {
      "@id": "ex:policy-public-read",
      "@type": "f:Policy",
      "f:action": "query",
      "f:resource": { "ex:visibility": "public" },
      "f:allow": true
    },
    {
      "@id": "ex:policy-team-internal",
      "@type": "f:Policy",
      "f:subject": "?user",
      "f:action": "query",
      "f:resource": {
        "ex:visibility": "internal",
        "ex:team": "?team"
      },
      "f:condition": [
        { "@id": "?user", "ex:team": "?team" }
      ],
      "f:allow": true
    },
    {
      "@id": "ex:policy-manager-confidential",
      "@type": "f:Policy",
      "f:subject": "?user",
      "f:action": "query",
      "f:resource": {
        "ex:visibility": "confidential",
        "ex:team": "?team"
      },
      "f:condition": [
        { "@id": "?user", "ex:team": "?team", "ex:role": "manager" }
      ],
      "f:allow": true
    }
  ]
}'
```

These three policies create a layered access model:

1. **Public articles** — visible to everyone
2. **Internal articles** — visible only to members of the same team
3. **Confidential articles** — visible only to managers on the same team

Query as Alice (engineer, platform team):

```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?title", "?visibility"],
  "where": [
    {"@id": "?doc", "@type": "ex:Article", "schema:name": "?title", "ex:visibility": "?visibility"}
  ],
  "opts": {"identity": "ex:alice"}
}'
```

Alice sees the public onboarding guide and the internal deployment runbook, but **not** the confidential incident playbook.

Query as Carol (manager, platform team):

```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?title", "?visibility"],
  "where": [
    {"@id": "?doc", "@type": "ex:Article", "schema:name": "?title", "ex:visibility": "?visibility"}
  ],
  "opts": {"identity": "ex:carol"}
}'
```

Carol sees all three articles, including the confidential one.

The same query, different results, based on who's asking — enforced by the database, not application code.

## Step 6: Combine everything

Now let's use all features together. Carol (manager) searches for articles about "database" in the knowledge base, with policies applied, and compares what she sees now vs. what existed before the reorganization:

**Current state, with policy:**
```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "select": ["?title", "?visibility", "?score"],
  "where": [
    {
      "@id": "?doc", "@type": "ex:Article",
      "ex:content": "?content",
      "schema:name": "?title",
      "ex:visibility": "?visibility"
    },
    ["bind", "?score", "(fulltext ?content \"database\")"],
    ["filter", "(> ?score 0)"]
  ],
  "orderBy": [["desc", "?score"]],
  "opts": {"identity": "ex:carol"}
}'
```

**Historical state (before runbook was updated):**
```bash
fluree query '{
  "@context": {"schema": "http://schema.org/", "ex": "http://example.org/"},
  "from": "knowledge-base:main@t:1",
  "select": ["?title", "?score"],
  "where": [
    {
      "@id": "?doc", "@type": "ex:Article",
      "ex:content": "?content",
      "schema:name": "?title"
    },
    ["bind", "?score", "(fulltext ?content \"database\")"],
    ["filter", "(> ?score 0)"]
  ],
  "orderBy": [["desc", "?score"]]
}'
```

In a single database, you've combined:
- **Full-text search** — ranked by relevance
- **Access control** — Carol sees confidential articles, others wouldn't
- **Time travel** — compare current vs. historical content
- **Branching** — experimented with reorganization without risk

## What you've learned

| Feature | What it gave you |
|---|---|
| **Ledger** | A single place for all knowledge base data |
| **Full-text search** | BM25-ranked article discovery, integrated in queries |
| **Time travel** | Complete audit trail, historical comparison, rollback capability |
| **Branching** | Safe experimentation without affecting production |
| **Policies** | Automatic access control based on team and role |
| **SPARQL + JSON-LD + Cypher** | Three query languages accessing the same engine |

## Next steps

- [Search Cookbook](https://labs.flur.ee/docs/db/guides/cookbook-search) — Deeper guide to BM25 and vector search
- [Time Travel Cookbook](https://labs.flur.ee/docs/db/guides/cookbook-time-travel) — Practical time-travel patterns
- [Branching Cookbook](https://labs.flur.ee/docs/db/guides/cookbook-branching) — Branch/merge workflows
- [Policies Cookbook](https://labs.flur.ee/docs/db/guides/cookbook-policies) — Access control patterns
- [SPARQL Reference](https://labs.flur.ee/docs/db/query/sparql) — Full SPARQL 1.1 reference
- [JSON-LD Query](https://labs.flur.ee/docs/db/query/jsonld-query) — Fluree's native query language


## Using Fluree as a Rust Library

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/rust-api

This guide shows how to use Fluree programmatically in your Rust applications by depending on the `fluree-db-api` crate.

## Overview

Fluree can be embedded directly in Rust applications, giving you a powerful graph database without requiring a separate server process. This is ideal for:

- Desktop applications
- Edge computing
- Embedded systems
- Library/framework integration
- Testing and development

## Add Dependency

Add Fluree to your `Cargo.toml`:

```toml
[dependencies]
fluree-db-api = { path = "../fluree-db-api" }
tokio = { version = "1", features = ["full"] }
```

Note: Replace `path` with version when published to crates.io:
```toml
[dependencies]
fluree-db-api = "0.1"
```

### Features

Available feature flags:

- `native` (default) - File storage support
- `credential` (default in server/CLI) - DID/JWS/VerifiableCredential support for signed queries and transactions
- `shacl` (default in server/CLI) - SHACL constraint validation
- `iceberg` (default in server/CLI) - Apache Iceberg/R2RML graph source support
- `sql` (default in server/CLI) - SQL graph sources (R2RML over a Trino-protocol endpoint); implies `iceberg`
- `delta` (default in server/CLI) - Delta Lake graph sources (R2RML over Delta tables); implies `iceberg`
- `graphql` (default in server/CLI) - GraphQL over the schema derived from a ledger's data; implies `shacl`
- `aws` - AWS-backed storage support (S3, storage-backed nameservice). Enables `FlureeBuilder::s3()` and S3-based JSON-LD configs.
- `ipfs` - IPFS-backed storage via Kubo HTTP RPC
- `vector` - Embedded vector similarity search (HNSW indexes via usearch)
- `search-remote-client` - Remote search service client (HTTP client for remote BM25 and vector search services)
- `aws-testcontainers` - Opt-in LocalStack-backed S3/DynamoDB tests (auto-start via testcontainers)
- `full` - Convenience bundle: `native`, `credential`, `iceberg`, `sql`, `shacl`, `ipfs`, `graphql` (excludes `delta`, `aws`, `vector`, `search-remote-client`)

## Quick Start

### Basic Setup

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Create a memory-backed Fluree instance
    let fluree = FlureeBuilder::memory().build_memory();

    // Create a new ledger
    let ledger = fluree.create_ledger("mydb").await?;

    println!("Ledger created at t={}", ledger.t());

    Ok(())
}
```

### With File Storage

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Use file-backed storage for persistence
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Create a new ledger (or load an existing one)
    let ledger = fluree.create_ledger("mydb").await?;

    // Load an existing ledger by ID (`name:branch`)
    let ledger = fluree.ledger("mydb:main").await?;

    Ok(())
}
```

`build_async()` replays the storage's write-ahead log without blocking the async runtime.
`build()` builds the same instance from synchronous code that has entered a Tokio runtime (for example with `Runtime::enter`), replaying the log on the calling thread.

### One instance per storage directory

An instance owns its storage directory. Share it within a process by cloning it: `Fluree` is
cheap to clone, and clones share its caches, its per-ledger write locks and its indexer. Two
instances on one directory, in one process or two, are not coordinated: each serves its own
cached state, and both index and sweep the same files.

`with_storage_lock()` makes that a startup error. The instance locks the directory, and building
another one on it, in any process, fails with `ApiError::StorageInUse`. The lock lasts as long as
the instance: it is released once the instance and every clone of it are dropped, or when the
process exits, however it exits. A filesystem that cannot lock fails the build; see
[One process per directory](https://labs.flur.ee/docs/db/operations/storage#one-process-per-directory).

```rust
let fluree = FlureeBuilder::file("./data").with_storage_lock().build_async().await?;
```

Where code that opens storage cannot easily pass an instance around, `SharedFluree::open` returns
the one instance this process keeps for a directory, opening it, with the lock, on first use.
Handles dereference to `Fluree`. They own its lifecycle: the instance shuts down once the last
handle is closed or dropped, `disconnect()` on it does nothing, and a `Fluree` cloned from a handle
keeps the directory locked until that clone is dropped too:

```rust
use fluree_db_api::{SharedFluree, SharedOptions};

let fluree = SharedFluree::open("./data", SharedOptions::default()).await?;
fluree.create_ledger("mydb").await?;
fluree.close().await;
```

To use one directory from several processes, run a [server](https://labs.flur.ee/docs/db/operations/running-fluree) on it.

### Cache budgets

`cache_max_mb` sizes the in-memory cache of decoded index data. The default is a tiered fraction of
system RAM. `query_result_cache_max_mb` is a separate ceiling, in addition to it, for answers kept
by the [query result cache](https://labs.flur.ee/docs/db/query/result-cache). It defaults to 10% of `cache_max_mb`, and
nothing is allocated for it until a query opts in. `0` disables result caching.

```rust
let fluree = FlureeBuilder::file("./data")
    .cache_max_mb(4096)
    .query_result_cache_max_mb(200)
    .build_async()
    .await?;
```

A query opts in with `.result_cache(&outcome)` on `GraphDb::query()`, or with
`"opts": {"cache": true}` in JSON-LD.

### Bulk import (high throughput)

For initial ledger bootstraps (large Turtle or JSON-LD datasets), Fluree exposes a bulk import
pipeline as a first-class Rust API:

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // `chunks_dir` can be:
    // - a directory containing *.ttl, *.trig, or *.jsonld files (sorted lexicographically), OR
    // - a single .ttl or .jsonld file.
    // Directories must contain a single format (no mixing Turtle and JSON-LD).
    let result = fluree
        .create("dblp:main")
        .import("./chunks_dir")
        .threads(8)          // parallel TTL parsing; commits remain serial
        .build_index(true)   // write an index root and publish it
        .publish_every(50)   // nameservice checkpoints during long imports (0 disables)
        .cleanup(true)       // delete tmp import files on success
        .execute()
        .await?;

    println!(
        "import complete: t={}, flakes={}, root={:?}",
        result.t, result.flake_count, result.root_id
    );

    // Query normally after import (loads the published V2 root from CAS).
    let view = fluree.view("dblp:main").await?;
    let qr = fluree
        .query(&view, "SELECT * WHERE { ?s ?p ?o } LIMIT 10")
        .await?;
    println!("rows={}", qr.batches.iter().map(|b| b.len()).sum::<usize>());

    Ok(())
}
```

**Temporary files:** the bulk import pipeline uses a session-scoped `tmp_import/` directory and
removes it only on full success (unless `.cleanup(false)` is set). On failure, it keeps the
session directory and logs its path for debugging.

#### Into a new named graph of an existing ledger

`import_into_graph` runs the same pipeline into a named graph the ledger does not have yet, and
takes the same tuning options:

```rust
let result = fluree
    .import_into_graph("mydb:main", "http://example.org/graph/products")
    .import("./products")
    .threads(8)
    .execute()
    .await?;

let graph = result.graph.expect("a graph import names its graph");
println!(
    "<{}> is g_id {}, commits t={}..{}",
    graph.iri, graph.g_id, graph.base_t + 1, result.t
);
```

- Every statement lands in the named graph, and the import's commits follow the ledger's head,
  so a full reindex from the commits rebuilds the same ledger.
- An IRI or string the ledger already holds keeps its id, so the graph joins with the rest of
  the ledger. The new graph's index is built in bulk and spliced into the ledger's existing
  index; nothing else is rebuilt.
- A ledger with commits after its index is indexed first. Writes through the same `Fluree`'s
  cached ledger wait until the import publishes; reads go on against the head it started from.
  A writer that does not share that cache (another process, another `Fluree`, or one built
  without ledger caching) is not held: if it commits first, the import fails with nothing
  published.
- `ImportError::PublishedWithoutIndex { t, .. }` is the one failure after which the import is in
  the ledger: its commits are published through `t` and its index is not. Queries read the graph
  from those commits until an index covers them, which `Fluree::reindex` builds. A future
  dropped while the import publishes can leave the ledger the same way.
- The source holds default-graph data (Turtle, N-Triples, JSON-LD, JSONL/NDJSON). An existing
  graph, `urn:default`, the system graphs, TriG / N-Quads, and JSON-LD that names graphs of its
  own are refused with `ImportError::Refused` (or `ImportError::Invalid`), with nothing written.
- `result.has_annotations` reports a graph with statement annotations: the ledger's annotation
  index is then set aside, and annotation queries read by scan until `Fluree::reindex`.

### With S3 Storage

Requires `fluree-db-api` feature `aws` and standard AWS credential/region configuration.

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // LocalStack: an endpoint override is enough.
    let fluree = FlureeBuilder::s3("my-bucket", "http://localhost:4566")
        .build_client()
        .await?;

    // MinIO also needs path-style addressing: without it the SDK emits
    // `http://my-bucket.minio:9000/key`, which a plain MinIO (no wildcard
    // bucket-subdomain DNS) rejects.
    let _minio = FlureeBuilder::s3("my-bucket", "http://minio:9000")
        .s3_force_path_style(true)
        .build_client()
        .await?;

    let ledger = fluree.create_ledger("mydb").await?;
    println!("Ledger created at t={}", ledger.t());
    Ok(())
}
```

**S3 Express One Zone note:** for directory buckets (`--x-s3` suffix), omit `s3Endpoint` in JSON-LD config and let the SDK handle it.

## Connection Configuration (JSON-LD)

For advanced configuration (tiered storage, address identifier routing, DynamoDB nameservice,
environment variable indirection), use `FlureeBuilder::from_json_ld()` to parse a JSON-LD config
and build from it. The typed builder methods (`build()`, `build_memory()`, `build_s3()`) and
the type-erased `build_client()` all share the same underlying construction logic.

See also: [JSON-LD connection configuration reference](https://labs.flur.ee/docs/db/reference/connection-config-jsonld).

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let cfg = json!({
        "@context": {"@base": "https://ns.flur.ee/config/connection/", "@vocab": "https://ns.flur.ee/system#"},
        "@graph": [
            {"@id": "s3Index", "@type": "Storage", "s3Bucket": {"envVar": "INDEX_BUCKET"}, "s3Endpoint": {"envVar": "S3_ENDPOINT"}},
            {"@id": "conn", "@type": "Connection", "indexStorage": {"@id": "s3Index"}}
        ]
    });
    // from_json_ld parses the config into builder settings; build_client() constructs
    // a type-erased FlureeClient suitable for runtime-determined backends.
    let fluree = FlureeBuilder::from_json_ld(&cfg)?.build_client().await?;
    Ok(())
}
```

### Environment variables (`ConfigurationValue`)

Any string/number config value can be specified directly or via a `ConfigurationValue` object:

```json
{
  "s3Bucket": { "envVar": "FLUREE_S3_BUCKET", "defaultVal": "my-bucket" },
  "cacheMaxMb": { "envVar": "FLUREE_CACHE_MAX_MB", "defaultVal": "1024" }
}
```

### Supported JSON-LD fields (Rust)

Connection node:
- `parallelism`
- `cacheMaxMb`
- `queryResultCacheMaxMb` (see [Cache budgets](#cache-budgets))
- `indexStorage`, `commitStorage`
- `primaryPublisher` (publisher node)
- `defaults.indexing`: `reindexMinBytes`, `reindexMaxBytes`, `indexingEnabled`, and the [index retention](#index-retention) settings `gcMinTimeMins`, `maxOldIndexes`, `gcHardMaxOldIndexes`

Storage node:
- Any storage: `AES256Key`, or `AES256Keys` + `AES256CurrentKey` (mutually exclusive; put the key on `indexStorage`)
- File: `filePath`, `durability`
- S3: `s3Bucket`, `s3Prefix`, `s3Endpoint`, `s3ReadTimeoutMs`, `s3WriteTimeoutMs`, `s3ListTimeoutMs`, `s3MaxRetries`, `s3RetryBaseDelayMs`, `s3RetryMaxDelayMs`, `s3MaxConcurrentRequests`

Publisher node:
- DynamoDB nameservice: `dynamodbTable`, `dynamodbRegion`, `dynamodbEndpoint`, `dynamodbTimeoutMs`
- Storage-backed nameservice: `storage` (reference to a Storage node)

## Core Patterns

### The Graph API

The primary API revolves around `fluree.graph(graph_ref)`, which returns a lazy `Graph` handle.
No I/O occurs until a terminal method (`.execute()`, `.commit()`, `.load()`) is called.

Use `graph(...).query()` when the target may be a mapped graph source as well as a native ledger. If the query body itself carries `"from"` / `FROM`, use `query_from()`. The lower-level `fluree.db(...)` + `fluree.query(&view, ...)` path is for materialized native ledger snapshots, not graph source aliases.

**When I/O happens:**
- `.execute()` / `.execute_formatted()` / `.execute_tracked()` — loads the graph from storage, then runs the query (each call reloads)
- `.commit()` — loads the cached ledger handle, stages, and commits
- `.stage()` — loads the ledger and stages without committing
- `.load()` — loads the graph once, returning a `GraphSnapshot` for repeated queries without reloading

```rust
// Lazy query — loads graph and executes in one step
let result = fluree.graph("mydb:main")
    .query()
    .sparql("SELECT ?name WHERE { ?s <http://schema.org/name> ?name }")
    .execute()
    .await?;

// Lazy transact + commit
let out = fluree.graph("mydb:main")
    .transact()
    .insert(&data)
    .commit()
    .await?;

// Materialize for reuse (avoids reloading on each query)
let db = fluree.graph("mydb:main").load().await?;
let r1 = db.query().sparql("SELECT ...").execute().await?;
let r2 = db.query().jsonld(&q).execute().await?;

// Time travel
let result = fluree.graph_at("mydb:main", TimeSpec::AtT(42))
    .query()
    .jsonld(&q)
    .execute()
    .await?;
```

### Insert Data

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    // Insert JSON-LD data using the Graph API
    let data = json!({
        "@context": {
            "schema": "http://schema.org/",
            "ex": "http://example.org/ns/"
        },
        "@graph": [
            {
                "@id": "ex:alice",
                "@type": "schema:Person",
                "schema:name": "Alice",
                "schema:email": "alice@example.org",
                "schema:age": 30
            },
            {
                "@id": "ex:bob",
                "@type": "schema:Person",
                "schema:name": "Bob",
                "schema:email": "bob@example.org",
                "schema:age": 25
            }
        ]
    });

    let result = fluree.graph("mydb:main")
        .transact()
        .insert(&data)
        .commit()
        .await?;

    println!("Transaction committed");

    Ok(())
}
```

### Query Data with JSON-LD Query

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    // Insert test data first (see Insert Data above)
    // ...

    // Query with JSON-LD using the lazy Graph API
    let query = json!({
        "select": ["?name", "?email"],
        "where": [
            { "@id": "?person", "@type": "schema:Person" },
            { "@id": "?person", "schema:name": "?name" },
            { "@id": "?person", "schema:email": "?email" },
            { "@id": "?person", "schema:age": "?age" }
        ],
        "filter": "?age > 25"
    });

    let result = fluree.graph("mydb:main")
        .query()
        .jsonld(&query)
        .execute_formatted()
        .await?;

    println!("Query results: {}",
        serde_json::to_string_pretty(&result)?);

    Ok(())
}
```

### Query Data with SPARQL

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    // Insert test data first (see Insert Data above)
    // ...

    // Query with SPARQL using the lazy Graph API
    let sparql = r#"
        PREFIX schema: <http://schema.org/>

        SELECT ?name ?email
        WHERE {
            ?person a schema:Person .
            ?person schema:name ?name .
            ?person schema:email ?email .
            ?person schema:age ?age .
            FILTER (?age > 25)
        }
        ORDER BY ?name
    "#;

    let result = fluree.graph("mydb:main")
        .query()
        .sparql(sparql)
        .execute_formatted()
        .await?;

    println!("Results: {}",
        serde_json::to_string_pretty(&result)?);

    Ok(())
}
```

#### Parameters

`params` binds variables to values: each named variable (`?name` or `$name`,
the same variable) is replaced by its value wherever it appears — subqueries,
`OPTIONAL`, `FILTER`s and update templates included — before the query is
planned, so it runs exactly as if the value had been written inline. Values
take the JSON-LD forms: a JSON string, number or boolean; `{"@id": iri}`;
`{"@value": v, "@type": datatype}` (`"@type": "@id"` reads `v` as an IRI);
`{"@value": s, "@language": tag}`; and an embedding vector as its numbers,
`{"@value": [0.1, 0.2], "@type": "https://ns.flur.ee/db#embeddingVector"}`.
IRIs are full IRIs — neither the query's `PREFIX`es nor a `@context` apply. A
blank node is the `_:fdb-…` id a query returned for a stored node; any other
label is refused, since written inline it would be a variable and match every
node.

```rust
let params = json!({ "name": "Alice", "min": 21 });
let result = fluree.graph("mydb:main")
    .query()
    .sparql("PREFIX schema: <http://schema.org/>
             SELECT ?person WHERE { ?person schema:name $name ; schema:age ?age FILTER(?age > $min) }")
    .params(params.as_object().unwrap().clone())
    .execute_formatted()
    .await?;
```

A projected parameter stays a column holding its value. A parameter the query
never mentions is an error — its misspelt variable would otherwise be unbound
and match everything — as is one the query assigns itself (`BIND`, `VALUES`,
`AS`), one used inside a remote `SERVICE` (whose body is sent as written), and
any parameter on a JSON-LD query. Without parameters nothing changes: the
query is not rewritten at all.

The same parameters go on `QueryExecutionOptions::with_params`,
`Fluree::explain_sparql_with_params`, a transact builder's
`sparql_update_with_params(sparql, &params)`, and
`TxnOperation::SparqlUpdate(sparql, Some(params))`.

### Streaming Query Results (NDJSON)

The buffered `.query()` paths above collect the whole result set into a
`QueryResult` before returning. For large result sets or long-running queries,
the streaming API instead formats each batch as a newline-delimited JSON
("NDJSON") record and pushes it through an `mpsc` channel, so rows reach the
consumer incrementally and bytes keep flowing while the query runs. This is the
in-process producer behind the server's
[`/stream/query` endpoint](https://labs.flur.ee/docs/db/api/streaming-query); see that reference for
the record protocol (`head` → `row`* → terminal `end`/`error`) and the stable
error codes.

The flow is two steps, mirroring the server handler:

1. **`plan_stream_query(&db, &input)`** — parse, validate, and plan. Parse
   errors and shapes the streaming path does not support (ASK,
   CONSTRUCT/DESCRIBE, `selectOne`, JSON-LD hydration, history) surface here,
   *before* any record is emitted — so a caller can map them to a clean error
   up front.
2. **`run_stream_query(ledger, plan, tracker, options, tx)`** — typically
   `tokio::spawn`ed. It sends a `head` record, then one `row` record per result
   row as batches arrive, then exactly one terminal record (`end` on success,
   `error` on failure). It takes an owned `LedgerState` so it can outlive the
   call site. Backpressure is natural: a full channel suspends the producer.

```rust
use fluree_db_api::{
    FlureeBuilder, GraphDb, OwnedStreamQuery, QueryExecutionOptions, Result, Tracker,
    TrackingOptions,
};
use bytes::Bytes;
use std::sync::Arc;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = Arc::new(FlureeBuilder::file("./data").build_async().await?);

    // Plan against a borrowed GraphDb, then move the owned LedgerState into the
    // spawned producer (GraphDb borrows the state, so plan first).
    let ledger_state = fluree
        .ledger_cached("mydb:main")
        .await?
        .snapshot()
        .await
        .to_ledger_state();

    let input = OwnedStreamQuery::Sparql(
        "SELECT ?s ?name WHERE { ?s <http://schema.org/name> ?name }".to_string(),
    );
    // JSON-LD form: OwnedStreamQuery::JsonLd(serde_json::Value)

    let plan = {
        let db = GraphDb::from_ledger_state(&ledger_state);
        fluree.plan_stream_query(&db, &input).await? // 4xx-worthy errors surface here
    };

    let (tx, mut rx) = mpsc::channel::<Bytes>(64);
    let producer = Arc::clone(&fluree);
    tokio::spawn(async move {
        producer
            .run_stream_query(
                ledger_state,
                plan,
                Tracker::new(TrackingOptions::all_enabled()), // time + fuel on records
                QueryExecutionOptions::new(),                 // optional cancellation handle
                tx,
            )
            .await;
    });

    // Each `Bytes` is one (or more) NDJSON line(s). Treat the absence of a
    // terminal `end`/`error` record as a truncated stream, not success.
    while let Some(chunk) = rx.recv().await {
        print!("{}", String::from_utf8_lossy(&chunk));
    }
    Ok(())
}
```

> **Heartbeats** are injected by the *transport* layer (the HTTP server), not by
> `run_stream_query`. An embedder consuming the channel directly gets only
> `head`/`row`/terminal records; add your own keep-alive if you tunnel the
> stream through an idle-timing proxy.

**Multi-ledger / `from` / policy queries** use the dataset variant. Build a
policy-wrapped `DataSetDb` first, then plan and run against it:

```rust
// JSON-LD with `from`/`fromNamed`, multi-ledger, or an identity/policy input:
let dataset = fluree.build_stream_dataset(&query_json).await?;
let input = OwnedStreamQuery::JsonLd(query_json);
let plan = fluree.plan_stream_query_dataset(&dataset, &input).await?;
// fluree.run_stream_query_dataset(dataset, plan, tracker, options, tx).await;
```

`build_stream_dataset` reads the spec from the query body's `from`/`fromNamed`;
`build_stream_dataset_from_spec` / `build_stream_dataset_for_sparql` take an
explicit `DatasetSpec` or extract one from SPARQL `FROM`/`FROM NAMED`. Per-graph
policy rides on the runtime dataset and is enforced identically to the buffered
dataset path.

### Update Data

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    // Update using WHERE/DELETE/INSERT pattern
    let update = json!({
        "@context": { "schema": "http://schema.org/" },
        "where": [
            { "@id": "?person", "schema:name": "Alice" },
            { "@id": "?person", "schema:age": "?oldAge" }
        ],
        "delete": [
            { "@id": "?person", "schema:age": "?oldAge" }
        ],
        "insert": [
            { "@id": "?person", "schema:age": 31 }
        ]
    });

    let result = fluree.graph("mydb:main")
        .transact()
        .update(&update)
        .commit()
        .await?;

    println!("Updated successfully");

    Ok(())
}
```

### SPARQL UPDATE

Use SPARQL UPDATE syntax for transactions:

```rust
use fluree_db_api::{
    FlureeBuilder, Result,
    parse_sparql, lower_sparql_update, NamespaceRegistry, TxnOpts,
    SparqlQueryBody,
};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Get a cached ledger handle
    let handle = fluree.ledger_cached("mydb:main").await?;

    // SPARQL UPDATE string
    let sparql = r#"
        PREFIX ex: <http://example.org/ns/>

        DELETE {
            ?person ex:age ?oldAge .
        }
        INSERT {
            ?person ex:age 31 .
        }
        WHERE {
            ?person ex:name "Alice" .
            ?person ex:age ?oldAge .
        }
    "#;

    // Parse SPARQL
    let parse_output = parse_sparql(sparql);
    if parse_output.has_errors() {
        // Handle parse errors
        for diag in parse_output.diagnostics.iter().filter(|d| d.is_error()) {
            eprintln!("Parse error: {}", diag.message);
        }
        return Err(fluree_db_api::ApiError::Internal("SPARQL parse error".into()));
    }

    let ast = parse_output.ast.unwrap();

    // Extract the UPDATE operation
    let update_op = match &ast.body {
        SparqlQueryBody::Update(op) => op,
        _ => return Err(fluree_db_api::ApiError::Internal("Expected SPARQL UPDATE".into())),
    };

    // Get namespace registry from the ledger
    let snapshot = handle.snapshot().await;
    let mut ns = NamespaceRegistry::from_db(&snapshot.snapshot);

    // Lower SPARQL UPDATE to Txn IR
    let txn = lower_sparql_update(update_op, &ast.prologue, &mut ns, TxnOpts::default())?;

    // Execute the transaction
    let result = fluree.stage(&handle)
        .txn(txn)
        .execute()
        .await?;

    println!("SPARQL UPDATE committed at t={}", result.receipt.t);

    Ok(())
}
```

**Supported SPARQL UPDATE operations:**
- `INSERT DATA` - Insert ground triples
- `DELETE DATA` - Delete specific triples
- `DELETE WHERE` - Delete matching patterns
- `DELETE/INSERT WHERE` - Full update with patterns

See [SPARQL UPDATE](https://labs.flur.ee/docs/db/query/sparql#sparql-update) for syntax details.

### Stage and Preview Changes

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    let data = json!({
        "@context": {"ex": "http://example.org/ns/"},
        "@graph": [{"@id": "ex:alice", "ex:name": "Alice"}]
    });

    // Stage without committing
    let staged = fluree.graph("mydb:main")
        .transact()
        .insert(&data)
        .stage()
        .await?;

    // Query the staged state to preview changes
    let preview_query = json!({
        "select": ["?name"],
        "where": [{"@id": "ex:alice", "ex:name": "?name"}]
    });

    let preview = staged.query()
        .jsonld(&preview_query)
        .execute()
        .await?;

    println!("Preview: {} rows", preview.row_count());

    Ok(())
}
```

`StagedGraph` is a read-only preview of one transaction. To stage several
writes, read between them, and commit them as one commit, use a
`Transaction`.

### Multi-Write Transactions

`Fluree::begin_transaction` opens a transaction at the ledger's current head.
Each `stage` applies its write over the ones before it (an update's `WHERE`
sees an earlier insert), and is validated as it is staged: a write that fails
to parse, is denied by policy, or violates SHACL returns an error and is left
out, and the transaction carries on without it. Which shapes, uniqueness
constraints and config apply is read once, from the state the transaction
began on: a write that changes them does not change how a later write in the
same transaction is checked. A model ledger the config names is read at the
head the transaction's first lookup of it found. The config checks (a setting group split across
graphs, a second value for a single-valued setting) run once, on what the
transaction commits. `db()` reads the staged state.
`commit` writes everything as one commit, keeping only the net change: a fact
one write adds and a later one removes is not committed. If another commit
lands first, a transaction that was never read is re-based over it when they
touched different subjects, and otherwise staged again on the new head, under
the policy the ledger has then. One that was read through `db()` fails with
`TransactError::CommitConflict` instead — its writes may rest on what it read —
and should be run again. A write that fails to stage doesn't count as a read:
if what you stage next depends on that error, read the transaction through
`db()` first.

```rust
use fluree_db_api::{CommitOpts, FlureeBuilder, Result, TransactionOptions, TxnOperation};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    fluree.create_ledger("mydb").await?;

    let mut txn = fluree
        .begin_transaction("mydb:main", TransactionOptions::default())
        .await?;
    txn.stage(TxnOperation::Insert(json!({
        "@context": {"ex": "http://example.org/ns/"},
        "@id": "ex:alice", "ex:age": 30
    })))
    .await?;
    txn.stage(TxnOperation::SparqlUpdate(
        "PREFIX ex: <http://example.org/ns/> \
         DELETE { ex:alice ex:age ?a } INSERT { ex:alice ex:age ?b } \
         WHERE { ex:alice ex:age ?a BIND(?a + 1 AS ?b) }"
            .into(),
        None, // parameters
    ))
    .await?;

    let staged = txn.db().await?; // alice is 31 here; the ledger is unchanged
    let result = txn.commit(CommitOpts::default()).await?;
    println!("committed t={}", result.receipt.t);
    Ok(())
}
```

`TransactionOptions` sets what the transaction runs under: `governance`
checks every write against that policy; `tracking` accounts for fuel, time and
policy across every operation, so a `max_fuel` limit bounds the transaction as
a whole and the tally comes back with the commit; `index_config` sets the
novelty limits the commit is held to. `stage_cypher(query, params)` stages a
Cypher write alongside the other operations — its `MATCH` and `MERGE` see
them — and returns the rows of its `RETURN`, if any. Receiving those rows
counts as reading the transaction, as `db()` does. Dropping a `Transaction`
discards it.

`savepoint()` marks the operations staged so far, and `rollback_to(savepoint)`
discards the ones after it. The operations before the savepoint are staged
again, so values computed as they stage — `NOW()`, `UUID()`, `STRUUID()`, a
SPARQL update's blank nodes — can change; JSON-LD, Turtle and Cypher blank
nodes keep their identities. Rolling back past a savepoint discards it, and
returning to it later is an error.

`commit` commits on the process's own write path, as Bolt's explicit
transactions do, so transactions are for local-commit deployments: a Raft or
peer host must not offer them to its clients.

### Export Data

Stream ledger data as Turtle, N-Triples, N-Quads, TriG, or JSON-LD using the builder API:

```rust
use fluree_db_api::{FlureeBuilder, Result};
use fluree_db_api::export::ExportFormat;
use std::io::BufWriter;
use std::fs::File;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Export as Turtle to a file
    let file = File::create("backup.ttl").unwrap();
    let mut writer = BufWriter::new(file);
    let stats = fluree.export("mydb")
        .format(ExportFormat::Turtle)
        .write_to(&mut writer)
        .await?;
    println!("Exported {} triples", stats.triples_written);

    // Export as JSON-LD with custom prefixes
    let mut buf = Vec::new();
    let stats = fluree.export("mydb")
        .format(ExportFormat::JsonLd)
        .context(&serde_json::json!({"ex": "http://example.org/"}))
        .write_to(&mut buf)
        .await?;

    // Export all graphs as N-Quads (dataset export)
    let stats = fluree.export("mydb")
        .format(ExportFormat::NQuads)
        .all_graphs()
        .to_stdout()
        .await?;

    Ok(())
}
```

All formats stream directly from the binary SPOT index. Memory usage is O(leaflet size) for line-oriented formats and O(largest subject) for JSON-LD, regardless of dataset size.

**Builder methods:**
- `.format(ExportFormat)` — output format (default: Turtle)
- `.all_graphs()` — include all named graphs including system graphs (requires TriG or NQuads)
- `.graph("iri")` — export a specific named graph by IRI
- `.as_of(TimeSpec)` — time-travel export (`AtT`, `AtTime`/`AtRecorded` for the event and recorded time axes, `AtCommit`, or `Latest`; parse a user-supplied string with `TimeSpec::parse_at`)
- `.context(&json)` — override prefix map (default: ledger's context from nameservice)
- `.write_to(&mut writer)` — stream to any `Write` sink
- `.to_stdout()` — convenience for stdout output

See also: [CLI export](https://labs.flur.ee/docs/db/cli/export) for command-line usage.

### Materialize for Reuse

When you need to run multiple queries against the same snapshot, materialize a `GraphSnapshot` once:

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Load once, query many times
    let db = fluree.graph("mydb:main").load().await?;

    let r1 = db.query()
        .sparql("SELECT ?name WHERE { ?s <http://schema.org/name> ?name }")
        .execute()
        .await?;

    let q2 = json!({
        "select": ["?email"],
        "where": [{"@id": "?s", "schema:email": "?email"}]
    });
    let r2 = db.query()
        .jsonld(&q2)
        .execute()
        .await?;

    // Access the underlying view if needed
    let view = db.view();

    Ok(())
}
```

## Advanced Usage

### Ledger Caching

Ledger caching is enabled by default on all `FlureeBuilder` constructors. When caching is active, `fluree.ledger()` returns a cached handle and subsequent calls avoid reloading from storage:

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Caching is on by default — no extra call needed
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // First call loads from storage
    let ledger = fluree.ledger("mydb:main").await?;

    // Subsequent calls return cached state (fast)
    let ledger2 = fluree.ledger("mydb:main").await?;

    Ok(())
}
```

To **disable** caching (e.g., for a CLI tool that runs once and exits):

```rust
let fluree = FlureeBuilder::file("./data")
    .without_ledger_caching()
    .build_async()
    .await?;
```

#### Disconnecting Ledgers

Use `disconnect_ledger` to release a ledger from the connection cache. This forces a fresh load on the next access:

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Load and use ledger
    let ledger = fluree.ledger("mydb:main").await?;
    println!("Ledger at t={}", ledger.t());

    // Release cached state
    fluree.disconnect_ledger("mydb:main").await;

    // Next access will reload from storage
    let ledger = fluree.ledger("mydb:main").await?;

    Ok(())
}
```

**When to use `disconnect_ledger`:**

- **Force fresh load**: After external changes to the ledger (e.g., another process wrote data)
- **Free memory**: Release memory for ledgers you no longer need
- **Clean shutdown**: Release resources before application exit
- **Testing**: Reset state between test cases

**Note:** If caching is disabled (via `without_ledger_caching()` on builder), `disconnect_ledger` is a no-op.

#### Checking Ledger Existence

Use `ledger_exists` to check if a ledger is registered in the nameservice without loading it:

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Check if ledger exists (lightweight nameservice lookup)
    if fluree.ledger_exists("mydb:main").await? {
        // Ledger exists - load it
        let ledger = fluree.ledger("mydb:main").await?;
        println!("Loaded ledger at t={}", ledger.t());
    } else {
        // Ledger doesn't exist - create it
        let ledger = fluree.create_ledger("mydb").await?;
        println!("Created new ledger");
    }

    Ok(())
}
```

**When to use `ledger_exists`:**

- **Conditional create-or-load**: Check before deciding whether to create or load
- **Validation**: Verify ledger IDs exist before operations
- **Defensive programming**: Avoid `NotFound` errors in application logic

**Performance note:** This is a lightweight check that only queries the nameservice - it does NOT load the ledger data, indexes, or novelty. Much faster than attempting to load and catching `NotFound` errors.

#### Dropping Ledgers

`drop_ledger` operates on the **whole ledger** — every branch under a ledger
name, including retracted-but-not-purged branches and the cross-branch
`@shared/dicts/` namespace. Use `drop_branch` to remove a single branch.

```rust
use fluree_db_api::{FlureeBuilder, DropMode, DropStatus, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Soft drop: retract every branch in the nameservice, preserve artifacts
    let report = fluree.drop_ledger("mydb", DropMode::Soft).await?;
    match report.status {
        DropStatus::Dropped => println!("Ledger dropped"),
        DropStatus::AlreadyRetracted => println!("Already dropped"),
        DropStatus::NotFound => println!("Ledger not found"),
    }

    // Hard drop: delete artifacts for every branch + @shared/dicts (IRREVERSIBLE)
    let report = fluree.drop_ledger("mydb", DropMode::Hard).await?;
    println!(
        "Dropped {} branches; deleted {} storage artifacts",
        report.branch_reports.len(),
        report.artifacts_deleted
    );
    for br in &report.branch_reports {
        println!("  - {} ({:?})", br.ledger_id, br.status);
    }

    Ok(())
}
```

**Accepted inputs:**

| Input | Behavior |
|-------|----------|
| `"mydb"` | Whole-ledger drop (canonical form). |
| `"mydb:<branch>"` (including `"mydb:main"`) | **Rejected** with a `400`/`ApiError::Http`. Use `drop_branch("mydb", "<branch>")` to drop a single branch. |

**Drop Modes:**

| Mode | Behavior | Reversible |
|------|----------|------------|
| `DropMode::Soft` (default) | Marks every branch retracted in the nameservice; artifacts remain | Partially; requires administrative recovery |
| `DropMode::Hard` | Deletes managed storage artifacts for every branch, wipes `@shared/dicts/`, and purges nameservice records so the name can be reused | **No** for deleted artifacts |

**Drop Sequence:**

1. Parses input (rejects non-default branch suffixes).
2. Snapshots every NsRecord under the ledger name via `all_records` (so retracted branches are included). Enumeration failures propagate as `Err`.
3. Sorts branches leaf-first via `source_branch` parent pointers — partial failures leave orphan parents, never dangling children.
4. Cancels and waits for pending background indexing on each branch.
5. For each branch: deletes per-branch artifacts (commit/txn/index/config) in hard mode; retracts (soft) or drops the NS record (hard) using the parent-aware path so surviving parents have accurate child counts.
6. Hard mode: wipes `{ledger_name}/@shared/dicts/` after every branch is gone.
7. Disconnects each branch from the ledger cache.

**Report shape:**

`DropReport.ledger_id` is the bare ledger name. `artifacts_deleted` and
`warnings` aggregate across branches plus the shared cleanup;
`branch_reports: Vec<BranchDropReport>` carries per-branch detail in
leaf-first order — useful for surfacing partial failures.

**`drop_branch` for single branches:**

```rust
let report = fluree.drop_branch("mydb", "dev").await?;
```

`drop_branch` refuses the **root** branch (any branch whose
`source_branch.is_none()`). `"main"` carries no special meaning; a ledger
created with a different initial branch (e.g. `mydb:trunk`) has that
branch as its root and is the one that `drop_branch` will refuse.

**Idempotency:**

Safe to call multiple times:
- Returns `DropStatus::AlreadyRetracted` when every branch was already retracted (hard mode still runs cleanup for these).
- Returns `DropStatus::NotFound` without touching storage when no NsRecord exists for the ledger name. Orphaned storage with no nameservice pointer is not swept by `drop_ledger`; that's a separate admin concern.
- On a real per-branch nameservice failure, returns `ApiError::Drop` without touching parents or `@shared/dicts/`. Each step is idempotent under partial progress, so retry is safe.

**Warnings:**

```rust
let report = fluree.drop_ledger("mydb", DropMode::Hard).await?;
for warning in &report.warnings {
    eprintln!("Warning: {warning}");
}
for br in &report.branch_reports {
    for warning in &br.warnings {
        eprintln!("  {}: {warning}", br.ledger_id);
    }
}
```

#### Refreshing Cached Ledgers

Use `refresh` to poll-check whether a cached ledger is stale and update it if needed.
`refresh` returns a `RefreshResult` containing the ledger's `t` after the operation
and what action was taken:

```rust
use fluree_db_api::{FlureeBuilder, NotifyResult, RefreshOpts, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Load ledger into cache
    let _ledger = fluree.ledger_cached("mydb:main").await?;

    // Later, check if the cached state is still fresh
    match fluree.refresh("mydb:main", Default::default()).await? {
        Some(r) => {
            println!("Ledger at t={}, action: {:?}", r.t, r.action);
            match r.action {
                NotifyResult::Current => println!("Already up to date"),
                NotifyResult::Reloaded => println!("Reloaded from storage"),
                NotifyResult::IndexUpdated => println!("Index was updated"),
                NotifyResult::CommitsApplied { count } => {
                    println!("{count} commits applied incrementally");
                }
                NotifyResult::NotLoaded => println!("Not in cache"),
            }
        }
        None => println!("Ledger not found in nameservice"),
    }

    Ok(())
}
```

**Key behaviors:**

- **Does NOT cold-load**: If the ledger isn't already cached, returns `NotLoaded` (no-op)
- **Returns `None`**: If the ledger doesn't exist in the nameservice
- **Alias resolution**: Supports short aliases (`mydb` resolves to `mydb:main`)
- **No-op without caching**: If caching is disabled, returns `NotLoaded`
- **Returns `t`**: The `RefreshResult.t` field always tells you the ledger's current transaction time

**When to use `refresh`:**

- **Poll-based freshness**: When you can't use SSE events but need periodic freshness checks
- **Before critical reads**: Ensure you have the latest state before important queries
- **Peer mode**: Check if the local cache is behind the transaction server

**`refresh` vs `disconnect_ledger`:**

| Behavior | `refresh` | `disconnect_ledger` |
|----------|-----------|---------------------|
| Checks freshness | Yes | No |
| Updates in place | Yes | No (forces full reload on next access) |
| Handles not-cached | Returns `NotLoaded` | No-op |
| Use case | Poll-based updates | Force full reload |

#### Read-After-Write Consistency

A writer always reads its own writes: a commit through the embedded API
(`insert`/`update`/`transact`, or the `transact(...).execute()` builder) updates the
in-process ledger cache, so a subsequent `fluree.db(...)` / `query(...)` in the same
process sees it. Across processes, the engine is **eventually consistent**: when one
process writes data and another queries it, that other process may not yet see the
latest commit until its cache catches up. The `t` value returned from a transaction
is the key to bridging this cross-process gap.

Pass `RefreshOpts { min_t: Some(t) }` to `refresh()` to assert that the cached
ledger has reached at least that transaction time. If it hasn't after pulling the
latest state from the nameservice, `refresh` returns `ApiError::AwaitTNotReached`
with both the `requested` and `current` `t` values. Your code owns retry timing
and timeout policy.

**Basic usage:**

```rust
use fluree_db_api::{FlureeBuilder, RefreshOpts, ApiError, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;
    let handle = fluree.ledger_cached("mydb:main").await?;

    // Transaction returns the commit's t value
    let receipt = fluree.stage(&handle)
        .insert(&json!({"@id": "ex:item", "ex:count": 42}))
        .commit()
        .await?;
    let committed_t = receipt.t;

    // Ensure the cache reflects at least this t before querying
    let opts = RefreshOpts { min_t: Some(committed_t) };
    let result = fluree.refresh("mydb:main", opts).await?;
    // result.unwrap().t >= committed_t is guaranteed here

    Ok(())
}
```

**Serverless / Lambda pattern (retry with backoff):**

In a serverless environment, the transacting process and the querying process may be
different Lambda invocations. The querying invocation receives `t` (e.g., via an
event payload or API parameter) and must wait for that commit to be visible:

```rust
use fluree_db_api::{RefreshOpts, ApiError};
use std::time::{Duration, Instant};

async fn wait_for_t(
    fluree: &Fluree<impl Storage, impl NameService>,
    ledger_id: &str,
    min_t: i64,
    timeout: Duration,
) -> Result<i64, ApiError> {
    let deadline = Instant::now() + timeout;
    let opts = RefreshOpts { min_t: Some(min_t) };

    loop {
        match fluree.refresh(ledger_id, opts.clone()).await {
            Ok(Some(r)) => return Ok(r.t),   // reached min_t
            Ok(None) => return Err(ApiError::NotFound(
                format!("ledger {ledger_id} not in nameservice"),
            )),
            Err(ApiError::AwaitTNotReached { current, .. }) => {
                if Instant::now() >= deadline {
                    return Err(ApiError::AwaitTNotReached {
                        requested: min_t,
                        current,
                    });
                }
                // Back off before retrying
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            Err(e) => return Err(e),
        }
    }
}
```

**How it works internally:**

1. **Fast path**: If the cached `t` already satisfies `min_t`, returns immediately
   without hitting the nameservice at all.
2. **Pull**: Queries the nameservice for the latest commit/index pointers and applies
   any new commits incrementally (or reloads if the gap is large).
3. **Check**: If `t` is still below `min_t` after the pull, returns
   `ApiError::AwaitTNotReached` so you can retry.

This design keeps retry/timeout policy out of the database layer. Different
deployment contexts (Lambda with 100ms backoff, HTTP handler with 5s deadline,
integration test with immediate assertion) each wrap the same primitive differently.

### Branch Diff (Merge Preview)

`Fluree::merge_preview` returns the rich diff between two branches —
ahead/behind commit summaries, the commit both branches last shared,
conflict keys, and
fast-forward eligibility — **without mutating any state**. It uses the
same primitives as `merge_branch` but skips the publish/copy steps,
making it cheap enough to call on every UI render.

```rust
use fluree_db_api::{FlureeBuilder, MergePreviewOpts, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // ... create ledger, branch, transact on dev, etc.

    // Default: previewing dev → main with the spec defaults
    // (cap each commit list at 500, conflict keys at 200, run conflicts).
    let preview = fluree.merge_preview("mydb", "dev", None).await?;

    println!(
        "{} ahead, {} behind, fast-forward: {}",
        preview.ahead.count, preview.behind.count, preview.fast_forward,
    );

    if preview.fast_forward {
        println!("merge would advance {} → {}", preview.source, preview.target);
    } else {
        println!("merge has {} conflict(s)", preview.conflicts.count);
        for k in &preview.conflicts.keys {
            println!("  - s={} p={}", k.s, k.p);
        }
    }

    // `mergeable` is the answer to "will `merge_branch` go through?": the
    // strategy applies without aborting AND the merged state conforms to
    // the target's SHACL shapes. The preview stages the resolved change
    // set and runs the same validation the merge runs, so the two agree.
    if let Some(v) = &preview.validation {
        if !v.conforms {
            println!("merge would be rejected:\n{}", v.report.as_deref().unwrap_or(""));
        }
    }
    println!("mergeable: {}", preview.mergeable);
    Ok(())
}
```

`validation` is present for every non-fast-forward preview unless
`MergePreviewOpts::include_validation` is `false`, and for a fast-forward
when the target's config enables SHACL or uniqueness, or the commits it
adopts carry config settings (a field the config reader reads, or a write to a config or txn-meta graph of this ledger): the merge checks them
against the target's config as it is before the merge. Any other
fast-forward carries none.

#### Tuning the preview

`merge_preview_with` takes a `MergePreviewOpts` for callers that need
control over response size or want to skip the conflict computation:

```rust
use fluree_db_api::{FlureeBuilder, MergePreviewOpts, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Cheap preview: counts only, no conflict walks.
    let counts = fluree
        .merge_preview_with(
            "mydb",
            "dev",
            Some("main"),
            MergePreviewOpts {
                max_commits: Some(0),       // counts only — no commit summaries
                max_conflict_keys: Some(0),
                include_conflicts: false,
                include_validation: false,  // skip the target-state load + SHACL pass
                ..MergePreviewOpts::default()
            },
        )
        .await?;

    // Direct Rust callers can opt in to **unbounded** results — useful for
    // tooling that needs the full divergence. The HTTP layer always supplies
    // a bound, so this is a Rust-only escape hatch.
    let full = fluree
        .merge_preview_with(
            "mydb",
            "dev",
            None,
            MergePreviewOpts {
                max_commits: None,
                max_conflict_keys: None,
                include_conflicts: true,
                ..MergePreviewOpts::default()
            },
        )
        .await?;

    Ok(())
}
```

#### The aggregate change set (`include_changes`)

For a merge-request "Changes" panel, `include_changes` returns the **net**
set of facts the merge would apply: the source side's commits since the
two branches diverged, folded per fact, each keeping its newest op. A branch with
40 commits that ultimately touches 12 facts reviews as 12 facts, and a fact
the branch created and then deleted shows as the deletion the merge
applies:

```rust
use fluree_db_api::{FlureeBuilder, MergePreviewOpts, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // ... create ledger, branch, transact on dev, etc.

    let preview = fluree
        .merge_preview_with(
            "mydb",
            "dev",
            None,
            MergePreviewOpts {
                include_changes: true,
                // Cap the payload at 100 flakes, cut at subject boundaries.
                // Some(0) = stats-only; None = unbounded (Rust-only escape hatch).
                max_changes: Some(100),
                ..MergePreviewOpts::default()
            },
        )
        .await?;

    let changes = preview.changes.expect("include_changes was set");
    println!(
        "+{} -{} across {} subject(s)",
        changes.assert_count, changes.retract_count, changes.subject_count,
    );
    for entry in &changes.entries {
        println!("{}: +{} -{}", entry.subject, entry.asserts.len(), entry.retracts.len());
    }
    // Page through a large diff: subjects are ordered by full IRI and a
    // truncated page carries a resume cursor.
    if let Some(cursor) = changes.next_cursor {
        let _next_page = fluree
            .merge_preview_with(
                "mydb",
                "dev",
                None,
                MergePreviewOpts {
                    include_changes: true,
                    max_changes: Some(100),
                    changes_after_subject: Some(cursor),
                    ..MergePreviewOpts::default()
                },
            )
            .await?;
    }
    Ok(())
}
```

Exact counts (`assert_count` / `retract_count` / `subject_count`) are never
truncated, so a UI can render "showing X of Y". The change set is
strategy-independent — the raw source-vs-ancestor delta before conflict
resolution; conflicting keys resolve per `conflicts.details`. Each page
re-pays the source-side replay cost (there is no cache), matching what the
merge itself would pay.

#### What the caps do (and don't) control

`max_commits` and `max_conflict_keys` cap the **size of the returned
lists**, not the cost of computing them:

- `BranchDelta::count` on each side reflects the full unbounded
  divergence, computed by walking every commit envelope down to the commit
  the other side holds, regardless of `max_commits`.
- When `include_conflicts: true`, both delta-key walks scan the full
  per-side delta regardless of `max_conflict_keys`.
- When `include_conflict_details: true`, value details are collected only
  for the returned `conflicts.keys` after the `max_conflict_keys` cap is
  applied.
- Set `include_conflicts: false` for a cheap preview on heavily diverged
  branches; you still get accurate `ahead.count` / `behind.count`.

#### Response shape

| Type | Notable fields |
|------|----------------|
| `MergePreview` | `source`, `target`, `ancestor: Option<AncestorRef>`, `ahead`, `behind`, `fast_forward`, `conflicts`, `mergeable` |
| `BranchDelta` | `count` (unbounded), `commits: Vec<CommitSummary>` (newest-first, capped), `truncated` |
| `CommitSummary` | `t`, `commit_id`, `time`, `asserts`, `retracts`, `flake_count`, `message: Option<String>` (extracted from the `f:message` `txn_meta` entry when present) |
| `ConflictSummary` | `count` (unbounded), `keys: Vec<ConflictKey>` (sorted, capped), `truncated`, `strategy`, `details` |
| `ConflictDetail` | `key`, `source_values`, `target_values`, `resolution` (values are the current asserted values at each branch HEAD) |
| `ConflictKey` | `s: Sid`, `p: Sid`, `g: Option<Sid>` |
| `ValidationSummary` | `conforms`, `report: Option<String>` (present only when `conforms` is false; the message the merge would fail with) |

`mergeable` is `false` when the selected strategy would abort on detected
conflicts or, when `validation` is present, when the merged state fails the
target's SHACL shapes. The preview stages the resolved change set and runs
the same validation `merge_branch` runs, so with `include_validation` on
(the default) `mergeable=true` means neither the strategy nor the target's
shapes will reject the merge. Other conditions still apply when the commit
is built, novelty backpressure among them. With it off, `mergeable`
reflects only the conflict/strategy interaction.

All types derive `Serialize` so the response is wire-stable; the HTTP
endpoint at `GET /v1/fluree/merge-preview/{ledger...}` returns the same struct.
See `docs/api/endpoints.md` and `docs/cli/server-integration.md` for the
HTTP contract.

#### Reusable primitives in `fluree-db-core`

The per-commit summary types and DAG walker are factored into core for
reuse outside the merge-preview flow (e.g., git-log-style commit history
viewers, indexer integration). Re-exported from `fluree-db-api`:

- `diff_branches(store, source_head, target_head) -> Result<BranchDiff>`
  — each side's commits since the two branches diverged, by commit
  identity, plus the most recent commit both hold and whether the merge
  fast-forwards.
- `commit_to_summary(commit) -> CommitSummary` — pure function, no I/O.

### Time Travel Queries

```rust
use fluree_db_api::{FlureeBuilder, TimeSpec, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Query at a specific point in time
    let result = fluree.graph_at("mydb:main", TimeSpec::AtT(100))
        .query()
        .sparql("SELECT * WHERE { ?s ?p ?o } LIMIT 10")
        .execute()
        .await?;

    println!("Results at t=100: {:?}", result.row_count());

    Ok(())
}
```

### Multi-Ledger Queries

```rust
use fluree_db_api::{FlureeBuilder, DataSetDb, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Load views from multiple ledgers
    let customers = fluree.view("customers:main").await?;
    let orders = fluree.view("orders:main").await?;

    // Compose a dataset from multiple graphs
    let dataset = DataSetDb::new()
        .with_default(customers)
        .with_named("orders:main", orders);

    // Query across ledgers using the dataset builder
    let query = r#"
        SELECT ?customerName ?orderTotal
        WHERE {
            ?customer schema:name ?customerName .
            ?customer ex:customerId ?cid .

            GRAPH <orders:main> {
                ?order ex:customerId ?cid .
                ?order ex:total ?orderTotal .
            }
        }
    "#;

    let result = dataset.query(&fluree)
        .sparql(query)
        .execute()
        .await?;

    Ok(())
}
```

### Remote Federation

Query ledgers on remote Fluree servers using SPARQL `SERVICE` with the `fluree:remote:` scheme. Register remote connections at build time — each maps a name to a server URL and optional bearer token:

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data")
        .remote_connection(
            "acme",
            "https://acme-fluree.example.com",
            Some("eyJhbG...".to_string()),
        )
        .build_async().await?;

    let db = fluree.view("local-ledger:main").await?;

    // Join local data with a ledger on the remote server
    let result = fluree.query(&db, r#"
        PREFIX ex: <http://example.org/ns/>
        SELECT ?name ?email
        WHERE {
          ?person ex:name ?name .
          SERVICE <fluree:remote:acme/customers:main> {
            ?person ex:email ?email .
          }
        }
    "#).await?;

    Ok(())
}
```

The connection name (`acme`) maps to the server URL. The ledger path (`customers:main`) is appended to form the request URL: `POST https://acme-fluree.example.com/v1/fluree/query/customers:main`. The bearer token is sent as `Authorization: Bearer <token>` on every request.

Multiple ledgers on the same remote server use the same connection name — you register the server once and can query any ledger your token is authorized for.

See [Configuration: Remote connections](https://labs.flur.ee/docs/db/operations/configuration#remote-connections) for details and [SPARQL: Remote Fluree Federation](https://labs.flur.ee/docs/db/query/sparql#remote-fluree-federation) for full query syntax.

### FROM-Driven Queries (Connection Queries)

When the query body itself specifies which ledgers to target (via `"from"` in JSON-LD or `FROM` in SPARQL), use `query_from()`:

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Query where the "from" is embedded in the query body
    let query = json!({
        "from": "mydb:main",
        "select": ["?name"],
        "where": { "@id": "?s", "schema:name": "?name" }
    });

    let result = fluree.query_from()
        .jsonld(&query)
        .execute_formatted()
        .await?;

    // SPARQL with FROM clause
    let result = fluree.query_from()
        .sparql("SELECT ?name FROM <mydb:main> WHERE { ?s <http://schema.org/name> ?name }")
        .execute_formatted()
        .await?;

    Ok(())
}
```

### Background Indexing

Persistent builders (`file`, `s3`, `ipfs`) run a background indexer: once a ledger's novelty passes the soft threshold, it builds and publishes a new index version. The memory builder does not; call `with_indexing()` to enable it. Build inside a tokio runtime.

```rust
use fluree_db_api::{FlureeBuilder, Result, TriggerIndexOptions};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data")
        // Novelty bytes that start an index build, and the hard limit at which
        // writes are rejected until the indexer catches up.
        .with_indexing_thresholds(1_000_000, 512 * 1024 * 1024)
        .build_async()
        .await?;

    fluree.create_ledger("mydb").await?;
    for i in 0..100 {
        let txn = json!({
            "@context": {"ex": "http://example.org/ns/"},
            "@graph": [{"@id": format!("ex:item{}", i), "ex:value": i}]
        });
        fluree.graph("mydb:main").transact().insert(&txn).commit().await?;
    }

    // Wait until everything committed so far is indexed.
    fluree
        .trigger_index("mydb:main", TriggerIndexOptions::default())
        .await?;
    Ok(())
}
```

Call `without_indexing()` when another process, such as a dedicated indexer, maintains the index for the same storage. That needs storage several processes can share: a file storage directory is used by one process at a time ([One process per directory](https://labs.flur.ee/docs/db/operations/storage#one-process-per-directory)).

### Index retention

Each index build supersedes the previous version. New queries read the newest one, but a query already running keeps reading the version it started on, so the indexer keeps superseded versions for a while before it collects them:

- **Age guard** (default 15 minutes): a superseded version is kept this long.
- **Ceiling** (default 10): past this many old versions, a version is collected even inside the age guard.
- **Floor** (default 0): optionally, the newest this many old versions are always kept, whatever their age.

```rust
use fluree_db_api::{FlureeBuilder, IndexerConfig};

// Floor, age guard in minutes, ceiling; `None` keeps a default.
let builder = FlureeBuilder::file("./data").with_gc_settings(None, Some(30), Some(40));

// Or remove the ceiling, so the age guard alone decides:
let config = IndexerConfig::default().with_gc_hard_max_old_indexes(None);
let builder = FlureeBuilder::file("./data").with_indexer_config(config);
```

A query that outlasts its version's retention can lose that version while it reads. Size the age guard from your longest query, and the ceiling from how many versions the ledger publishes during it. See [Index Retention](https://labs.flur.ee/docs/db/indexing-and-search/background-indexing#index-retention) for how the settings combine and how to monitor them.

### BM25 Full-Text Search

```rust
use fluree_db_api::{
    FlureeBuilder, Bm25CreateConfig, Bm25FieldConfig, Result
};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger = fluree.create_ledger("mydb").await?;

    // Insert searchable data and create BM25 index
    // ...

    // Query with full-text search using JSON-LD and the f:graphSource pattern
    let search_query = json!({
        "@context": {
            "schema": "http://schema.org/",
            "f": "https://ns.flur.ee/db#"
        },
        "from": "mydb:main",
        "select": ["?product", "?score", "?name"],
        "where": [
            {
                "f:graphSource": "products-search:main",
                "f:searchText": "laptop",
                "f:searchLimit": 10,
                "f:searchResult": { "f:resultId": "?product", "f:resultScore": "?score" }
            },
            { "@id": "?product", "schema:name": "?name" }
        ],
        "orderBy": [["desc", "?score"]],
        "limit": 10
    });

    let result = fluree.query_from()
        .jsonld(&search_query)
        .execute()
        .await?;

    println!("Found {} matching products", result.row_count());

    Ok(())
}
```

## Configuration

### Builder Options

```rust
use fluree_db_api::{FlureeBuilder, ConnectionConfig, IndexConfig, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let config = ConnectionConfig {
        storage_path: "./data".into(),
        index_config: IndexConfig {
            interval_ms: 5000,
            batch_size: 10,
            memory_mb: 2048,
            threads: 4,
        },
        ..Default::default()
    };

    let fluree = FlureeBuilder::with_config(config).build()?;

    Ok(())
}
```

### Custom Storage Backend

```rust
use fluree_db_api::{
    FlureeBuilder, Storage, StorageWrite, Result
};
use async_trait::async_trait;

// Implement custom storage
struct MyStorage;

#[async_trait]
impl Storage for MyStorage {
    async fn read(&self, address: &str) -> Result<Vec<u8>> {
        // Custom implementation
        todo!()
    }
}

#[async_trait]
impl StorageWrite for MyStorage {
    async fn write(&self, address: &str, data: &[u8]) -> Result<()> {
        // Custom implementation
        todo!()
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let storage = MyStorage;
    let fluree = FlureeBuilder::custom(storage).build()?;

    Ok(())
}
```

If you need full control over both storage and nameservice (e.g., for proxy mode or custom backends), use `build_with()`:

```rust
let storage = MyStorage;
let nameservice = MyNameService;

let fluree = FlureeBuilder::memory()
    .build_with(storage, nameservice);
```

`build_with()` respects the builder's caching configuration — caching is on by default, or call `.without_ledger_caching()` before `build_with()` to disable it.

## Error Handling

```rust
use fluree_db_api::{FlureeBuilder, ApiError, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Create a ledger — handles duplicates gracefully
    match fluree.create_ledger("mydb").await {
        Ok(ledger) => {
            println!("Ledger created at t={}", ledger.t());
        }
        Err(ApiError::LedgerExists(ledger_id)) => {
            println!("Ledger {} already exists, loading...", ledger_id);
            let ledger = fluree.ledger("mydb:main").await?;
            println!("Loaded at t={}", ledger.t());
        }
        Err(e) => {
            eprintln!("Error: {}", e);
            return Err(e);
        }
    }

    Ok(())
}
```

## Testing

### Unit Tests

```rust
#[cfg(test)]
mod tests {
    use fluree_db_api::{FlureeBuilder, Result};
    use serde_json::json;

    #[tokio::test]
    async fn test_insert_and_query() -> Result<()> {
        // Use memory storage for tests
        let fluree = FlureeBuilder::memory().build_memory();
        let ledger = fluree.create_ledger("test").await?;

        // Insert data
        let data = json!({
            "@context": {"ex": "http://example.org/ns/"},
            "@graph": [{"@id": "ex:alice", "ex:name": "Alice"}]
        });

        fluree.graph("test:main")
            .transact()
            .insert(&data)
            .commit()
            .await?;

        // Query data
        let query = json!({
            "select": ["?name"],
            "where": [{"@id": "ex:alice", "ex:name": "?name"}]
        });

        let result = fluree.graph("test:main")
            .query()
            .jsonld(&query)
            .execute()
            .await?;

        assert_eq!(result.row_count(), 1);

        Ok(())
    }
}
```

### Integration Tests

```rust
// tests/integration_test.rs
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;
use tempfile::TempDir;

#[tokio::test]
async fn test_persistence() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let path = temp_dir.path().to_str().unwrap();

    // Create ledger and write data
    {
        let fluree = FlureeBuilder::file(path).build_async().await?;
        let ledger = fluree.create_ledger("test").await?;

        let data = json!({"@context": {}, "@graph": [{"@id": "ex:test"}]});
        fluree.graph("test:main")
            .transact()
            .insert(&data)
            .commit()
            .await?;
    }

    // Verify persistence by reopening
    {
        let fluree = FlureeBuilder::file(path).build_async().await?;
        let ledger = fluree.ledger("test:main").await?;

        assert!(ledger.t() > 0);
    }

    Ok(())
}
```

## Performance Tips

### Batch Transactions

```rust
// Good: Batch related changes
let batch_data = json!({
    "@graph": [
        {"@id": "ex:item1", "ex:value": 1},
        {"@id": "ex:item2", "ex:value": 2},
        {"@id": "ex:item3", "ex:value": 3}
    ]
});
let result = fluree.graph("mydb:main")
    .transact()
    .insert(&batch_data)
    .commit()
    .await?;

// Bad: Individual transactions (more overhead per commit)
for i in 1..=3 {
    let txn = json!({"@graph": [{"@id": format!("ex:item{}", i), "ex:value": i}]});
    fluree.graph("mydb:main")
        .transact()
        .insert(&txn)
        .commit()
        .await?;
}
```

### Use Appropriate Storage

- **Memory**: Fastest, no persistence (tests, temporary data)
- **File**: Good balance (single server, local development)
- **AWS**: Distributed, durable (production, multi-server)

### Query Optimization

```rust
// Good: Specific patterns
let query = json!({
    "select": ["?name"],
    "where": [
        {"@id": "ex:alice", "schema:name": "?name"}
    ]
});

// Bad: Broad patterns
let query = json!({
    "select": ["?s", "?p", "?o"],
    "where": [
        {"@id": "?s", "?p": "?o"}
    ]
});
```

### Enable Query Tracking

```rust
use fluree_db_api::{FlureeBuilder, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // Use execute_tracked() for fuel/time/policy tracking
    let tracked = fluree.graph("mydb:main")
        .query()
        .sparql("SELECT * WHERE { ?s ?p ?o }")
        .execute_tracked()
        .await?;

    println!("Query used {} fuel", tracked.fuel().unwrap_or(0));

    Ok(())
}
```

## Graph API Reference

The Graph API follows a **lazy-handle** pattern: `fluree.graph(graph_ref)` returns a lightweight handle, and all I/O is deferred to terminal methods.

### Getting a Graph Handle

```rust
// Lazy handle to the current (head) state
let graph = fluree.graph("mydb:main");

// Lazy handle at a specific point in time
let graph = fluree.graph_at("mydb:main", TimeSpec::AtT(100));
```

### Querying

```rust
// JSON-LD query (lazy — loads graph at execution time)
let result = fluree.graph("mydb:main")
    .query()
    .jsonld(&query_json)
    .execute().await?;

// SPARQL query
let result = fluree.graph("mydb:main")
    .query()
    .sparql("SELECT ?s WHERE { ?s a <ex:Person> }")
    .execute().await?;

// Formatted output (JSON-LD or SPARQL JSON based on query type)
let json = fluree.graph("mydb:main")
    .query()
    .jsonld(&query_json)
    .execute_formatted().await?;

// Tracked query (fuel/time/policy metrics)
let tracked = fluree.graph("mydb:main")
    .query()
    .sparql("SELECT * WHERE { ?s ?p ?o }")
    .execute_tracked().await?;
```

### Materializing a GraphSnapshot

```rust
// Load once, query many times (avoids reloading)
let db = fluree.graph("mydb:main").load().await?;

let r1 = db.query().sparql("...").execute().await?;
let r2 = db.query().jsonld(&q).execute().await?;

// Access the underlying GraphDb
let view = db.view();
```

### Transacting

```rust
// Insert and commit
let result = fluree.graph("mydb:main")
    .transact()
    .insert(&data)
    .commit().await?;

// Upsert with options. f:identity is system-controlled (signed DID,
// opts.identity, or CommitOpts::identity). f:message and f:author are
// pure user claims — supply them in the transaction body just like any
// other txn-meta property.
let data = serde_json::json!({
    "@context": {
        "ex": "http://example.org/",
        "f": "https://ns.flur.ee/db#"
    },
    "@graph": [{ "@id": "ex:alice", "ex:name": "Alice" }],
    "f:message": "admin update",
    "f:author": "did:admin"
});

let result = fluree.graph("mydb:main")
    .transact()
    .upsert(&data)
    .commit_opts(CommitOpts::default().identity("did:admin"))
    .commit().await?;

// Stage without committing (preview changes)
let staged = fluree.graph("mydb:main")
    .transact()
    .insert(&data)
    .stage().await?;

// Query staged state
let preview = staged.query()
    .jsonld(&validation_query)
    .execute().await?;
```

### Commit Inspection

Decode and display the contents of a commit — assertions and retractions with IRIs resolved to compact form. Similar to `git show` for individual commits.

```rust
// By exact CID
let detail = fluree.graph("mydb:main")
    .commit(&commit_id)
    .execute().await?;

// By transaction number
let detail = fluree.graph("mydb:main")
    .commit_t(5)
    .execute().await?;

// By hex-digest prefix (min 6 chars, like abbreviated git hashes)
let detail = fluree.graph("mydb:main")
    .commit_prefix("3dd028")
    .execute().await?;

// With a custom @context for IRI compaction
let detail = fluree.graph("mydb:main")
    .commit_prefix("3dd028")
    .context(my_parsed_context)
    .execute().await?;

// Access the result
println!("t={}, +{} -{}", detail.t, detail.asserts, detail.retracts);
for flake in &detail.flakes {
    let op = if flake.op { "+" } else { "-" };
    println!("{} {} {} {} [{}]", op, flake.s, flake.p, flake.o, flake.dt);
}
```

The returned `CommitDetail` contains:
- **Metadata**: `id`, `t`, `time`, `size`, `previous`, `signer`, `asserts`, `retracts`
- **`context`**: prefix → IRI map derived from the ledger's namespace codes
- **`flakes`**: flat list in SPOT order, each with resolved compact IRIs

`CommitDetail` implements `Serialize` — flakes serialize as `[s, p, o, dt, op]` tuples (with an optional 6th metadata element for language tags, list indices, or named graphs).

### Terminal Operations

| Method | Returns | Description |
|--------|---------|-------------|
| `.execute()` | `Result<QueryResult>` | Raw query result |
| `.execute_formatted()` | `Result<JsonValue>` | Formatted JSON output (JSON-LD for `.jsonld()`, SPARQL JSON for `.sparql()`) |
| `.execute_tracked()` | `Result<TrackedQueryResponse>` | Result with fuel/time/policy tracking |
| `.commit()` | `Result<TransactResultRef>` | Stage + commit transaction |
| `.stage()` | `Result<StagedGraph>` | Stage without committing |
| `.load()` | `Result<GraphSnapshot>` | Materialize snapshot for reuse |

### Format Override

```rust
use fluree_db_api::FormatterConfig;

// Force JSON-LD format for a SPARQL query
let result = fluree.graph("mydb:main")
    .query()
    .sparql("SELECT ?name WHERE { ?s <schema:name> ?name }")
    .format(FormatterConfig::jsonld())
    .execute_formatted()
    .await?;
```

### Multi-Ledger Queries (Dataset)

For multi-ledger queries, use `GraphDb` directly:

```rust
let customers = fluree.view("customers:main").await?;
let orders = fluree.view("orders:main").await?;

let dataset = DataSetDb::new()
    .with_default(customers)
    .with_named("orders:main", orders);

let result = dataset.query(&fluree)
    .sparql(query)
    .execute().await?;
```

### FROM-Driven Queries (Connection Queries)

```rust
let result = fluree.query_from()
    .jsonld(&query_with_from)
    .execute().await?;
```

## Transaction Builder API Reference

There are two transaction builder patterns, each suited for different use cases:

### `stage(&handle)` — Server/Application Pattern (Recommended)

Use `stage(&handle)` when building servers or applications with ledger caching enabled. The handle is borrowed and updated in-place on successful commit, ensuring concurrent readers see the update.

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    // Caching is on by default (required for stage)
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Get a cached handle
    let handle = fluree.ledger_cached("mydb:main").await?;

    // Transaction via builder — handle updated in-place
    let data = json!({"@graph": [{"@id": "ex:test", "ex:name": "Test"}]});
    let result = fluree.stage(&handle)
        .insert(&data)
        .execute()
        .await?;

    println!("Committed at t={}", result.receipt.t);

    // Handle now reflects the new state
    let snapshot = handle.snapshot().await;
    assert_eq!(snapshot.t, result.receipt.t);

    Ok(())
}
```

**Why use `stage(&handle)`:**
- **Concurrent safety**: Multiple requests share the same handle; updates are atomic
- **No ownership dance**: You don't need to track and pass around `LedgerState` values
- **Server-friendly**: Matches how the HTTP server handles transactions internally

### `stage_owned(ledger)` — CLI/Script/Test Pattern

Use `stage_owned(ledger)` when you manage your own `LedgerState` directly. This is typical for CLI tools, scripts, and tests where you don't need ledger caching.

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::memory().build_memory();

    // You own the ledger state
    let ledger = fluree.create_ledger("mydb").await?;

    // Transaction consumes ledger, returns updated state
    let data = json!({"@graph": [{"@id": "ex:test", "ex:name": "Test"}]});
    let result = fluree.stage_owned(ledger)
        .insert(&data)
        .execute()
        .await?;

    // Get the updated ledger from the result
    let ledger = result.ledger;
    println!("Now at t={}", ledger.t());

    Ok(())
}
```

**Why use `stage_owned(ledger)`:**
- **Simple ownership**: Good for linear workflows (load → transact → done)
- **No caching required**: Works even with `without_ledger_caching()`
- **Test-friendly**: Each test manages its own state

### Choosing Between Them

| Use Case | Pattern | Why |
|----------|---------|-----|
| HTTP server | `stage(&handle)` | Shared handles, atomic updates |
| Long-running app | `stage(&handle)` | Concurrent access to same ledger |
| CLI tool | `stage_owned(ledger)` | Simple, no caching needed |
| Integration test | `stage_owned(ledger)` | Isolated state per test |
| Script/batch job | `stage_owned(ledger)` | Linear workflow |

### Builder Methods (Both Patterns)

Both `stage(&handle)` and `stage_owned(ledger)` return a builder with identical methods:

```rust
let result = fluree.stage(&handle)  // or stage_owned(ledger)
    .insert(&data)                   // or .upsert(&data), .update(&data)
    .commit_opts(CommitOpts::default().identity("did:admin"))
    .execute()
    .await?;
// (Include `f:message` / `f:author` directly in `data` for user-claim provenance.)
```

| Method | Description |
|--------|-------------|
| `.insert(&json)` | Insert JSON-LD data |
| `.upsert(&json)` | Upsert JSON-LD data |
| `.update(&json)` | Update with WHERE/DELETE/INSERT |
| `.insert_turtle(&ttl)` | Insert Turtle or TriG data (graph blocks land in their named graphs) |
| `.upsert_turtle(&ttl)` | Upsert Turtle or TriG data |
| `.txn_opts(opts)` | Set transaction options (branch, context) |
| `.commit_opts(opts)` | Set commit options (identity, raw_txn) |
| `.policy(ctx)` | Set policy enforcement |
| `.execute()` | Stage + commit |
| `.stage()` | Stage without committing (returns `Staged`) |
| `.validate()` | Check configuration without executing |

### Graph API Transactions

The Graph API (`fluree.graph(graph_ref).transact()`) is built on top of `stage(&handle)` internally:

```rust
// Graph API (convenient, uses caching internally)
let result = fluree.graph("mydb:main")
    .transact()
    .insert(&data)
    .commit()
    .await?;

// Equivalent to:
let handle = fluree.ledger_cached("mydb:main").await?;
let result = fluree.stage(&handle)
    .insert(&data)
    .execute()
    .await?;
```

## Ledger Info API

Get comprehensive metadata about a ledger using the `ledger_info()` builder:

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Get ledger info with optional context for IRI compaction
    let context = json!({
        "schema": "http://schema.org/",
        "ex": "http://example.org/ns/"
    });

    let info = fluree
        .ledger_info("mydb:main")
        .with_context(&context)
        // Optional: include datatype breakdowns under stats.properties[*]
        // .with_property_datatypes(true)
        // Optional: make property datatype details novelty-aware (real-time)
        // .with_realtime_property_details(true)
        .execute()
        .await?;

    // Access metadata sections
    println!("Commit: {}", info["commit"]);
    println!("Nameservice: {}", info["nameservice"]);
    println!("Namespace codes: {}", info["namespace-codes"]);
    println!("Stats: {}", info["stats"]);
    println!("Index: {}", info["index"]);

    Ok(())
}
```

### Ledger Info Response

The response includes:

| Section | Description |
|---------|-------------|
| `commit` | Commit info in JSON-LD format |
| `nameservice` | NsRecord in JSON-LD format |
| `namespace-codes` | Inverted mapping (prefix → code) for IRI expansion |
| `stats` | Flake counts, size, property/class statistics with selectivity |
| `index` | Index metadata (`t`, ContentId, index ID) |

#### Stats freshness (real-time vs indexed)

The `stats` section now uses layered runtime stats assembly:

- Default `ledger_info()` uses the full novelty-aware path, including lookup-backed class/ref enrichment.
- `with_realtime_property_details(false)` downgrades to the lighter fast novelty-aware merge (`Indexed` + novelty deltas, no extra lookups).
- HLL / NDV fields remain index-derived, so they are omitted by default and only included via `with_property_estimates(true)`.

That means the payload still mixes **real-time** values (indexed + novelty deltas) with values that are only available **as-of the last index**.

- **Real-time (includes novelty)**:
  - `stats.flakes`, `stats.size`
  - `stats.properties[*].count` (but not NDV)
  - `stats.properties[*].datatypes` by default
  - `stats.classes[*].count`
  - `stats.classes[*].property-list` and `stats.classes[*].properties` (property presence)
  - `stats.classes[*].properties[*].refs` by default

- **As-of last index**:
  - `stats.indexed` (the index \(t\))
  - `stats.properties[*].ndv-values`, `stats.properties[*].ndv-subjects` when explicitly included via `with_property_estimates(true)`
  - Any selectivity derived from NDV values
  - `stats.classes[*].properties[*].refs` only when callers explicitly disable full detail with `with_realtime_property_details(false)`

## Nameservice Query API

Query metadata about all ledgers and graph sources using the `nameservice_query()` builder:

```rust
use fluree_db_api::{FlureeBuilder, Result};
use serde_json::json;

#[tokio::main]
async fn main() -> Result<()> {
    let fluree = FlureeBuilder::file("./data").build_async().await?;

    // Find all ledgers on main branch
    let query = json!({
        "@context": {"f": "https://ns.flur.ee/db#"},
        "select": ["?ledger", "?t"],
        "where": [{"@id": "?ns", "@type": "f:LedgerSource", "f:ledger": "?ledger", "f:branch": "main", "f:t": "?t"}],
        "orderBy": [{"var": "?t", "desc": true}]
    });

    let results = fluree.nameservice_query()
        .jsonld(&query)
        .execute_formatted()
        .await?;

    println!("Ledgers: {}", serde_json::to_string_pretty(&results)?);

    // SPARQL query
    let results = fluree.nameservice_query()
        .sparql("PREFIX f: <https://ns.flur.ee/db#>
                 SELECT ?ledger ?t WHERE { ?ns a f:LedgerSource ; f:ledger ?ledger ; f:t ?t }")
        .execute_formatted()
        .await?;

    println!("SPARQL results: {}", serde_json::to_string_pretty(&results)?);

    // Convenience method (equivalent to builder with defaults)
    let results = fluree.query_nameservice(&query).await?;

    Ok(())
}
```

### Available Properties

**Ledger Records** (`@type: "f:LedgerSource"`):

| Property | Description |
|----------|-------------|
| `f:ledger` | Ledger name (without branch suffix) |
| `f:branch` | Branch name |
| `f:t` | Current transaction number |
| `f:status` | Status: "ready" or "retracted" |
| `f:ledgerCommit` | Reference to latest commit ContentId |
| `f:ledgerIndex` | Index info with `@id` and `f:t` |

**Graph Source Records** (`@type: "f:GraphSourceDatabase"`):

| Property | Description |
|----------|-------------|
| `f:name` | Graph source name |
| `f:branch` | Branch name |
| `f:config` | Configuration JSON |
| `f:dependencies` | Source ledger dependencies |
| `f:indexAddress` | Index ContentId |
| `f:indexT` | Index transaction number |

### Builder Methods

| Method | Description |
|--------|-------------|
| `.jsonld(&query)` | Set JSON-LD query input |
| `.sparql(query)` | Set SPARQL query input |
| `.format(config)` | Override output format |
| `.execute_formatted()` | Execute and return formatted JSON |
| `.execute()` | Execute with default formatting |
| `.validate()` | Validate without executing |

### Example Queries

```rust
// Find ledgers with t > 100
let query = json!({
    "@context": {"f": "https://ns.flur.ee/db#"},
    "select": ["?ledger", "?t"],
    "where": [{"@id": "?ns", "f:ledger": "?ledger", "f:t": "?t"}],
    "filter": ["(> ?t 100)"]
});

// Find all BM25 graph sources
let query = json!({
    "@context": {"f": "https://ns.flur.ee/db#"},
    "select": ["?name", "?deps"],
    "where": [{"@id": "?gs", "@type": "f:Bm25Index", "f:name": "?name", "f:dependencies": "?deps"}]
});
```

## Examples

See complete examples in `fluree-db-api/examples/`:

- `benchmark_aj_query_1.rs` - Basic query patterns
- `benchmark_aj_query_2.rs` - Complex queries
- `benchmark_aj_query_3.rs` - Aggregations
- `benchmark_aj_query_4.rs` - Time travel queries

Run examples:

```bash
cargo run --example benchmark_aj_query_1 --release
```

## API Reference

For detailed API documentation, see:

```bash
cargo doc --open -p fluree-db-api
```

## Related Documentation

- [Getting Started](https://labs.flur.ee/docs/db/getting-started) - Overview
- [HTTP API](https://labs.flur.ee/docs/db/api) - Server-based usage
- [Distributed Tracing Integration](https://labs.flur.ee/docs/db/operations/distributed-tracing) - Correlating your app's traces with Fluree
- [Query](https://labs.flur.ee/docs/db/query) - Query documentation
- [Transactions](https://labs.flur.ee/docs/db/transactions) - Write operations
- [Crate Map](https://labs.flur.ee/docs/db/reference/crate-map) - Architecture overview
- [Dev Setup](https://labs.flur.ee/docs/db/contributing/dev-setup) - Development guide


## Using Fluree from Python

> Fluree DB v4.2 documentation · https://labs.flur.ee/docs/db/getting-started/python

The `fluree` package runs the Fluree engine inside your Python process: no
server to start, and the same engine the server and CLI run. This page gets
you started and shows how the rest of this book reads from Python. The
[Python documentation](https://fluree.github.io/db/python/) has a guide to the
whole package and its API reference, and each class and method carries its
documentation for `help()` and your editor.

## Install

```sh
pip install fluree                # or "fluree[pandas]", "fluree[polars]"
```

Wheels are published for Linux (x86-64 and arm64, glibc 2.28 or later), macOS
14 or later on Apple silicon, and Windows (x86-64), for CPython 3.10 and
later. The package version is the version of the engine inside it.

## Quick start

```python
import fluree

with fluree.connect("./data") as conn:          # or fluree.connect(":memory:")
    people = conn.create("people")

    people.insert("""
        @prefix ex: <http://example.org/> .
        ex:alice ex:name "Alice" ; ex:age 42 .
    """)
    commit = people.insert({
        "@context": {"ex": "http://example.org/"},
        "@id": "ex:bob", "ex:name": "Bob", "ex:age": 37,
    })

    rows = people.select("""
        PREFIX ex: <http://example.org/>
        SELECT ?name ?age WHERE { ?s ex:name ?name ; ex:age ?age } ORDER BY ?name
    """)
    for name, age in rows:
        print(name, age)              # Alice 42, then Bob 37: native str and int

    # Every past state stays queryable.
    before_bob = people.at(t=commit.t - 1)
    print(before_bob.query("PREFIX ex: <http://example.org/> ASK { ex:bob ?p ?o }"))  # False
```

`conn.ledger("people")` opens an existing ledger. Results come back as Python
values: `int`, `Decimal`, `datetime`, `str`, and `fluree.IRI` for IRIs. A
result converts to a DataFrame with `to_pandas()` or `to_polars()`.

## Reading this book from Python

The queries and transactions in this book work as written. A SPARQL, JSON-LD
or Cypher query that a page sends to the server goes to `ledger.query()`, and a
transaction body goes to `insert()`, `upsert()` or `update()`:

| In this book | From Python |
|--------------|-------------|
| [Query](https://labs.flur.ee/docs/db/query): JSON-LD, SPARQL or Cypher | `ledger.query(query)`, or `ledger.select(query)` for a table |
| A query whose `FROM` names ledgers ([datasets](https://labs.flur.ee/docs/db/query/datasets)) | `conn.query(query)` |
| [Insert](https://labs.flur.ee/docs/db/transactions/insert), [upsert](https://labs.flur.ee/docs/db/transactions/upsert), [update](https://labs.flur.ee/docs/db/transactions/update-where-delete-insert) | `ledger.insert(data)`, `ledger.upsert(data)`, `ledger.update(txn)` |
| [Sync](https://labs.flur.ee/docs/db/transactions/sync) a graph to a payload | `ledger.sync(data, graph=...)` |
| [Time travel](https://labs.flur.ee/docs/db/concepts/time-travel) (`t`, ISO time, commit) | `ledger.at(t=..., time=..., commit=...)` |
| [Branching](https://labs.flur.ee/docs/db/guides/cookbook-branching) | `ledger.branch(name)`, `merge()`, `rebase()`, `revert()` |
| [Policy](https://labs.flur.ee/docs/db/security/policy-model) options (`identity`, `policyClass`, ...) | `ledger.with_policy(identity=..., policy_class=...)` |
| [Ledger configuration](https://labs.flur.ee/docs/db/ledger-config/writing-config) | `ledger.update(...)` writing the config graph |
| [Full-text](https://labs.flur.ee/docs/db/indexing-and-search/fulltext) and [vector](https://labs.flur.ee/docs/db/indexing-and-search/vector-search) search | `ledger.set_full_text(...)`, `fluree.Vector`, and the query functions |
| [Graph sources](https://labs.flur.ee/docs/db/graph-sources/overview): Iceberg, Delta, SQL | `conn.map_iceberg(...)`, `conn.map_delta(...)`, `conn.map_sql(...)` |
| Export, and [archives](https://labs.flur.ee/docs/db/operations/pack-archive-restore) | `ledger.export(...)`, `ledger.archive(path)`, `conn.restore(path, name)` |
| [Connection configuration](https://labs.flur.ee/docs/db/reference/connection-config-jsonld) (S3, DynamoDB, encryption) | `fluree.connect(config={...})` |

A few things differ from the server:

- **Policy belongs to the handle.** Choose it with `ledger.with_policy(...)`.
  A query or write that names its own policy (JSON-LD `opts`, a SPARQL
  `# PRAGMA`) is refused, so a query passed in from elsewhere cannot widen
  what the handle sees.
- **A ledger's query reads that ledger.** A query that names other ledgers
  goes to `conn.query()`.
- **Several writes can be one commit.** `with ledger.transaction() as txn:`
  stages writes in any language together, and `ledger.transact(fn)` runs
  read-then-write work again when another commit lands first.
- **Parameters.** `query()`, `update()` and `stream()` take values by name,
  from a dict or keyword arguments: `ledger.query("... $name ...", name="Alice")`.

## asyncio

`fluree.aio` is the same API with coroutines, for FastAPI and other asyncio
applications. Cancelling a task stops its query in the engine:

```python
import fluree.aio

async with fluree.aio.connect("./data") as conn:
    people = await conn.ledger("people")
    rows = await people.query("SELECT ...")
```

## Reading documents

`fluree.doc.read` reads one document with an extraction model reached over
HTTP, exactly as [`fluree doc read`](https://labs.flur.ee/docs/db/cli/doc#fluree-doc-read) does: it
parses the file (PDF, Word, PowerPoint, HTML, Markdown, text, spreadsheets,
transcripts, email), sends its text and structure with your ontology and
catalog, and returns the reading: a Fluree DB transaction holding the run,
the facts in your ontology's terms, the claims behind them and the mentions,
which inserts into a ledger as it is (the run becomes the commit's metadata):

```python
import fluree

reading = fluree.doc.read("invoice.pdf", ontology="invoices.ttl",
                          catalog="suppliers.ttl", model="reader-small")
print(reading.usage.note)                  # 1,032 tokens
for m in reading.mentions():               # text, begin, end, class, entity, confidence, element
    print(m["text"], "->", m["entity"])
for c in reading.claims():                 # subject, predicate, object, status, score, asserted
    print(c["predicate"], c["score"])

with fluree.connect("./data") as conn:
    conn.create("invoices").insert(reading.to_jsonld())
```

`text=` reads a string instead of a file, under an IRI derived from its
content unless `doc_iri=` names one; `catalog` takes a list of files, each
optionally `(file, class IRI)`; `include=` says what comes with the facts
(`"claims"`, `"mentions"`, both by default, or `"none"`); `to_trig()` and
`to_turtle()` give the reading as TriG and Turtle. Offsets index the parser's
text (what `fluree doc parse --format text` prints), not the file's bytes.
The reading is kept as the reader wrote it, in the extraction vocabulary
(`xt:`, `https://ns.flur.ee/extract#`): `reading.transactions` holds one
transaction per call (a long document takes several, each its own run, and
`to_jsonld()` asks you to insert each), and `reading.runs` each call's run,
release and request ID.

The credential: `api_key` with `auth_header` is sent as is to `url`;
`api_key` alone is traded for an hour's token when it is a Fluree.ai API key
(`flk_…`) and sent as a bearer token otherwise; with no key, this machine's
`fluree login`, else `FLUREE_AI_API_KEY`, each only to its own service (a
`url` elsewhere is called with no credential). With `cache_dir`, a request
read once is answered from there afterwards. Python does no vision
escalation: pages the parser can't read are listed in `reading.notes`.

## Next steps

- The [Python guide](https://fluree.github.io/db/python/guide.html) for the
  whole package (results, transactions, Cypher, search, graph sources,
  branches, errors, logging and concurrency) and the
  [API reference](https://fluree.github.io/db/python/api/fluree/).
- [Concepts](https://labs.flur.ee/docs/db/concepts) for how Fluree works.
- [Guides](https://labs.flur.ee/docs/db/guides) for task-oriented recipes; their queries run
  unchanged through `ledger.query()`.

