--- # What is NodeDB (docs/introduction/what-is-nodedb) --- title: What is NodeDB description: A distributed hybrid database with eight peer engines for multi-modal AI and agentic workloads. --- # What is NodeDB NodeDB is a single Rust binary that provides eight peer engines — Document (schemaless), Document (strict), Key-Value, Columnar, Timeseries, Spatial, Vector, and Array — sharing one storage core, plus Graph and Full-Text Search as cross-engine overlays on any collection. Seven of the eight are selected per-collection via `WITH (engine='')`; Array uses its own `CREATE ARRAY` DDL family. Each engine is built with purpose-specific data structures. All share the same storage, memory, and query planner. Cross-engine queries execute in one process with zero network hops. ## The Problem Modern applications don't fit in one database. A healthcare app needs patient records (relational), medical imaging embeddings (vector), care team relationships (graph), device telemetry (timeseries), and offline-first sync for field workers (CRDT). The industry answer is a polyglot stack: PostgreSQL for relational, Qdrant for vectors, Neo4j for graphs, ClickHouse for timeseries, Redis for caching. Each system has its own protocol, deployment, and failure modes. Cross-database queries require application-level joins. Some databases claim to solve this by bolting on capabilities — "graph" as recursive JOINs, "timeseries" without columnar compression or continuous aggregation. The features exist in name but not in performance. ## Eight Engines **Vector** — HNSW index with SQ8, PQ, and IVF-PQ quantization. SIMD-accelerated distance math. Adaptive bitmap pre-filtering. **Graph** — CSR adjacency index with 13 native algorithms (PageRank, WCC, Louvain, SSSP, etc.) and a Cypher-subset MATCH pattern engine. GraphRAG fusion with vector search. **Document** — Two modes per collection. Schemaless: MessagePack blobs with CRDT sync. Strict: Binary Tuples with O(1) field extraction and 3-4x cache density over BSON. **Columnar / Timeseries / Spatial** — Three peer engines sharing one compressed-column storage core (ALP, FastLanes, FSST, Gorilla, LZ4 codecs; block statistics; predicate pushdown). `columnar` for general analytics; `timeseries` adds append-only ingest, retention, and continuous aggregation; `spatial` adds R*-tree, geohash, and H3 indexing. **Key-Value** — Hash-indexed O(1) point lookups with typed value fields. Native TTL, secondary indexes, atomic INCR/CAS, and predicate-filtered scans. SQL-queryable and joinable. **Full-Text Search** — Block-Max WAND optimized BM25 with 16 Snowball stemmers, 27-language stop words, CJK bigram tokenization, posting compression, fuzzy matching, and native hybrid vector fusion. **Array** — ND sparse multi-dimensional engine with tile-based storage, Z-order indexing, per-tile MBR statistics, and bitemporal cells. Replaces TileDB / Zarr / SciDB / Rasdaman for genomics, single-cell biology, raster cubes, and climate models. **CRDT** — Loro-backed conflict-free replicated data types. AP on the edge, CP in the cloud. SQL constraint validation at sync time with compensation hints. ## Three Deployment Modes **Origin (server)** — Full distributed database. Multi-Raft consensus, Thread-per-Core Data Plane with io_uring, PostgreSQL-compatible SQL over pgwire. Horizontal scaling with automatic shard rebalancing. **Origin (local)** — Same binary, single-node. No cluster overhead. Like running PostgreSQL locally. **NodeDB-Lite (embedded)** — In-process library for phones, browsers (WASM), and desktops. All eight engines run locally with sub-millisecond reads. CRDT sync to Origin via WebSocket. ## PostgreSQL Compatible Connect with `psql`, any PostgreSQL driver, or ORM. Six wire protocols are available: - **pgwire** — PostgreSQL wire protocol (port 6432) - **HTTP** — REST, SSE, WebSocket (port 6480) - **NDB** — Native MessagePack protocol (port 6433) - **RESP** — Redis-compatible KV protocol (optional) - **ILP** — InfluxDB Line Protocol for timeseries ingest (optional) - **Sync** — WebSocket sync for NodeDB-Lite clients (port 9090) ## What NodeDB Replaces The combination of PostgreSQL + pgvector + Redis + Neo4j + ClickHouse + Elasticsearch — unified into one binary with shared storage and zero network hops between engines. --- # Quick Start (docs/introduction/quickstart) --- title: Quick Start description: Start NodeDB and run your first queries across multiple engines in under five minutes. --- # Quick Start This guide takes you from zero to running multi-engine queries in five minutes. ## 1. Start NodeDB ```bash # Linux: prebuilt binary (recommended — best performance) gh release download --repo NodeDB-Lab/nodedb --pattern 'nodedb-*-linux-x64.tar.gz' \ && tar -xzf nodedb-*-linux-x64.tar.gz \ && ./nodedb # macOS / Windows / WSL2: Docker docker compose up -d # Or from source (any Linux with Rust 1.94+) ./target/release/nodedb ``` See [Installation](/docs/introduction/installation) for the full setup, configuration, and systemd unit examples. ## 2. Connect ```bash psql -h localhost -p 6432 -U nodedb -d default ``` The server starts in password mode with the superuser `nodedb`. Set `NODEDB_SUPERUSER_PASSWORD` before the first start, or read the generated password from `/.superuser_password`. `-d default` names the built-in database. Without it, psql asks for a database named after the user, and the server refuses the connection with `3D000`. ## 3. Documents (Schemaless) ```sql CREATE COLLECTION users; INSERT INTO users (id, name, email, age) VALUES ('u1', 'Alice', 'alice@example.com', 30); INSERT INTO users (id, name, email, role) VALUES ('u2', 'Bob', 'bob@example.com', 'admin'); -- Object literal syntax also works INSERT INTO users { name: 'Charlie', email: 'charlie@example.com', age: 25 }; SELECT name, email FROM users WHERE age > 25; ``` ## 4. Strict Documents (Schema-Enforced) ```sql CREATE COLLECTION orders ( id TEXT PRIMARY KEY, customer_id TEXT, total FLOAT, status TEXT, created_at TIMESTAMP ) WITH (engine='document_strict'); INSERT INTO orders (id, customer_id, total, status) VALUES ('o1', 'u1', 99.99, 'pending'); SELECT * FROM orders WHERE status = 'pending' ORDER BY created_at DESC; ``` ## 5. Vector Search ```sql CREATE COLLECTION articles; CREATE VECTOR INDEX idx_embed ON articles METRIC cosine DIM 384; INSERT INTO articles (id, title, embedding) VALUES ('a1', 'Intro to AI', ARRAY[0.1, 0.2, 0.3, ...]); SEARCH articles USING VECTOR(embedding, ARRAY[0.1, 0.3, ...], 10); ``` ## 6. Graph ```sql CREATE COLLECTION social; INSERT INTO social (id, name) VALUES ('alice', 'Alice'); INSERT INTO social (id, name) VALUES ('bob', 'Bob'); GRAPH INSERT EDGE IN 'social' FROM 'alice' TO 'bob' TYPE 'knows' PROPERTIES { since: 2020 }; GRAPH TRAVERSE FROM 'alice' DEPTH 2; GRAPH ALGO PAGERANK ON social DAMPING 0.85 ITERATIONS 20 TOLERANCE 1e-7; ``` ## 7. Key-Value ```sql CREATE COLLECTION sessions (key TEXT PRIMARY KEY) WITH (engine='kv'); INSERT INTO sessions (key, value) VALUES ('sess_abc', 'token-abc'); SELECT * FROM sessions WHERE key = 'sess_abc'; ``` ## 8. Columnar (Analytics) ```sql CREATE COLLECTION web_events ( ts TIMESTAMP, user_id UUID, page VARCHAR, duration_ms INT ) WITH (engine='columnar'); SELECT page, AVG(duration_ms), COUNT(*) FROM web_events WHERE ts > now() - INTERVAL '7 days' GROUP BY page ORDER BY COUNT(*) DESC; ``` ## 9. Timeseries ```sql CREATE COLLECTION cpu_metrics ( ts TIMESTAMP TIME_KEY, host VARCHAR, cpu FLOAT ) WITH (engine='timeseries', partition_by='1h'); SELECT time_bucket('5 minutes', ts) AS bucket, host, AVG(cpu) FROM cpu_metrics WHERE ts > now() - INTERVAL '1 hour' GROUP BY bucket, host; ``` ## 10. Triggers ```sql CREATE TRIGGER notify_on_order AFTER INSERT ON orders FOR EACH ROW $$ BEGIN INSERT INTO notifications (id, user_id, message) VALUES (NEW.id || '_notif', NEW.customer_id, 'Order received'); END; $$; ``` ## What's Next - [Architecture](/docs/architecture/overview) — how the three-plane execution model works - [Data Modeling](/docs/data-modeling/collections) — collections, schemas, and engine selection - [SQL Reference](/docs/sql/overview) — full query language reference --- # Installation (docs/introduction/installation) --- title: Installation description: Install NodeDB via prebuilt binary, Docker, or from source. Linux kernel 5.1+ required. --- # Installation NodeDB requires Linux kernel 5.1+ (for io_uring), regardless of how you install it. There are three ways to install NodeDB: 1. [Prebuilt binary](#prebuilt-binary-linux) — **recommended on Linux.** Direct kernel access to io_uring, no virtualization overhead, best raw performance. 2. [Docker](/docs/introduction/docker) — **recommended on macOS / Windows / WSL2**, or when you want a one-command setup with zero host configuration. 3. [Build from source](#build-from-source) — for development or custom features. All three share the same [configuration](#configuration) and connection paths described below. ## Prebuilt binary (Linux) Each tagged release ships a static `nodedb` tarball on GitHub for `linux-x64` and `linux-arm64`. macOS and Windows users should use [Docker](/docs/introduction/docker) until those targets ship. ```bash # Resolve the latest tag and your architecture TAG=$(curl -fsSL https://api.github.com/repos/NodeDB-Lab/nodedb/releases/latest \ | grep '"tag_name"' | cut -d'"' -f4) ARCH=$(uname -m | sed 's/aarch64/arm64/; s/x86_64/x64/') # Download and extract curl -L -o nodedb.tar.gz \ "https://github.com/NodeDB-Lab/nodedb/releases/download/${TAG}/nodedb-${TAG#v}-linux-${ARCH}.tar.gz" tar -xzf nodedb.tar.gz # Optional: install system-wide sudo mv nodedb /usr/local/bin/ # Run with all defaults (data goes to ~/.nodedb/data) nodedb ``` If you have the [GitHub CLI](https://cli.github.com/) installed, this is one command: ```bash gh release download --repo NodeDB-Lab/nodedb --pattern 'nodedb-*-linux-x64.tar.gz' \ && tar -xzf nodedb-*-linux-x64.tar.gz ``` Run with a config file or a custom data directory: ```bash # Point at an explicit data dir NODEDB_DATA_DIR=/var/lib/nodedb nodedb # Or load a config file (env vars still override TOML keys) nodedb --config /etc/nodedb/nodedb.toml ``` For a long-running server, drop a unit file at `/etc/systemd/system/nodedb.service`: ```ini [Unit] Description=NodeDB After=network.target [Service] Type=simple User=nodedb Group=nodedb ExecStart=/usr/local/bin/nodedb --config /etc/nodedb/nodedb.toml Restart=on-failure LimitNOFILE=1048576 [Install] WantedBy=multi-user.target ``` Then `sudo systemctl enable --now nodedb`. The user/group must be able to read the config file and write `data_dir`. For a specific version or to browse changelogs, see the release page: . The SQL surface is still pre-1.0 and changes between tags, so pin a version in production. ## Docker See [Docker](/docs/introduction/docker) for the full Compose and `docker run` setup. The right choice on macOS, Windows, or any host where you don't want to manage a binary directly. ## Build from Source Requires Rust 1.94+ and a Linux host. ```bash git clone https://github.com/NodeDB-Lab/nodedb.git cd nodedb # Release build (all crates) cargo build --release # Run tests (use nextest — the cluster integration tests rely on # the test groups defined in .config/nextest.toml and will hang # under plain `cargo test`) cargo install cargo-nextest --locked # one-time cargo nextest run --all-features ``` The build produces two binaries: - `target/release/nodedb` — the database server - `target/release/ndb` — the terminal client (TUI with syntax highlighting, tab completion, history search) Start the server: ```bash ./target/release/nodedb # Or with a config file ./target/release/nodedb --config nodedb.toml ``` Default startup output: ``` 2026-01-01T00:00:00Z INFO nodedb: Starting NodeDB 2026-01-01T00:00:00Z INFO nodedb: Listening on 127.0.0.1:6433 (native) 2026-01-01T00:00:00Z INFO nodedb: Listening on 127.0.0.1:6432 (PostgreSQL) 2026-01-01T00:00:00Z INFO nodedb: Listening on 127.0.0.1:6480 (HTTP) 2026-01-01T00:00:00Z INFO nodedb: Data directory: ~/.nodedb/data ``` ## Configuration This section applies to **every** install method — prebuilt binary, Docker, and source builds all read the same TOML schema and respond to the same environment variables. Pick whichever is convenient: - **TOML file** — pass `--config /path/to/nodedb.toml` on the command line. Best for production / systemd / pre-baked images. - **Environment variables** — prefix `NODEDB_*`. Best for Docker (`-e`), Compose (`environment:`), and Kubernetes. Env vars **override** values from the TOML file when both are set. All protocols share one bind address (`host`); only the port differs per protocol. ```toml # nodedb.toml [server] host = "127.0.0.1" data_dir = "/var/lib/nodedb" memory_limit = "4GiB" data_plane_cores = 4 max_connections = 1024 log_format = "text" [server.ports] native = 6433 pgwire = 6432 http = 6480 resp = 6381 # Optional: set to enable ilp = 8086 # Optional: set to enable ``` | Config field | Environment variable | Default | | ------------------ | ------------------------- | ---------------------------------------------------- | | `host` | `NODEDB_HOST` | `127.0.0.1` | | `ports.native` | `NODEDB_PORT_NATIVE` | `6433` | | `ports.pgwire` | `NODEDB_PORT_PGWIRE` | `6432` | | `ports.http` | `NODEDB_PORT_HTTP` | `6480` | | `ports.resp` | `NODEDB_PORT_RESP` | disabled | | `ports.ilp` | `NODEDB_PORT_ILP` | disabled | | `data_dir` | `NODEDB_DATA_DIR` | `~/.nodedb/data` (binary), `/var/lib/nodedb` (Docker) | | `memory_limit` | `NODEDB_MEMORY_LIMIT` | `1GiB` | | `data_plane_cores` | `NODEDB_DATA_PLANE_CORES` | CPUs - 1 | | `max_connections` | `NODEDB_MAX_CONNECTIONS` | `4096` | | `log_format` | `NODEDB_LOG_FORMAT` | `text` | ## Connect ```bash # With the ndb TUI client (source build). -w prompts for the password; NDB_PASSWORD also sets it. ./target/release/ndb -w # With psql psql -h localhost -p 6432 -U nodedb -d default # Health check via HTTP curl http://localhost:6480/healthz ``` ## System Requirements - **OS**: Linux (kernel 5.1+ for io_uring) — required for the binary and source builds; Docker users can run on any host that supports a Linux container with io_uring. - **Rust**: 1.94+ (source builds only) - **Memory**: 512 MiB minimum, 4+ GiB recommended - **Disk**: NVMe recommended for Data Plane I/O --- # Docker (docs/introduction/docker) --- title: Docker description: Run NodeDB with a single docker run command or Docker Compose. Single binary, all ports exposed. --- # Docker NodeDB is a single binary. One `docker run` command gets you a running server. Requires Linux kernel 5.1+ (for io_uring). ## Quick Start ```bash docker run -d --name nodedb \ -p 6432:6432 \ -p 6433:6433 \ -p 6480:6480 \ -p 9090:9090 \ -v nodedb-data:/var/lib/nodedb \ -e NODEDB_SUPERUSER_PASSWORD=change-me \ farhansyah/nodedb ``` That's it. Connect with `psql -h localhost -p 6432 -U nodedb -d default` (password from `NODEDB_SUPERUSER_PASSWORD`) or `curl http://localhost:6480/healthz`. Without the variable, the server generates a password into `/var/lib/nodedb/.superuser_password`. ## Ports | Port | Protocol | Required | | ------ | --------------------------------- | -------- | | `6432` | PostgreSQL wire protocol (pgwire) | Yes | | `6433` | Native MessagePack protocol (NDB) | Yes | | `6480` | HTTP API (REST, SSE, WebSocket) | Yes | | `9090` | WebSocket sync (NodeDB-Lite) | Yes | RESP (Redis) and ILP (InfluxDB) are disabled by default. Enable via environment variables: ```bash docker run -d --name nodedb \ -p 6432:6432 \ -p 6433:6433 \ -p 6480:6480 \ -p 9090:9090 \ -p 6381:6381 \ -p 8086:8086 \ -v nodedb-data:/var/lib/nodedb \ -e NODEDB_PORT_RESP=6381 \ -e NODEDB_PORT_ILP=8086 \ farhansyah/nodedb ``` ## Docker Compose ```yaml services: nodedb: image: farhansyah/nodedb ports: - "6432:6432" # pgwire - "6433:6433" # native - "6480:6480" # HTTP - "9090:9090" # sync volumes: - nodedb-data:/var/lib/nodedb environment: NODEDB_MEMORY_LIMIT: "4GiB" # NODEDB_PORT_RESP: "6381" # uncomment to enable Redis protocol # NODEDB_PORT_ILP: "8086" # uncomment to enable ILP ingest volumes: nodedb-data: ``` ```bash docker compose up -d ``` ## Stop ```bash # Stop (data preserved) docker compose down # Stop and wipe all data docker compose down -v # Or with docker run docker stop nodedb && docker rm nodedb # Data persists in the nodedb-data volume ``` ## Verify ```bash curl http://localhost:6480/healthz ``` ## Environment Variables | Variable | Default | Description | | ------------------------- | ---------- | ---------------------------- | | `NODEDB_MEMORY_LIMIT` | 75% of RAM | Total memory budget | | `NODEDB_DATA_PLANE_CORES` | CPUs - 1 | Number of Data Plane threads | | `NODEDB_LOG_FORMAT` | `text` | `text` or `json` | | `NODEDB_HOST` | `0.0.0.0` | Bind address | | `NODEDB_PORT_RESP` | disabled | Set to enable Redis protocol | | `NODEDB_PORT_ILP` | disabled | Set to enable ILP ingest | | `NODEDB_DATA_DIR` | `/var/lib/nodedb` | Data directory inside container | ## Custom Port Mapping Remap any port on the host side. The container always listens on the same internal ports: ```bash docker run -d --name nodedb \ -p 5432:6432 \ -p 8080:6480 \ -v nodedb-data:/var/lib/nodedb \ farhansyah/nodedb ``` --- # Architecture Overview (docs/architecture/overview) --- title: Architecture Overview description: The three-plane execution model — Control Plane, Data Plane, and Event Plane connected by lock-free ring buffers. --- # Architecture Overview NodeDB splits work across three planes connected by lock-free ring buffers. Each plane does exactly what it is best at and nothing else. Mixing planes is a correctness bug. ``` ┌───────────────────────────────────────────┐ │ Control Plane (Tokio) │ │ SQL parsing, query planning, connections │ │ Send + Sync, async │ └─────────────┬──────────────┬──────────────┘ │ SPSC Bridge │ Event subscriptions │ │ ┌─────────────▼──────────┐ ┌▼────────────────────────────────────┐ │ Data Plane (TPC) │ │ Event Plane (Tokio) │ │ Physical execution ├─►│ AFTER trigger dispatch │ │ Storage I/O, SIMD │ │ CDC change streams │ │ !Send, io_uring │ │ Cron scheduler │ │ Emits WriteEvents │ │ Durable pub/sub, webhook delivery │ └────────────────────────┘ └─────────────────────────────────────┘ ``` ## Plane Boundaries | Plane | Does | Does not do | | ------------- | -------------------------------------------------------------- | ----------------------------------------------- | | Control Plane | SQL parsing, query planning, connection handling | Event processing, trigger execution, storage I/O | | Data Plane | Physical I/O, SIMD math, WAL append, BEFORE triggers | Event delivery, AFTER triggers, cross-shard work | | Event Plane | AFTER triggers, CDC, cron, webhooks, durable pub/sub | Query planning, storage I/O, TPC tasks | If code needs to cross a plane boundary, it goes through the SPSC bridge (Control-Data) or the Event Bus (Data-Event). ## Query Entry Paths **SQL path** — All user-facing interfaces accept SQL. The Control Plane parses via sqlparser, plans via EngineRules, and dispatches a `SqlPlan` through the SPSC bridge to the Data Plane. ``` psql / ndb CLI / HTTP /v1/query → SQL parser (sqlparser-rs) → EngineRules::plan_*() → SqlPlan → SPSC Bridge → Data Plane ``` **Native opcode path** — The Rust SDK and FFI/WASM bindings dispatch typed opcode messages over the NDB protocol. The Control Plane converts them directly to a plan, skipping SQL parsing. ``` nodedb-client / FFI / WASM → Native opcode + typed fields → build_plan() → PhysicalPlan → SPSC Bridge → Data Plane ``` Both paths produce the same plan and execute identically on the Data Plane. ## Cross-Engine Identity Every row in every engine — document, KV, columnar, timeseries, spatial, vector, array, graph node, FTS posting — carries a stable global `u32` **surrogate** allocated at insert from a WAL-durable, Raft-replicated monotonic counter. Every engine keys its internal indexes on the surrogate, so cross-engine prefilter and join reduce to roaring-bitmap intersections with **zero per-query translation**. A query like "find product cells whose embedding is near `$q`, that have FTS hits for `'memory leak'`, that live within 5km of point P, in tenant 42" turns into: ``` vector_index.search($q, k) → roaring bitmap A fts_index.match("memory leak") → roaring bitmap B spatial_index.dwithin(P, 5km) → roaring bitmap C metadata_index.tenant_id = 42 → roaring bitmap D A ∩ B ∩ C ∩ D → final candidate surrogate set ``` No `HashMap` translations between hops. Adding a new engine does not require new translation paths — it just allocates surrogates from the same counter. This is the mechanism behind every cross-engine query example you'll see in the SQL reference. --- # Control Plane (docs/architecture/control-plane) --- title: Control Plane description: Tokio-based async runtime for SQL parsing, query planning, and connection handling. --- # Control Plane The Control Plane runs on the standard Tokio thread pool. All types are `Send + Sync`. It handles three responsibilities: ## Connection Handling Accepts connections on all wire protocols: - **pgwire** (port 6432) — PostgreSQL wire protocol - **HTTP** (port 6480) — REST, SSE, WebSocket - **NDB** (port 6433) — Native MessagePack protocol - **RESP** — Redis-compatible (optional) - **ILP** — InfluxDB Line Protocol (optional) - **Sync** (port 9090) — WebSocket for NodeDB-Lite clients Each connection is a Tokio task. Connection state (prepared statements, session variables, transaction context) lives on the connection task. ## Query Planning SQL text arrives from any protocol and flows through: 1. **sqlparser-rs** — parses SQL text into an AST 2. **nodedb-sql EngineRules** — resolves the target engine and produces a `SqlPlan` 3. **Plan conversion** — `SqlPlan` becomes a `PhysicalPlan` for the Data Plane `EngineRules` is the single source of truth for what each engine supports. One implementation per engine type (vector, graph, document, columnar, kv, fts, crdt). The compiler enforces exhaustive handling — adding a new engine or operation requires implementing every trait method. ## Dispatch The Control Plane dispatches `PhysicalPlan` messages to Data Plane cores via the SPSC bridge. Routing is by vShard — each request targets a specific shard, which maps to a specific core. The Control Plane never touches storage, never runs SIMD math, and never processes events. Those responsibilities belong to the Data Plane and Event Plane respectively. --- # Data Plane (docs/architecture/data-plane) --- title: Data Plane description: Thread-per-Core execution with io_uring for physical query execution and storage I/O. --- # Data Plane The Data Plane uses a Thread-per-Core (TPC) architecture. Each CPU core runs an isolated, shared-nothing shard. Types are `!Send` by design — no data crosses core boundaries. ## Execution Model Each core owns: - A dedicated event loop (no Tokio — raw TPC) - io_uring submission and completion queues for NVMe I/O - A jemalloc arena (no allocator lock contention) - Lock-free telemetry ring buffers for metrics There are no locks, no atomics, and no cross-core sharing. The Data Plane achieves predictable latency by eliminating all sources of contention. ## What the Data Plane Does - Executes `PhysicalPlan` nodes dispatched from the Control Plane - Reads from NVMe via io_uring - Runs SIMD-accelerated vector distance math - Appends to the WAL (O_DIRECT) - Evaluates BEFORE triggers (synchronous, same transaction) - Emits `WriteEvent` records to the Event Plane via per-core ring buffers ## What the Data Plane Does Not Do - Spawn Tokio tasks - Handle HTTP or pgwire connections - Process AFTER triggers or CDC events - Coordinate across shards ## WriteEvent Emission After each successful WAL commit, the Data Plane emits a `WriteEvent` containing: - `sequence` — monotonic per-core counter - `collection` — target collection name - `op` — Insert, Update, or Delete - `row_id`, `lsn`, `tenant_id`, `vshard_id` - `source` — User, Trigger, RaftFollower, or CrdtSync - `new_value`, `old_value` — for trigger and CDC consumption Events are fire-and-forget — the Data Plane never blocks waiting for the Event Plane. If the ring buffer overflows, the Event Plane replays from the WAL. ## Page Fault Hazard A major page fault on an mmap region blocks the faulting TPC thread, stalling the entire shard's reactor. The Data Plane pre-fetches pages asynchronously via `io_uring IORING_OP_READ` or `madvise(MADV_WILLNEED)` before compute touches them. --- # Event Plane (docs/architecture/event-plane) --- title: Event Plane description: Async event processing for triggers, CDC, cron scheduling, and durable pub/sub. --- # Event Plane The Event Plane is the third architectural layer. It runs on Tokio (`Send + Sync`) and handles all asynchronous, event-driven work. It never does storage I/O and never spawns TPC tasks. ## Responsibilities **AFTER trigger dispatch** — Trigger bodies execute asynchronously after the write commits. Retry with exponential backoff. Persistent failures go to a dead-letter queue. `EventSource` tagging prevents trigger cascades — the Event Plane skips non-User events. **CDC / change streams** — Routes `WriteEvent` records to matching change stream consumers. Per-partition offsets, consumer groups with rebalancing, and exactly-once transactional consumption. **Cron scheduler** — 1-second evaluation loop. Scheduled SQL is dispatched back through the Control Plane → Data Plane path. Per-collection affinity runs jobs on the collection's shard leader. **Durable pub/sub** — Named topics with consumer groups, offset tracking, and configurable retention. Consumers resume from last committed offset after disconnect. **Webhook delivery** — HTTP POST with exponential backoff retry and idempotency headers. ## Event Bus (Data → Event) The Event Bus consists of one bounded ring buffer per Data Plane core — no cross-core contention. - Data Plane emits `WriteEvent` records after WAL commit - Fire-and-forget: Data Plane never blocks on Event Plane - WAL-backed: if a ring buffer overflows, the Event Plane replays from the WAL LSN watermark ## Backpressure All Event Bus queues are bounded: - **> 85% utilization** — throttled, Data Plane continues but Event Plane signals pressure - **> 95% utilization** — suspended, Event Plane enters WAL Catchup Mode (replays from WAL instead of ring buffer) All backpressure transitions emit metrics and trace events. ## Side Effects When a trigger body or scheduled job produces a write, the Event Plane dispatches it back through the normal Control Plane → Data Plane path. The Event Plane handles routing and delivery, not compute. --- # SPSC Bridge (docs/architecture/spsc-bridge) --- title: SPSC Bridge description: Bounded lock-free ring buffers connecting the Control Plane and Data Plane. --- # SPSC Bridge The SPSC (Single-Producer, Single-Consumer) bridge is the only communication path between the Control Plane and Data Plane. No `Arc>`, no shared state — only bounded, lock-free ring buffers. ## Request Envelope Control Plane → Data Plane: | Field | Type | Purpose | | ------------------ | ---------------- | ---------------------------------- | | `request_id` | u64 | Correlates request with response | | `tenant_id` | u32 | Tenant scoping | | `vshard_id` | u16 | Routes to the correct core | | `plan` | PhysicalPlan | The physical execution plan | | `deadline_ns` | u64 | Absolute deadline (monotonic clock)| | `priority` | u8 | Scheduling priority | | `trace_id` | u64 | Distributed trace propagation | | `consistency` | ReadConsistency | Read consistency level | | `idempotency_key` | Option\ | Dedup key for non-idempotent writes| | `event_source` | EventSource | User, Trigger, Raft, or CrdtSync | | `user_roles` | Vec\ | Caller's RBAC roles | ## Response Envelope Data Plane → Control Plane: | Field | Type | Purpose | | ---------------- | -------- | -------------------------------- | | `request_id` | u64 | Matches the originating request | | `status` | u8 | Success, error, partial | | `attempt` | u32 | Retry attempt counter | | `partial` | bool | Whether more results follow | | `payload` | Payload | Response data | | `watermark_lsn` | u64 | Latest committed LSN | | `error_code` | u16 | Typed error (if status != ok) | ## Memory Ownership - Cross-plane payloads use `Arc<[u8]>` or slab IDs with explicit reclaim ACK - Producer owns buffer until ACK/NACK received - Zero-copy buffers remain valid until consumer ACK ## Ordering - Strict FIFO per `(connection_id, vshard_id)` stream - Best-effort ordering across streams - Cancellation is cooperative: Control Plane emits `CANCEL(request_id)`, Data Plane stops at the next safe point ## Backpressure | Queue utilization | Action | | ----------------- | ------------------------------ | | < 85% | Normal operation | | 85% - 95% | Reduce read depth | | > 95% | Suspend new reads | All transitions are observable via metrics and trace spans. --- # Storage Tiers (docs/architecture/storage-tiers) --- title: Storage Tiers description: Three-tier storage hierarchy — RAM, NVMe, and S3 — with temperature-aware data placement. --- # Storage Tiers NodeDB uses tiered storage to match data temperature to the right medium. ## Tiers | Tier | Medium | Contents | I/O Method | | --------- | ------ | ----------------------------------------------- | --------------------- | | L0 (hot) | RAM | Memtables, active CRDT states, incoming metrics | None (in-memory) | | L1 (warm) | NVMe | HNSW graphs, metadata indexes, segment files | mmap + madvise | | L2 (cold) | S3 | Historical logs, compressed vector layers | Parquet + HTTP range | | WAL | NVMe | Write-ahead log | O_DIRECT via io_uring | ## Critical Rules **WAL uses O_DIRECT.** Bypasses the kernel page cache entirely for deterministic write latency. Group commit batches multiple writes per io_uring submission for NVMe IOPS efficiency. **L1 indexes use mmap.** Zero-copy deserialization. SIMD reads directly from mapped pages. `madvise(MADV_WILLNEED)` pre-fetches before compute touches the data. **WAL and L1 never share page cache.** O_DIRECT (WAL) and mmap (L1) use fundamentally different I/O paths. Mixing them would cause cache coherency issues. ## Per-Core Memory Each Data Plane core is pinned to a dedicated jemalloc arena via `nodedb-mem`. This eliminates allocator lock contention in the TPC architecture. Memory budgets are enforced per engine — no single engine can starve others. ## Compaction L1 segment files undergo three-phase crash-safe compaction: 1. Write new merged segments to temporary files 2. Atomically swap file references in the catalog 3. Delete old segments after all readers have released them Compaction preserves monotonic LSN ordering. Delete bitmaps (Roaring) track removed rows without rewriting segments. ## Cold Storage L2 uses Parquet format with predicate pushdown. A packed single-file format enables HTTP range requests for minimal egress from S3/GCS/Azure. --- # Write-Ahead Log (docs/architecture/wal) --- title: Write-Ahead Log description: O_DIRECT WAL with group commit, CRC32C checksums, and AES-256-GCM encryption. --- # Write-Ahead Log The WAL ensures durability. Every write is persisted to the WAL before being acknowledged. On crash recovery, the WAL replays to reconstruct any state not yet flushed to segments. ## Record Format ``` ┌──────────┬─────────────────┬────────────┬─────┬───────────┬───────────┬─────────────┬─────────┐ │ magic │ format_version │ record_type│ lsn │ tenant_id │ vshard_id │ payload_len │ crc32c │ │ 4 bytes │ 2 bytes │ 2 bytes │ 8B │ 4 bytes │ 2 bytes │ 4 bytes │ 4 bytes │ └──────────┴─────────────────┴────────────┴─────┴───────────┴───────────┴─────────────┴─────────┘ ``` ## Properties **O_DIRECT** — Bypasses the kernel page cache. Writes go directly to NVMe via io_uring. This provides deterministic write latency — no interference from page cache eviction or writeback. **Page size** — 4 KiB or 16 KiB, alignment-compatible with O_DIRECT requirements. **CRC32C** — Every page has a checksum for silent bit-rot detection. **Group commit** — Multiple writes batch into a single io_uring submission for NVMe IOPS efficiency. A double-write buffer ensures atomicity. **Segmented** — The WAL rolls over to a new segment file automatically. Old segments are eligible for cleanup once all records have been flushed to L1 segments. **Tombstone GC** — Each checkpoint garbage-collects WAL rows for collections that have been hard-deleted (tombstoned), so tombstone records do not accumulate across restarts. On replay, the startup path merges persisted WAL tombstones with tombstones extracted from the WAL itself — a crash mid-purge cannot resurrect a dropped collection. **Encryption** — Optional AES-256-GCM encryption at the page level. Key management is external. ## Crash Recovery On startup, NodeDB: 1. Scans WAL segments from the last known checkpoint 2. Validates CRC32C checksums on each page 3. Replays valid records to reconstruct in-memory state 4. Discards any partially written records (torn writes) The Event Plane uses WAL LSN watermarks to resume event processing from the correct position after a crash. ## Write Path A write is acknowledged only after: 1. WAL append is persisted (O_DIRECT + fsync) 2. Raft quorum commit (for replicated namespaces) Single-node mode: linearizable writes for shard leader. Replicated mode: linearizable writes within each Raft group. --- # Consistency Model (docs/architecture/consistency) --- title: Consistency Model description: Read consistency levels, serializable snapshot transactions, and cross-engine query consistency. --- # Consistency Model ## Write Consistency A write is acknowledged only after: - **WAL append** is persisted (O_DIRECT + fsync) - **Raft quorum commit** (for replicated namespaces) Single-node: linearizable writes for the shard leader. Replicated: linearizable writes within each Raft group. ## Read Consistency Levels ```sql -- Strong: leader-read after commit index >= required LSN (default for metadata/constraints) SET read_consistency = 'strong'; -- Bounded staleness: follower read allowed if lag <= duration SET read_consistency = 'bounded_staleness_5s'; -- Eventual: local read for CRDT edge sync (monotonic convergence) SET read_consistency = 'eventual'; ``` | Level | Behavior | Use case | | ------------------- | -------------------------------------------- | --------------------------------- | | Strong | Leader read, waits for commit index | Metadata, constraints, OLTP | | Bounded Staleness | Follower read if lag within configured bound | Read replicas, analytics | | Eventual | Local read, monotonic convergence | CRDT edge sync, NodeDB-Lite | ## Serializable Snapshot Transactions Cross-engine queries execute against a shared snapshot watermark. A query that combines vector search, graph traversal, and document field access sees a consistent point-in-time view across all engines. Transaction blocks are serializable snapshot transactions. A block reads one snapshot, taken at its first statement. Every read sees that snapshot plus the block's own writes. At `COMMIT`, at the moment the writes apply, NodeDB checks that nothing the transaction read or overwrote changed after its snapshot. If something changed, `COMMIT` fails with SQLSTATE `40001` and the client retries the whole block. - A read-only block commits without validation and never fails with `40001`. - A snapshot older than `[tuning.network] txn_snapshot_max_age_secs` (default 300) fails the next statement with `40001`. - A write that cannot be buffered inside a block is refused with SQLSTATE `25001`. - Every isolation level a client requests runs serializable. - An autocommit statement reads the current state at a per-statement cut. - `AS OF SYSTEM TIME` works on every collection. ## Cross-Model Queries RRF fusion and cross-engine joins include source watermarks in response metadata. This lets clients verify the freshness of results that span multiple engines. --- # Cluster Topology (docs/architecture/cluster-topology) --- title: Cluster Topology description: Multi-node deployment with vShards, Raft groups, and QUIC transport. --- # Cluster Topology NodeDB scales horizontally by distributing data across multiple nodes using virtual shards (vShards). ## Nodes and Roles Every node in a NodeDB cluster runs the same binary. Roles are determined by Raft group membership: - **Leader** — accepts writes and reads for its Raft groups - **Follower** — replicates from leader, serves stale reads (bounded staleness) - **Learner** — non-voting replica, used for read scaling or cross-region copies ## vShards Data is partitioned into virtual shards (vShards). Each vShard is assigned to a Raft group. A single node may host multiple vShards. Benefits of virtual sharding: - **Rebalancing** — move a vShard to a different node without reshuffling the entire dataset - **Granular replication** — each vShard can have a different replication factor - **Independent failure domains** — a vShard failure affects only the data in that shard ## Transport Cluster communication uses QUIC (via nexar + quinn). QUIC provides: - Multiplexed streams over a single connection - 0-RTT connection resumption - Built-in TLS 1.3 - Connection migration (IP address changes) ## Request Routing The Control Plane routes each request to the correct Data Plane core based on vShard assignment. If the local node does not own the target vShard, the request is forwarded to the correct node over QUIC. --- # Multi-Raft Consensus (docs/architecture/multi-raft) --- title: Multi-Raft Consensus description: Independent Raft groups per vShard for leader election, log replication, and snapshots. --- # Multi-Raft Consensus NodeDB uses Multi-Raft — each vShard is its own independent Raft group with its own leader, log, and snapshot schedule. This avoids the bottleneck of a single Raft group for the entire cluster. ## Per-vShard Raft Each Raft group handles: - **Leader election** — automatic failover when the current leader becomes unreachable - **Log replication** — WAL entries replicated to followers before acknowledgement - **Snapshots** — periodic state snapshots to truncate the Raft log ## Write Path (Replicated) 1. Client sends write to the vShard leader 2. Leader appends to local WAL 3. Leader replicates to Raft followers 4. Quorum acknowledges (majority of replicas) 5. Leader commits and responds to client Writes are linearizable within each Raft group. ## Raft group kinds NodeDB runs three kinds of Raft groups simultaneously: | Kind | Purpose | Count | |---|---|---| | **Data** | One per vShard — replicates WAL entries for that shard's data | One per vShard | | **Meta** | Cluster membership, catalog, schema | One per cluster | | **Sequencer** | Cross-shard transaction ordering (Calvin epoch log) | One per cluster | Each kind has independent leader election. A sequencer leader failure does not affect data-group leaders, and vice versa. ### Sequencer Raft group The sequencer group exists solely to produce a globally-ordered log of cross-shard transaction batches (epochs). It has its own dedicated group ID outside the data-group range so it can never accidentally alias a vShard. See [Cross-Shard Transactions](./cross-shard-transactions) for how the sequencer group interacts with the scheduler and executor. Single-shard writes never touch the sequencer group — they go directly through the relevant data-group's Raft. ## Advantages of Multi-Raft - **Independent leaders** — different vShards can have leaders on different nodes, distributing write load - **Parallel commits** — vShards commit independently, no global ordering bottleneck - **Granular failover** — a node failure only triggers leader election for the vShards it led, not the entire cluster - **Failure isolation** — sequencer leader election is independent of data and meta group elections --- # vShards (docs/architecture/vshards) --- title: vShards description: Virtual sharding for data distribution, rebalancing, and per-shard replication. --- # vShards Virtual shards (vShards) are NodeDB's unit of data distribution. Each collection's data is partitioned across vShards, and each vShard maps to a Raft group and a Data Plane core. ## How vShards Work - Data is hashed to a vShard based on the document ID (or a configured shard key) - Each vShard is assigned to a node and a specific Data Plane core on that node - The assignment is tracked in the cluster catalog and updated during rebalancing ## Rebalancing When nodes join or leave the cluster, vShards are redistributed: 1. The coordinator selects vShards to move based on load metrics 2. Target node begins replicating the vShard's data 3. Once caught up, ownership transfers atomically in the catalog 4. Old node drops the vShard data Rebalancing is transparent to clients — requests are forwarded to the new owner during migration. There is no downtime. ## Shard Count The number of vShards is set at cluster creation and does not change. Choose a count that is several times the expected maximum number of cores across all nodes — this gives the rebalancer enough granularity to distribute evenly. --- # Replication (docs/architecture/replication) --- title: Replication description: Raft-based replication with configurable replication factor per vShard. --- # Replication NodeDB replicates data via Raft log replication. Each vShard's Raft group independently replicates its WAL entries to followers. ## Replication Factor Configurable per collection or per vShard: - **RF=1** — no replication, single-node durability only - **RF=3** — default for production, tolerates one node failure - **RF=5** — high durability, tolerates two node failures ## How Replication Works 1. Leader receives a write and appends to its WAL 2. WAL entry is sent to all followers in the Raft group 3. Each follower appends to its own WAL and acknowledges 4. Leader waits for a quorum (majority) of acknowledgements 5. Leader commits the entry and responds to the client ## Follower Reads Followers can serve reads with bounded staleness: ```sql SET read_consistency = 'bounded_staleness_5s'; SELECT * FROM orders WHERE status = 'pending'; ``` The follower checks that its replication lag is within the configured bound before serving the read. If the lag exceeds the bound, the read is forwarded to the leader. ## Cross-Region Replication Learner replicas (non-voting Raft members) can be placed in remote regions for read scaling. They replicate asynchronously and do not participate in quorum decisions, so they do not add write latency. --- # Cross-Shard Transactions (docs/architecture/cross-shard-transactions) --- title: Cross-Shard Transactions description: Calvin sequencer architecture for deterministic, atomically-committed cross-shard writes. --- # Cross-Shard Transactions When a write touches rows that hash to more than one vShard, NodeDB routes it through the **Calvin sequencer** — a dedicated Raft-backed coordination layer that guarantees all participating shards commit the transaction in the same order, with no mid-flight aborts. Single-shard writes bypass this entirely and take the normal per-vShard Raft fast path. ## Why Calvin, not 2PC Two-phase commit with compensating actions was the earlier design. It was replaced because compensation creates observable intermediate states (a row exists, then disappears), compensation can itself fail, and every read path that crosses an in-flight transaction has to know about pending compensations. The concern spreads outward indefinitely. Calvin (Thomson et al., SIGMOD 2012) eliminates the problem by validating the full read/write set *before* any shard touches the transaction. Every shard executes against a globally-ordered input log. There is no concept of "shard A committed, shard B failed" — either all shards execute the transaction or none do. ## Architecture ``` Client / Control Plane │ declares read/write set ▼ SEQUENCER (dedicated Raft group, Control Plane) │ batches transactions into epochs (default 20 ms) │ replicates each epoch via Raft — globally ordered ▼ SCHEDULER (per vShard, Control Plane) │ acquires locks in deterministic global order │ single-threaded per shard ▼ EXECUTOR (Data Plane, existing engine handlers) │ executes deterministically using the sequenced batch │ no application-level aborts — all constraint checks happen upstream ``` ### The sequencer Raft group The sequencer runs as its own independent Raft group (`SEQUENCER_GROUP_ID`), separate from the per-vShard data groups and the metadata group. This means: - **Failure isolation** — sequencer leader election doesn't disrupt metadata reads, schema operations, or data writes - **Independent tuning** — epoch duration (default 20 ms) is tuned separately from data-group commit latency - **Geographic placement** — the sequencer triad can sit on the lowest-latency nodes without constraining where data groups live ### Epochs The sequencer leader batches incoming transactions into epoch windows (default 20 ms). At the end of each window it: 1. Runs a pre-validation pass — detects intra-batch write-set conflicts; admits the first txn for a conflicting key, rejects others with `SequencerConflict` so the client retries 2. Proposes the validated batch to the sequencer Raft group 3. Once committed, fans the epoch out to each participating vShard's scheduler ### Determinism All replicas must produce byte-identical WAL output for the same epoch. The executor is forbidden from using wall-clock time, non-seeded randomness, or non-deterministic map iteration on the cross-shard write path. System-time columns (bitemporal `sys_from`, KV TTL expiry, graph HLC ordinals) are seeded from the epoch timestamp so all replicas stamp the same value. ## Session variable ```sql -- Default: route multi-vShard writes through the sequencer (atomic) SET cross_shard_txn = 'strict'; -- Explicit opt-out: each shard commits independently (NOT atomic) SET cross_shard_txn = 'best_effort_non_atomic'; SHOW cross_shard_txn; ``` `best_effort_non_atomic` is intended for bulk loads where atomicity is not required. It is deliberately named to discourage accidental use. ## EXPLAIN output `EXPLAIN` reports whether a query routes through the sequencer: ```sql EXPLAIN INSERT INTO orders VALUES (...); -- cross-shard: sequenced | vshards: [3, 7] | epoch: | position: EXPLAIN INSERT INTO local_cache VALUES (...); -- single-shard: vshard 3 ``` ## OLLP — value-dependent predicates For `UPDATE ... WHERE balance > 10000` where the write set depends on a scan result, NodeDB uses Optimistic Lock Location Prediction: 1. The planner runs the query optimistically once to capture the predicted write set 2. Submits to the sequencer with the predicted set 3. At execution time the executor re-scans and compares — if the set changed due to a concurrent commit, it returns `OllpRetryRequired` and retries transparently To prevent retry storms, each predicate class (the parsed predicate AST, ignoring bound parameters) has: - **Adaptive backoff** — starts at 10 ms, doubles up to 5 s - **Circuit breaker** — opens after >50% retry rate over a 60 s window; half-opens after 30 s; closes after 4 consecutive successes - **Per-tenant budget** — 1000 retries/min per tenant; excess returns `OllpTenantBudgetExceeded` Static predicates (`WHERE id IN (...)`, `WHERE id = ?`) compute a deterministic write set at parse time and never enter the OLLP path. ### Predicate writes inside a transaction A predicate `UPDATE` or `DELETE` inside `BEGIN … COMMIT`, a trigger body, or a procedure body reads its matching rows at its own statement, as the transaction sees them. The statement fails at once if the rows change before it stages, after the same backoff and retry budget. At `COMMIT`, each participant checks the predicted rows again at the statement's turn in the transaction. If a concurrent commit changed them, the transaction aborts on every participant with SQLSTATE `40001`, and the client retries the whole transaction. A transaction cannot be retried in place, because its other statements read the data it saw. ## Admission limits The sequencer enforces caps to prevent a single transaction from monopolising the cluster: | Cap | Default | Error on exceed | |---|---|---| | `max_plans_bytes_per_txn` | 1 MiB | `TxnTooLarge` | | `max_participating_vshards_per_txn` | 64 | `FanoutTooWide` | | `max_txns_per_epoch` | 1024 | queued to next epoch | | `max_bytes_per_epoch` | 16 MiB | queued to next epoch | | Per-tenant inbox quota | inbox / 8 | `TenantQuotaExceeded` | ## Failure modes | Failure | Behaviour | |---|---| | Sequencer leader dies | Raft re-elects; in-flight inbox submissions dropped; clients see `Unavailable` and retry | | Sequencer follower dies | No client-visible impact; quorum remains | | Scheduler shard crashes | Rebuilt from sequencer log on restart; shard unavailable until rebuild completes | | Executor panic mid-apply | Locks held; shard restarts and replays the txn from WAL (determinism ensures identical result) | | Network partition | Partitioned shard stops applying new epochs; serves reads with snapshot semantics; catches up on heal | ## Metrics | Metric | Type | Description | |---|---|---| | `nodedb_sequencer_epochs_total` | counter | Epochs proposed | | `nodedb_sequencer_epoch_duration_ms` | histogram | Time to drain + propose each epoch | | `nodedb_sequencer_admitted_txns_total{outcome}` | counter | Per-outcome admission counts (`admitted`, `rejected_conflict`, `rejected_inbox_full`, `rejected_txn_too_large`, `rejected_fanout_too_wide`, `rejected_tenant_quota`, `rejected_not_leader`) | | `nodedb_sequencer_inbox_depth` | gauge | Pending txns in the inbox | | `nodedb_calvin_scheduler_lock_wait_ms_total{vshard}` | counter | Cumulative lock-wait time per shard | | `nodedb_calvin_executor_txn_duration_ms{vshard}` | histogram | Per-shard execution time | | `nodedb_calvin_ollp_retries_total{predicate_class,outcome}` | counter | OLLP retry outcomes | | `nodedb_calvin_ollp_circuit_state{predicate_class}` | gauge | 0=closed, 1=half-open, 2=open | | `nodedb_calvin_ollp_backoff_ms{predicate_class}` | gauge | Current OLLP backoff delay | | `nodedb_calvin_infra_abort_total{reason}` | counter | Infrastructure-level aborts (disk error, OOM, etc.) | --- # Collections (docs/data-modeling/collections) --- title: Collections description: Collections are NodeDB's top-level data containers. Each collection has a storage engine chosen at creation time. --- # Collections A collection is NodeDB's top-level data container — analogous to a table in PostgreSQL or a collection in MongoDB. Each collection has a storage engine chosen at creation time. ## Creating Collections ```sql -- Schemaless document (default) CREATE COLLECTION users; -- Strict document (schema-enforced) CREATE COLLECTION orders ( id UUID DEFAULT gen_uuid_v7(), customer_id UUID NOT NULL, total DECIMAL NOT NULL, status STRING DEFAULT 'pending' ) WITH (engine='document_strict'); -- Columnar (analytics) CREATE COLLECTION events ( ts TIMESTAMP TIME_KEY, user_id UUID, event VARCHAR, duration_ms INT ) WITH (engine='columnar'); -- Key-Value CREATE COLLECTION sessions (key TEXT PRIMARY KEY) WITH (engine='kv'); ``` ## Storage Engines NodeDB has eight peer engines. Seven of them are picked per collection via `WITH (engine='')` — the default (no `engine=`) is `document_schemaless`. The eighth, Array, uses its own `CREATE ARRAY` DDL family. See [Array Engine](../storage-engines/array) for that path. | Engine | Selector | Best for | | --------------------- | ----------------------------------- | ------------------------------------------------- | | `document_schemaless` | (default) | Flexible data, prototyping, agent state | | `document_strict` | `WITH (engine='document_strict')` | OLTP, transactions, known schemas | | `columnar` | `WITH (engine='columnar')` | Analytics, reporting, scan-heavy workloads | | `timeseries` | `WITH (engine='timeseries')` | Append-only metrics, retention, continuous aggs | | `spatial` | `WITH (engine='spatial')` | Geo-primary workloads, R*-tree, OGC predicates | | `kv` | `WITH (engine='kv')` | Sessions, caches, counters, key-dominant access | | `vector` | `WITH (engine='vector', vector_field='emb', dim=384)` | Vector-primary collections | Column modifiers add capabilities to any engine: | Modifier | Effect | | ---------------- | ----------------------------------------------------------------- | | `TIME_KEY` | Marks the time column (used by timeseries engine, allowed elsewhere) | | `SPATIAL_INDEX` | R*-tree index on a `GEOMETRY` column | | `PRIMARY KEY` | Row identity column (inline only — table-level not supported) | ## Cross-Engine Indexes Any collection can have indexes from multiple engines: ```sql CREATE COLLECTION products; -- Add a vector index for semantic search CREATE VECTOR INDEX ON products METRIC cosine DIM 384; -- Add a full-text index for keyword search CREATE SEARCH INDEX ON products FIELDS title, description ANALYZER 'english'; -- Add a spatial index for location queries CREATE SPATIAL INDEX ON products FIELDS location; -- Add graph edges for relationships GRAPH INSERT EDGE IN 'products' FROM 'products:p1' TO 'products:p2' TYPE 'similar'; ``` ## Converting Between Engines Collections can be converted at any time without data loss: ```sql CONVERT COLLECTION users TO document_strict; CONVERT COLLECTION cache TO kv; CONVERT COLLECTION events TO document_schemaless; ``` NodeDB infers the schema from existing documents when converting to strict mode. --- # Schemas & Types (docs/data-modeling/schemas-types) --- title: Schemas & Types description: Data types, schema enforcement, typeguards, and schema evolution. --- # Schemas & Types ## Data Types | Type | Description | Example | | ----------- | ------------------------------------ | ---------------------- | | `STRING` | UTF-8 text | `'hello'` | | `TEXT` | Alias for STRING | `'hello'` | | `VARCHAR` | Alias for STRING | `'hello'` | | `INT` | 64-bit signed integer | `42` | | `FLOAT` | 64-bit IEEE 754 | `3.14` | | `DECIMAL` | Arbitrary precision | `99.99` | | `BOOL` | Boolean | `true` | | `TIMESTAMP` | UTC timestamp (nanosecond precision) | `now()` | | `DATETIME` | Alias for TIMESTAMP | `'2026-01-01T00:00Z'` | | `UUID` | 128-bit UUID | `gen_uuid_v7()` | | `GEOMETRY` | OGC geometry (WKB internally) | `ST_Point(-73.9, 40.7)`| | `ARRAY` | Ordered list | `ARRAY[1, 2, 3]` | | `OBJECT` | Nested document | `{ name: 'Alice' }` | ## Schema Modes **Schemaless** — No schema required. Fields can vary between documents. Types are inferred on insert. This is the default when you `CREATE COLLECTION x`. **Strict** — Schema is defined at creation time and enforced on every write. O(1) field extraction via binary tuple format. Created with `(...) WITH (engine='document_strict')`. ## Typeguards (Schemaless Validation) Typeguards add write-time validation to schemaless collections without changing the storage format. Guarded fields are type-checked; unguarded fields pass freely. ```sql CREATE TYPEGUARD ON users ( email STRING REQUIRED CHECK (email LIKE '%@%.%'), age INT CHECK (age >= 0 AND age <= 150), role STRING DEFAULT 'user', slug STRING VALUE LOWER(REPLACE(title, ' ', '-')) ); ``` | Modifier | Behavior | | ---------- | --------------------------------------------------------- | | `REQUIRED` | Field must be present and non-null | | `DEFAULT` | Inject a value when the field is absent or null | | `VALUE` | Always inject/overwrite (computed fields) | | `CHECK` | SQL boolean expression validated at write time | Every write form enforces the guards: `INSERT … VALUES`, `INSERT … { }`, `INSERT … SELECT`, `UPSERT`, `UPDATE`, `MERGE`, and native puts, batches and updates. | Rule | Behavior | | ------------------------ | ---------------------------------------------------------------------------------------------------------- | | Deterministic expressions | `DEFAULT` and `VALUE` are evaluated on every write. `now()`, `uuid_v7()` and `nextval()` are refused. | | `UPDATE` | `VALUE` recomputes. `DEFAULT` refills a field that is absent or set to null. | | `UPDATE` validation | `REQUIRED` and type are checked for the assigned and injected fields. `CHECK` runs whenever its field is present. | | CRDT collections | Only `REQUIRED`, type and `CHECK` are accepted. Every replica merges the state, so nothing is injected. The guards judge the merged row each write produces. | ```sql -- Modify guards ALTER TYPEGUARD ON users ADD score FLOAT CHECK (score >= 0); ALTER TYPEGUARD ON users DROP age; -- Audit existing data against guards VALIDATE TYPEGUARD ON users; -- Graduate to strict schema CONVERT COLLECTION users TO document_strict; ``` `CONVERT … TO document_strict` carries each guard onto the converted schema: | Guard clause | Converted to | | ---------------------- | ------------------------------------------------------------------- | | `VALUE expr` | A `GENERATED ALWAYS AS (expr)` column | | Constant `DEFAULT` | A column `DEFAULT` | | Cross-field `DEFAULT` | Refused: a column `DEFAULT` is evaluated with no row in scope | | `CHECK` | A `CHECK` constraint | The converted schema keeps the source primary key. A column list that omits it is refused. ## Schema Evolution (Strict Mode) ```sql -- Add a column with a default (zero-downtime, multi-version reads) ALTER COLLECTION orders ADD COLUMN region STRING DEFAULT 'us-east'; -- Drop a column ALTER COLLECTION orders DROP COLUMN region; ``` `ALTER ADD COLUMN` uses multi-version reads — existing rows are served with the default value without rewriting storage. New writes include the column natively. --- # Document Engine (docs/storage-engines/document) --- title: Document Engine description: Two modes — schemaless (MessagePack, CRDT sync) and strict (Binary Tuples, O(1) field extraction). --- # Document Engine NodeDB supports two document storage modes per collection. Choose based on your workload and convert at any time. ## Schemaless Documents Flexible JSON-like documents stored as MessagePack. No schema required — fields can vary between documents. ```sql CREATE COLLECTION users; INSERT INTO users { name: 'Alice', email: 'alice@example.com', age: 30 }; INSERT INTO users { name: 'Bob', role: 'admin', tags: ['ops', 'dev'] }; -- Standard SQL also works INSERT INTO users (id, name, email) VALUES ('u3', 'Charlie', 'charlie@example.com'); CREATE INDEX ON users FIELDS email; SELECT * FROM users WHERE age > 25; ``` **Best for:** Prototyping, AI agent state, user profiles, nested data, CRDT sync. ## Strict Documents Schema-enforced documents stored as Binary Tuples with O(1) field extraction. The engine jumps directly to the byte offset of any column — 3-4x better cache density than MessagePack or BSON. ```sql CREATE COLLECTION orders ( id UUID DEFAULT gen_uuid_v7(), customer_id UUID NOT NULL, total DECIMAL NOT NULL, status STRING DEFAULT 'pending', created_at TIMESTAMP DEFAULT now() ) WITH (engine='document_strict'); INSERT INTO orders (customer_id, total, status) VALUES ($cust_id, 149.99, 'shipped'); SELECT * FROM orders WHERE id = '...'; -- Schema evolution (zero-downtime) ALTER COLLECTION orders ADD COLUMN region STRING DEFAULT 'us-east'; ``` **Best for:** OLTP, transactions, known schemas, HTAP with columnar materialized views. ## Comparison | | Schemaless | Strict | | ------------- | ------------------------------ | ------------------------------- | | Schema | Flexible, evolves freely | Fixed, enforced on write | | Field access | Parse MessagePack | O(1) byte offset | | Cache density | Good | 3-4x better | | CRDT sync | Native | Via adapter | | HTAP | No | Yes (materialized views) | ## Typeguards Add validation to schemaless collections without changing to strict mode: ```sql CREATE TYPEGUARD ON users ( email STRING REQUIRED CHECK (email LIKE '%@%.%'), age INT CHECK (age >= 0 AND age <= 150), role STRING DEFAULT 'user' ); ``` See [Schemas & Types](/docs/data-modeling/schemas-types) for full typeguard reference. ## Converting ```sql CONVERT COLLECTION users TO document_strict; -- schemaless → strict CONVERT COLLECTION logs TO columnar; -- document → columnar CONVERT COLLECTION cache TO kv; -- document → key-value ``` --- # Key-Value Engine (docs/storage-engines/kv) --- title: Key-Value Engine description: Hash-indexed O(1) point lookups with TTL, atomic operations, sorted indexes, and rate gates. --- # Key-Value Engine Purpose-built hash-indexed store with O(1) point lookups, native TTL, and secondary indexes. Unlike a standalone KV store, data is SQL-queryable, joinable, and syncable via CRDTs. ## When to Use - Session state and tokens - Feature flags and configuration - Rate limiters and counters - Caching without an external cache - Leaderboards and rankings ## SQL Usage ```sql CREATE COLLECTION sessions (key TEXT PRIMARY KEY) WITH (engine='kv'); -- Insert with TTL; plain INSERT raises unique_violation (23505) on duplicate key. INSERT INTO sessions { key: 'sess_abc', user_id: 'alice', role: 'admin', ttl: 3600 }; -- Set-or-overwrite (Redis SET semantics) UPSERT INTO sessions { key: 'sess_abc', user_id: 'alice', role: 'admin', ttl: 3600 }; -- Set-if-absent (Redis SETNX semantics) INSERT INTO sessions { key: 'sess_abc', user_id: 'alice', role: 'admin', ttl: 3600 } ON CONFLICT DO NOTHING; -- Conditional merge: bump counter on conflict, EXCLUDED references the incoming row. INSERT INTO sessions (key, user_id, role, hits) VALUES ('sess_abc', 'alice', 'admin', 1) ON CONFLICT (key) DO UPDATE SET role = EXCLUDED.role, hits = sessions.hits + 1; -- Get by key SELECT * FROM sessions WHERE key = 'sess_abc'; -- Analytical queries work too SELECT role, COUNT(*) FROM sessions GROUP BY role; -- Join with other collections SELECT u.name, s.role FROM users u JOIN sessions s ON u.id = s.user_id; ``` ## Atomic Operations ```sql SELECT KV_INCR('counters', 'page_views', 1); SELECT KV_DECR('credits', 'user-123', 50); SELECT KV_CAS('state', 'player-1', 'idle', 'in_match'); SELECT KV_GETSET('token', 'sess-1', 'new-token'); SELECT KV_INCR('daily_logins', 'user-1', 1, TTL => 86400); ``` ## Sorted Indexes (Leaderboards) ```sql CREATE SORTED INDEX lb_global ON scores (score DESC, updated_at ASC) KEY player_id; SELECT RANK(lb_global, 'player-123'); SELECT * FROM TOPK(lb_global, 10); SELECT * FROM RANGE(lb_global, 100, 250.5); SELECT SORTED_COUNT(lb_global); -- Time-windowed leaderboard CREATE SORTED INDEX lb_daily ON scores (score DESC, updated_at ASC) KEY player_id WINDOW DAILY ON updated_at; -- Fixed-range window: bounds are milliseconds or ISO 8601 CREATE SORTED INDEX lb_season ON scores (score DESC, updated_at ASC) KEY player_id WINDOW CUSTOM START '2026-01-01' END '2026-04-01' ON updated_at; ``` ### Sort Order Each sort column orders its values by type first, then by value: | Order | Type | Order within the type | | ----- | ---- | --------------------- | | 1 | null | — | | 2 | boolean | `false` before `true` | | 3 | number | numeric value | | 4 | string | byte order of the UTF-8 text | | 5 | array or object | byte order of the JSON text | - Integers and floats share one numeric order. `10.5` sorts between `10` and `11`. - The order is exact for every 64-bit integer and every float. Integers above 2^53 keep their order. - An integer and a float of equal value are equal. `11` and `11.0` hold one position. - `-0.0` equals `0`. - A non-finite float is stored as the text `NaN`, `Infinity` or `-Infinity`, so it sorts as a string. - `RANGE(index, min, max)` is inclusive at both ends and reads the first sort column. An integer bound matches a float row of equal value. - `DESC` reverses all of the above for that column. ### Window Rules - The window timestamp column must be one of the sort columns. `CREATE SORTED INDEX` refuses the index otherwise (SQLSTATE `42601`). - `ON` defaults to `updated_at` when the clause names no column. - `DAILY`, `WEEKLY` (from Monday) and `MONTHLY` windows start at 00:00 UTC of the current period. - A `CUSTOM` window is the half-open range `[START, END)`. `END` must be after `START`. - A `CUSTOM` bound is integer milliseconds since the Unix epoch or an ISO 8601 date or instant. - A timestamp value is one of: - an integer: milliseconds since the Unix epoch; - a float: fractional milliseconds since the Unix epoch; - a string: an ISO 8601 date or instant. - Integers are milliseconds. A value in epoch seconds lands in January 1970 and falls outside current windows. - A row whose timestamp is null, a boolean, an array, an object, or a non-ISO 8601 string is hidden from every window. - A row without the timestamp field is not indexed. ## Rate Gates ```sql SELECT RATE_CHECK('attack_cooldown', 'player-123', 3, 10); -- {"allowed": true, "remaining": 2, "resets_in_ms": 7500} SELECT RATE_REMAINING('api_calls', 'tenant-1', 100, 60); SELECT RATE_RESET('attack_cooldown', 'player-123'); ``` ## Redis-Compatible Access (RESP) Enable by setting `ports.resp = 6381` in config. Any Redis client works: ```bash redis-cli -p 6381 SET sess_abc '{"user":"alice"}' EX 3600 GET sess_abc INCR page_views ZADD leaderboard 1500 player-123 ZRANK leaderboard player-123 ``` Supported: GET, SET, DEL, EXISTS, MGET, MSET, EXPIRE, TTL, SCAN, KEYS, HGET, HSET, INCR, DECR, ZADD, ZREM, ZRANK, ZRANGE, SUBSCRIBE, PUBLISH, and more. --- # Columnar Engine (docs/storage-engines/columnar) --- title: Columnar Engine description: Per-column compression with block statistics, predicate pushdown, and 20-40x compression ratios. --- # Columnar Engine Typed columns with per-column compression — the same approach as ClickHouse and DuckDB, living alongside your OLTP data. ## When to Use - Analytical queries (GROUP BY, aggregations, window functions) - Reporting dashboards - Data science workloads - Any scan-heavy workload reading few columns from many rows - HTAP: pair with strict documents for combined OLTP + OLAP ## Compression Codecs Each column gets a codec chain tuned for its data type: | Codec | Target | Approach | | ---------- | ----------------------------- | ----------------------------------- | | ALP | Floats | Lossless float-to-integer conversion | | FastLanes | Integers | SIMD bit-packing | | FSST | Strings | Substring dictionary compression | | Gorilla | Metrics | XOR-based compression | | Pcodec | Complex numerics | Adaptive numeric compression | | rANS | Cold-tier data | Entropy coding | | LZ4 | All | Terminal stage compression | Multi-stage pipeline achieves 20-40x compression on typical workloads. ## Block Statistics Data is stored in 1024-row blocks. Each block has min/max/null-count statistics. The query engine skips blocks that can't match the predicate — no decompression needed. ## DDL ```sql -- Plain columnar CREATE COLLECTION logs ( ts TIMESTAMP TIME_KEY, host VARCHAR, level VARCHAR, message VARCHAR ) WITH (engine='columnar'); -- Timeseries (peer engine — append-only, retention, continuous aggregates) CREATE COLLECTION metrics ( ts TIMESTAMP TIME_KEY, host VARCHAR, cpu FLOAT ) WITH (engine='timeseries', partition_by='1h'); -- Spatial (peer engine — R-tree + geohash + OGC predicates) CREATE COLLECTION locations ( geom GEOMETRY SPATIAL_INDEX, name VARCHAR ) WITH (engine='spatial'); ``` ## Queries ```sql -- Point-get by primary key hits the segment PK index (not a full scan). SELECT * FROM logs WHERE ts = '2026-04-24T10:00:00Z'; SELECT level, COUNT(*) FROM logs WHERE ts > now() - INTERVAL '1 hour' GROUP BY level ORDER BY COUNT(*) DESC; -- ORDER BY is supported on columnar scans SELECT ts, host, message FROM logs WHERE level = 'error' ORDER BY ts DESC LIMIT 100; -- Window functions SELECT host, message, ROW_NUMBER() OVER (PARTITION BY host ORDER BY ts DESC) AS rank FROM logs; ``` Plain `INSERT` on a columnar collection raises `unique_violation` on primary-key conflict; use `UPSERT` or `INSERT ... ON CONFLICT (pk) DO UPDATE SET col = EXCLUDED.col` for overwrite semantics. ## HTAP Bridge Combine strict (OLTP) with columnar (OLAP): ```sql CREATE COLLECTION orders (...) WITH (engine='document_strict'); CREATE MATERIALIZED VIEW order_analytics AS SELECT status, DATE_TRUNC('day', created_at) AS day, COUNT(*), SUM(total) FROM orders GROUP BY status, day; -- Point lookups → strict engine. Scans → columnar engine. Automatic routing. ``` ## Delete Bitmaps Deleted rows are tracked with Roaring Bitmaps. Three-phase crash-safe compaction reclaims space: write new segments → swap references → delete old segments. --- # Timeseries Engine (docs/storage-engines/timeseries) --- title: Timeseries Engine description: Peer engine for time-ordered data with retention, continuous aggregation, ILP ingest, and PromQL. --- # Timeseries Engine Timeseries is a peer engine sharing storage with `columnar` and `spatial`. It adds retention policies, continuous aggregation, ILP ingest, and dedicated time-series SQL functions. Data is stored in the same compressed-column memtables with a `TIME_KEY` column driving partition-by-time and block-level skip. Selected via `WITH (engine='timeseries')` on `CREATE COLLECTION`, or the `CREATE TIMESERIES ` convenience alias. ## DDL ```sql CREATE COLLECTION cpu_metrics ( ts TIMESTAMP TIME_KEY, host VARCHAR, region VARCHAR, cpu_usage FLOAT, mem_usage FLOAT ) WITH (engine='timeseries', partition_by='1d', retention='90d'); -- Convenience alias CREATE TIMESERIES cpu_metrics; ``` ## Partitions Rows land in an in-memory buffer first. A flush of that buffer writes one sealed partition for each `partition_by` interval its rows fall in. The partitions of one flush appear together: a crash leaves all of them or none. | `partition_by` | Interval | | -------------------- | --------------------------------------------------------------- | | not set | One hour. A flush whose rows span several hours writes one partition per hour. | | `30s`, `15m`, `1h`, `1d`, `1w` | A fixed duration, aligned to multiples of itself from the Unix epoch. | | `1M` | A calendar month, starting at 00:00 UTC on the first day. | | `1y` | A calendar year, starting at 00:00 UTC on 1 January. | | `UNBOUNDED` | One partition per flush. | | `AUTO` | Starts at one day. It narrows to one hour once a core ingests more than 100,000 rows a second. | - `ALTER TIMESERIES SET (partition_by = '…')` applies to later flushes only. A partition already on disk keeps the interval it was cut at. - A late row, one whose interval an earlier flush already sealed, forms a new partition in that interval. A sealed partition is never rewritten to take it. The maintenance tick later merges the partitions of that interval (see [Merging](#merging)). ```sql -- List the partitions of a timeseries collection SHOW PARTITIONS FOR cpu_metrics; -- Rewrite every sealed partition with the current schema and codecs REWRITE PARTITIONS FOR cpu_metrics; ``` `SHOW PARTITIONS FOR` returns one row per partition: | Column | Meaning | | ------------- | ----------------------------------------------------------------------- | | `partition` | The partition name. | | `state` | `Active`, `Sealed` or `Merged`. | | `min_ts` | The earliest row timestamp, in milliseconds. | | `max_ts` | The latest row timestamp, in milliseconds. | | `rows` | The row count. | | `size` | The size on disk. | | `interval_ms` | The width of the interval the partition was cut at. `0` means `UNBOUNDED`. | `REWRITE PARTITIONS FOR` rewrites each sealed partition and drops every column the collection no longer has. The rows do not change. The statement returns after the last partition is rewritten and reports how many partitions it rewrote. It needs the `ALTER` privilege on the collection. Both statements read the collection in the current database. Neither runs inside a transaction. `SHOW PARTITIONS ON ` is a different statement: it lists a change stream's partitions (see [Consumer Groups](../real-time/consumer-groups)). ### Merging Late rows leave an interval with several partitions that overlap in time. The maintenance tick merges the partitions of one interval into one `Merged` partition. A merge moves rows and never changes them. - A merge runs on the core that owns the collection, and on each replica for its own partitions. Partition names differ between replicas. Rows do not. - An interval merges once it ended `merge_quiet_ms` ago, so late rows still arriving for it flush first. `COMPACT ` runs every merge at once, including the merge of an interval that has not ended. - A merged partition stays within one interval, so retention removes its rows at most one interval later than it would remove the separate partitions. On a bitemporal collection, partitions whose system times lie more than one interval apart do not merge. - A `UNBOUNDED` collection has no interval to merge within. Its partitions do not merge. - A crash at any point leaves every row in exactly one partition. Restart finishes a merge that committed and discards one that did not. - Encrypted partitions merge with the segment key, and the merged partition is encrypted with it. A merge keeps every continuous aggregate exact. It waits while an aggregate has folded some partitions of the interval and not others: - An `on_flush` or `on_seal` aggregate folds the missing partitions on the next tick, and the interval merges after that. - An interval-refreshed or `manual` aggregate folds them at its next refresh. A `manual` aggregate that is never refreshed keeps such an interval unmerged. | `[tuning.timeseries]` key | Default | Meaning | | ------------------------- | ------- | ------- | | `merge_groups_per_tick` | `2` | Partition groups one maintenance tick merges. `0` turns merging off. `COMPACT` ignores it. | | `merge_max_rows` | `4000000` | Most rows one merge reads and writes. A larger interval merges in several groups. | | `merge_quiet_ms` | `60000` | How long after an interval ends its partitions merge. | ## Queries ```sql -- Time-bucketed aggregation SELECT time_bucket('5 minutes', ts) AS bucket, host, AVG(cpu_usage) AS avg_cpu FROM cpu_metrics WHERE ts > now() - INTERVAL '1 hour' GROUP BY bucket, host ORDER BY bucket DESC; -- Approximate aggregation (mergeable across shards) SELECT approx_count_distinct(host), approx_percentile(cpu_usage, 0.95) FROM cpu_metrics WHERE ts > now() - INTERVAL '24 hours'; ``` ## Continuous Aggregation A continuous aggregate folds new rows into per-bucket state. It never re-scans the source. ```sql CREATE CONTINUOUS AGGREGATE cpu_hourly ON cpu_metrics BUCKET '1h' AGGREGATE avg(cpu_usage) AS avg_cpu, ts_percentile(cpu_usage, 0.99) AS p99_cpu GROUP BY host WITH (refresh_interval = '1m', retention = '365d'); REFRESH CONTINUOUS AGGREGATE cpu_hourly; ``` `BUCKET` sets the bucket width. Do not use `time_bucket(...)` in the definition. | Clause | Meaning | | ------ | ------- | | `AGGREGATE f(col) [AS alias], ...` | Outputs. Functions: `count`, `sum`, `avg`, `min`, `max`, `first`, `last`, `count_distinct`, `approx_count_distinct`, `percentile(col, q)` (also `ts_percentile`, `approx_percentile`), `topk(col, k)` (also `approx_topk`). `q` is in `[0, 1]`. `k` is at least 1. Use `count(*)` to count rows. | | `GROUP BY col, ...` | Optional. Adds group columns to each bucket. | | `refresh_policy` | `on_flush` (default), `on_seal`, `manual`, or an interval such as `'5m'` (folds periodically). | | `refresh_interval` | Interval such as `'1m'`. Folds periodically on the maintenance tick. | | `retention` | Interval after which the aggregate drops old buckets. | Refresh behavior: - `on_flush` and `on_seal` fold each flushed partition once. - An interval `refresh_policy` or `refresh_interval` folds on the maintenance tick at that interval. - `manual` folds only on `REFRESH CONTINUOUS AGGREGATE`. A read serves the last refresh. Aggregate state survives restart. It keeps its history after raw retention removes the source rows. `SELECT * FROM cpu_hourly` returns one row per bucket and group. Columns are `bucket`, the `GROUP BY` columns, then the outputs. The aggregate is read-only. ## Timeseries SQL Functions | Function | What it does | | ---------------------- | ------------------------------------ | | `ts_rate` | Per-second rate of change | | `ts_delta` | Difference between consecutive values| | `ts_moving_avg` | Moving average over a window | | `ts_ema` | Exponential moving average | | `ts_interpolate` | Gap-fill with interpolated values | | `ts_percentile` | Percentile calculation | | `ts_zscore` | Z-score anomaly detection | | `ts_bollinger_upper/lower/mid/width` | Bollinger Bands | | `ts_moving_percentile` | Rolling percentile | | `ts_correlate` | Correlation between two series | | `ts_lag` / `ts_lead` | Previous/next value in a series | ## ILP Ingest Enable with `ports.ilp = 8086`. Any ILP-compatible client (Telegraf, Vector) pushes metrics directly: ```bash echo "cpu,host=web-01 usage=72.5 1609459200000000000" | nc localhost 8086 ``` Adaptive batching and per-series core routing — self-tuning, no configuration needed. ## Grafana / PromQL NodeDB works as a native Grafana Prometheus data source at `http://nodedb:6480/v1/obsv/api`. Full PromQL engine (Tier 1+2+3 functions). Also supports Prometheus remote write/read for long-term storage. --- # Spatial Engine (docs/storage-engines/spatial) --- title: Spatial Engine description: Peer engine for geo-primary workloads — R*-tree index, OGC predicates, geohash, H3 hexagonal indexing, and hybrid spatial-vector search. --- # Spatial Engine Spatial is a peer engine sharing storage with `columnar` and `timeseries`. Collections selected via `WITH (engine='spatial')` and a `GEOMETRY SPATIAL_INDEX` column get automatic R*-tree indexing over the geometry column. ## DDL ```sql -- Spatial peer engine (R-tree + geohash + OGC predicates) CREATE COLLECTION restaurants ( location GEOMETRY SPATIAL_INDEX, name VARCHAR, cuisine VARCHAR, rating FLOAT ) WITH (engine='spatial'); -- Or add a spatial index to any collection CREATE COLLECTION restaurants; CREATE SPATIAL INDEX ON restaurants FIELDS location; ``` ## Queries ```sql -- Find within 1km SELECT name, ST_Distance(location, ST_Point(-73.990, 40.750)) AS dist FROM restaurants WHERE ST_DWithin(location, ST_Point(-73.990, 40.750), 1000) ORDER BY dist; -- Geofencing (point-in-polygon) SELECT name FROM restaurants WHERE ST_Within(location, ST_GeomFromGeoJSON('{ "type": "Polygon", "coordinates": [[[-74.0, 40.7], [-73.9, 40.7], [-73.9, 40.8], [-74.0, 40.8], [-74.0, 40.7]]] }')); -- H3 hexagonal binning SELECT h3_latlngtocell(40.748, -73.985, 9) AS hex; -- Spatial join SELECT r.name, z.zone_name FROM restaurants r, delivery_zones z WHERE ST_Contains(z.boundary, r.location); -- Hybrid spatial-vector: nearby AND semantically similar SELECT name, vector_distance(embedding, $query_vec) AS similarity FROM restaurants WHERE ST_DWithin(location, ST_Point(-73.990, 40.750), 2000) AND embedding <-> $query_vec LIMIT 10; ``` ## Geometry Functions - **Predicates** — `ST_Contains`, `ST_Within`, `ST_Intersects`, `ST_Disjoint`, `ST_DWithin`, `ST_IsValid` - **Constructors** — `ST_Point`, `ST_MakePoint`, `ST_GeomFromText`, `ST_GeomFromWKB`, `ST_GeomFromGeoJSON`, `ST_MakeLine`, `ST_MakePolygon`, `ST_MakeEnvelope` - **Accessors** — `ST_AsText`, `ST_AsGeoJSON`, `ST_X`, `ST_Y`, `ST_GeometryType`, `ST_NPoints`, `ST_SRID` - **Spatial reference systems** — `ST_SRID`, `ST_SetSRID`, `ST_Transform` - **Measures** — `ST_Distance`, `ST_Length`, `ST_Perimeter`, `ST_Area` (meters; geodesic for `4326`, planar for a projected SRID) - **Operations** — `ST_Buffer`, `ST_Envelope`, `ST_Centroid`, `ST_Union`, `ST_Intersection` Each works in every geometry position — `INSERT` values, projections, and predicate arguments — and constructors nest. See [Spatial Queries](/docs/sql/spatial-queries) for the full reference. ## SRID Every geometry carries an SRID, `4326` by default. Supported SRIDs are `4326`, `32647`, `32648`, `3375`, and `3376`. Operands in different SRIDs raise a data exception (SQLSTATE `22000`) instead of transforming implicitly. Use `ST_Transform` to convert. A spatial index fixes its SRID at its first entry and refuses geometries in another SRID. See [Spatial Reference Systems](/docs/sql/spatial-queries#spatial-reference-systems). ## Format Support WKB, WKT, and GeoJSON interchange. GeoParquet v1.1.0 and GeoArrow metadata for bulk export. ## Combined with Timeseries ```sql -- Fleet tracking: spatial + time CREATE COLLECTION fleet ( ts TIMESTAMP TIME_KEY, vehicle_id VARCHAR, position GEOMETRY SPATIAL_INDEX, speed FLOAT ) WITH (engine='timeseries', partition_by='1d'); ``` --- # Vector Engine (docs/storage-engines/vector) --- title: Vector Engine description: HNSW index with quantization, adaptive pre-filtering, and SIMD-accelerated distance math for semantic search. --- # Vector Engine The vector engine powers semantic search — nearest-neighbor retrieval over high-dimensional embeddings. It uses a custom HNSW index with multiple quantization levels and hardware-accelerated distance math. ## When to Use - Semantic search over embeddings (text, images, audio) - RAG pipelines for AI agents - Recommendation systems - Similarity matching and deduplication ## Key Features - **HNSW index** — Multi-layer proximity graph. Construction at full precision (FP32/FP16) for structural integrity; traversal on quantized payloads for cache residency. - **Quantization** — SQ8 (~4x memory reduction), PQ (~4-8x), IVF-PQ (~16 bytes/vector for 100M+ datasets). - **Adaptive pre-filtering** — Roaring Bitmap-based filtering. Automatic strategy selection: pre-filter (selective), post-filter (broad), or brute-force. - **Distance metrics** — L2, cosine, inner product, Manhattan, Chebyshev, Hamming, Jaccard, Pearson. - **Cross-engine fusion** — Combine with graph (GraphRAG), full-text (hybrid BM25+vector), or spatial filtering. ## SQL Usage ```sql -- Create a collection with a vector index CREATE COLLECTION articles; CREATE VECTOR INDEX idx_embed ON articles METRIC cosine DIM 384; -- Insert with embedding INSERT INTO articles { title: 'Understanding Transformers', embedding: [0.12, -0.34, 0.56, ...] }; -- Nearest neighbor search SEARCH articles USING VECTOR(embedding, ARRAY[0.1, 0.3, -0.2, ...], 10); -- Filtered vector search SELECT title, vector_distance(embedding, ARRAY[0.1, 0.3, ...]) AS score FROM articles WHERE category = 'machine-learning' AND id IN (SEARCH articles USING VECTOR(embedding, ARRAY[0.1, 0.3, ...], 10)); -- Hybrid BM25 + vector (RRF fusion) SELECT title, rrf_score( vector_distance(embedding, $query_vec), bm25_score(body, 'transformer attention') ) AS score FROM articles LIMIT 10; ``` ## Quantization & Storage Precision **Storage Precision** (`storage_dtype` — raw HNSW structural storage): | Type | Bytes/dim | Best for | | ------- | --------- | ---------------------------------- | | `F32` | 4 | Maximum accuracy, small indexes | | `F16` | 2 | Balanced memory vs accuracy | | `BF16` | 2 | Better dynamic range than F16 (preferred for embeddings) | **Quantization** (`quantization` — index-level compression, independent of storage_dtype): Codes are traversed for speed, then top candidates are re-ranked against full-precision vectors. Memory is the per-vector code size at 384 dimensions; smaller codes trade recall for footprint and scale. | `quantization` | Code size (384d) | Best for | | -------------- | ----------------------- | ----------------------------------------- | | `none` | 1536 B (`dim×4`) | < 1M vectors, maximum accuracy | | `sq8` | 384 B (`dim×1`) | 1–10M vectors, near-lossless | | `pq` | `m` B (default `m`=16) | 10M+ vectors, classic Product Quantization | | `opq` | `m` B (rotation + PQ) | PQ + learned rotation, minor accuracy bump | | `binary` | 48 B (`dim/8`) | Massive scale, sign-bit asymmetric search | | `rabitq` | 48 B + scalars | 1-bit frontier with bounded error | | `bbq` | 62 B (`dim/8` + 14 B) | Centroid-asymmetric 1-bit + corrective | | `ternary` | ~77 B (`dim/5`) | BitNet b1.58 trit-packed | ## How It Works Vectors are indexed in the HNSW graph at full precision. During search, quantized copies are traversed for speed, then top candidates are re-ranked against full-precision vectors. When metadata filters are present, the engine builds a Roaring Bitmap of matching IDs and selects the optimal strategy based on selectivity. --- # Array Engine (docs/storage-engines/array) --- title: Array Engine description: ND sparse array engine — coordinate-tuple indexed, tile-based, bitemporal. Replaces TileDB / Zarr / SciDB / Rasdaman. --- # Array Engine NodeDB's array engine stores multi-dimensional sparse data with bitemporal support — system time (when the cell was written) and valid time (when the cell represents). Cells are coordinate-tuple indexed, grouped into tiles, compressed per-tile, and queryable via SQL table-valued functions. This is a peer engine but uses its own DDL family (`CREATE ARRAY`) — not `CREATE COLLECTION ... WITH (engine='array')`. ## When to Use - Genomics: `(chromosome × position × sample × allele)` — replaces TileDB-VCF - Single-cell biology: `(gene × cell × condition × replicate)` — replaces TileDB-SOMA - Earth observation: `(lat × lon × band × time)` raster cubes — replaces Zarr / TileDB-Geo - Climate models: `(lat × lon × level × time × variable)` — replaces HDF5 + Dask - Astronomy: `(RA × Dec × wavelength × time)` — replaces custom Zarr stacks - Sparse ML features: `(user × item × context)` — replaces specialized matrix-factorization systems ## Key Features - **ND coordinate-tuple keying** — arbitrary number of dimensions; only materialized cells are stored - **Tile-based compression** — cells grouped into tiles; each tile independently compressed (ALP, FastLanes, Gorilla, LZ4 via `nodedb-codec`) - **Z-order indexing** — Hilbert/Z-order curve linearization for spatial locality and fast range queries - **Per-tile ND MBR statistics** — minimum bounding rectangle skip; queries prune entire tiles before decompressing - **Bitemporal** — both system time (audit trail) and valid time (temporal semantics) tracked per tile - **Row-major or column-major layout** — `cell_order` chosen at creation - **Cross-engine surrogate identity** — array cells participate in cross-engine bitmap intersections alongside vector / graph / document / columnar - **Distributed** — tiles vShard-routed; queries scatter-gather across cores and nodes - **WAL-durable + Raft-replicated** — same durability guarantees as the rest of NodeDB - **Tile-level retention** — `audit_retain_ms` enables GDPR / data-minimization compliance ## DDL Syntax ```sql CREATE ARRAY spatial_grid DIMS ( x INT64 [0..1000], y INT64 [0..1000], z INT64 [0..1000] ) ATTRS ( temperature FLOAT64 NOT NULL, pressure FLOAT64, humidity FLOAT64 ) TILE_EXTENTS (64, 64, 64) CELL_ORDER ZORDER TILE_ORDER ROW_MAJOR WITH ( prefix_bits = 8, audit_retain_ms = 86400000, minimum_audit_retain_ms = 3600000 ); ``` | Parameter | Required | Default | Description | | ----------------- | -------- | ----------- | -------------------------------------------------------------------------------------------------------- | | `DIMS` | Yes | — | Dimensions. Each has a name, type (`INT64`, `FLOAT64`, `TIMESTAMP_MS`, `STRING`), and optional domain `[lo..hi]`. | | `ATTRS` | Yes | — | Attributes (cell values). Each has a name, a type (see [Attribute types](#attribute-types)), and optional `NOT NULL`. | | `TILE_EXTENTS` | Yes | — | Tile extent per dimension; all > 0. Determines cell locality and compression block granularity. | | `CELL_ORDER` | No | `HILBERT` | Unquoted: `ROW_MAJOR`, `COL_MAJOR`, `HILBERT`, `ZORDER` (Z-order curve). Affects cell layout. | | `TILE_ORDER` | No | `HILBERT` | Unquoted: `ROW_MAJOR`, `COL_MAJOR`, `HILBERT`, `ZORDER`. Affects tile layout. | | `prefix_bits` | No | `8` | Range 1–16. Bits used in prefix codec for compression. Higher = finer granularity, lower = better compression. | | `audit_retain_ms` | No | `NULL` | Tiles older than `now - audit_retain_ms` (system time) become eligible for purge. `NULL` = keep all. | | `minimum_audit_retain_ms` | No | `NULL` | Minimum retention even if `audit_retain_ms` is lower. Used to enforce compliance minimums. | `ALTER ARRAY SET (audit_retain_ms = ...)` updates retention; `DROP ARRAY [IF EXISTS] ` is two-phase like `DROP COLLECTION`. ### Attribute types An attribute stores each cell at its declared width. A value outside the width is refused with SQLSTATE `22003` on `INSERT`, `COPY`, and the native bulk load. It is never wrapped or clamped. | Type | Aliases | Range | Column type (OID) | | --------- | ------------------------ | ------------------------- | ------------------------ | | `UINT8` | | 0 to 255 | `smallint` (21) | | `INT16` | `SMALLINT`, `INT2` | -32768 to 32767 | `smallint` (21) | | `UINT16` | | 0 to 65535 | `integer` (23) | | `INT32` | `INTEGER`, `INT`, `INT4` | -2147483648 to 2147483647 | `integer` (23) | | `UINT32` | | 0 to 4294967295 | `bigint` (20) | | `INT64` | `BIGINT` | 64-bit signed | `bigint` (20) | | `FLOAT32` | `REAL`, `FLOAT4` | 32-bit IEEE float | `real` (700) | | `FLOAT64` | `DOUBLE`, `FLOAT` | 64-bit IEEE float | `double precision` (701) | | `STRING` | `TEXT`, `VARCHAR` | UTF-8 text | `text` (25) | | `BYTES` | `BLOB`, `BYTEA` | raw bytes | `bytea` (17) | - An unsigned type reads as the next wider signed column type, so every stored value fits. - `INT` is the 4-byte `INT32`, as in PostgreSQL. A bare `FLOAT` is the 8-byte `FLOAT64`. - A float written to a `FLOAT32` attribute rounds to the nearest `f32`. Only a finite value past the `f32` range is refused. `0.1` stored as `FLOAT32` reads back as `0.1`. - An integer literal is accepted by every integer and float type. A float literal is accepted by `FLOAT32` and `FLOAT64` only. - An integer column compresses by its value range, so a `UINT16` column takes the same bytes on disk as an `INT64` column of the same values. A `FLOAT32` column stores at most 4 bytes per value, half the raw width of `FLOAT64`. - A `NULL` stays `NULL` through a flush and a compaction, in every type. ## Insert ```sql CREATE ARRAY elevation_map DIMS ( lon FLOAT64 [-180..180], lat FLOAT64 [-90..90] ) ATTRS (height FLOAT64) TILE_EXTENTS (256, 256); -- COORDS lists the dimensions in schema order. VALUES lists the attributes in schema order. -- Values are literals: numbers, strings, or NULL for an attribute. INSERT INTO ARRAY elevation_map COORDS (-73.5, 40.7) VALUES (10.5), COORDS (-73.6, 40.8) VALUES (12.3), COORDS (-73.7, 40.6) VALUES (8.9); -- Remove cells by coordinate DELETE FROM ARRAY elevation_map WHERE COORDS IN ((-73.7, 40.6)); -- Force the in-memory tiles to durable storage SELECT ARRAY_FLUSH('elevation_map'); ``` ## Bulk Load `COPY FROM STDIN` loads cells in bulk. Columns are the dimensions in schema order, then the attributes in schema order. ```sql COPY scene FROM STDIN WITH (FORMAT csv); COPY scene FROM STDIN WITH (FORMAT csv, DELIMITER ';', HEADER); COPY scene FROM STDIN; -- text format, tab-delimited ``` - `FORMAT` is `csv` or `text`. The default is `text`, tab-delimited. `HEADER` is off unless given. A bare `HEADER` turns it on. The file form `COPY FROM ''` takes CSV only, and its `HEADER` defaults to `true`. - Each value parses by its column's declared type. No type is guessed. - With `HEADER`, the first line must name the dimensions, then the attributes, in schema order. A mismatch is `42703`. - A wrong column count or an unparsable value is `22P02`. A NULL in a `NOT NULL` attribute is `23502`. A coordinate outside its dimension domain is `22003`. A value outside its attribute's width, such as `256` in a `UINT8` attribute, is `22003`. - The load streams. Rows are checked as they arrive and load in chunks of about 4 MiB. Each chunk is written before the next rows are read, so the server holds a few chunks whatever the input size. A repeated coordinate keeps its last value. - Outside a transaction block, each chunk commits on its own, as each row of a collection `COPY` does. A bad row or a refused chunk, such as `53200` under memory pressure, stops the load. The chunks before it stay committed. The error names the row and the committed row count: `COPY: CSV row 150000: ... (139810 rows committed)`. Those rows are in the array. - Inside `BEGIN`, every chunk stages, and an error aborts the block, so the load commits or rolls back whole. A chunk that takes the staged redo past the 64 MiB WAL record cap is refused with `54000` before it stages. Load more than that outside a block. - A record must end within the array engine's memory headroom. A record with no line break past it is `54000`. - The native protocol loads the same way through the `ArrayPutBatch` opcode (`NodeDb::array_put_cells` in `nodedb-client`). The same rules apply to each request. ## Query Functions Array queries are expressed as table-valued functions in `FROM`. System time and valid time apply via `AS OF` clauses. ### `ARRAY_SLICE` — multi-dimensional range ```sql SELECT * FROM ARRAY_SLICE( 'elevation_map', '{lon: [-74.0, -73.0], lat: [40.0, 41.0]}', ['height'], -- attribute projection (optional) 1000 -- max cells (optional) ); ``` | Parameter | Required | Type | Description | | --------- | -------- | -------------- | --------------------------------------------------------------- | | `array` | Yes | `STRING` | Array name, as a string literal | | `bounds` | Yes | `STRING` | Quoted object literal `'{ dim: [lo, hi] }'`. Each range is closed: both ends are included. Omitted dims = full range. | | `attrs` | No | `ARRAY[STRING]`| Attributes to project, such as `['height']`. `'*'` = all attributes. Omit it to read all attributes. | | `limit` | No | `INT` | Max cells returned, as a non-negative integer literal. Omit it for no limit. | #### Result Relation `ARRAY_SLICE` and `ARRAY_PROJECT` return one row per cell. The row has one column per dimension, then one column per requested attribute, or every attribute when the list is empty. Each column carries its declared type: | Declared type | Column type | | ------------- | ------------------------ | | `UINT8`, `INT16` (attribute only) | `smallint` | | `UINT16`, `INT32` (attribute only) | `integer` | | `UINT32` (attribute only) | `bigint` | | `INT64` | `bigint` | | `FLOAT32` (attribute only) | `real` | | `FLOAT64` | `double precision` | | `TIMESTAMP_MS` (dimension) | `timestamp` | | `STRING` | `text` | | `BYTES` | `bytea` (attribute only) | `SELECT *` lists the dimensions first, then the attributes, in schema order. For a 2-D image with `nir` and `red` bands: ```sql SELECT * FROM ARRAY_SLICE('img', '{x: [0, 3], y: [0, 3]}'); -- x | y | nir | red -- ---+---+------+------ -- 0 | 0 | 0.80 | 0.20 -- 0 | 1 | 0.60 | 0.30 ``` Every `SELECT` clause applies to the rows: `WHERE`, computed columns, `GROUP BY`, aggregates, `HAVING`, `ORDER BY`, `DISTINCT`, `LIMIT` / `OFFSET`, and window functions. Qualify a column with the call's alias, or with the array name when the call has no alias. ```sql -- NDVI per cell, vegetated cells only, greenest first SELECT x, y, (nir - red) / (nir + red) AS ndvi FROM ARRAY_SLICE('img', '{x: [0, 3], y: [0, 3]}') AS t WHERE t.nir > t.red ORDER BY ndvi DESC LIMIT 10; -- Mean NIR per column of pixels SELECT x, AVG(nir) AS mean_nir FROM ARRAY_SLICE('img', '{x: [0, 3], y: [0, 3]}') GROUP BY x; ``` The 4th-argument `limit` caps the cells the slice reads before any clause applies. An outer `LIMIT` applies to the query's result. A smaller outer `LIMIT` also lowers the read cap when no other clause reads past the cut. A `WHERE` bound on a dimension narrows the read range only when the slice has no cap. A capped slice keeps the cells its cap selects. `AS OF SYSTEM TIME NULL` adds a `_ts_system` column: the version's system time in milliseconds. `SELECT *` omits it. Name it to read it. ### `ARRAY_PROJECT` — attribute projection ```sql SELECT * FROM ARRAY_PROJECT('spatial_grid', ['temperature', 'pressure']); ``` `ARRAY_PROJECT` returns the same typed relation as `ARRAY_SLICE`, so every `SELECT` clause applies to its rows. The attribute list is required and must not be empty. ### `ARRAY_AGG` — reduce an attribute Reduces one attribute with a reducer. The optional 4th argument names a dimension to group by: ```sql -- One result for the whole array SELECT * FROM ARRAY_AGG('spatial_grid', 'temperature', 'SUM'); -- One result per value of x SELECT * FROM ARRAY_AGG('spatial_grid', 'temperature', 'SUM', 'x'); ``` The result has a `result` column. A grouped call also has a `group` column that holds the dimension value. The `group` column takes the group dimension's declared type: `TIMESTAMP_MS` gives `timestamp`, `FLOAT64` gives `float8`, `INT64` gives `int8`, and `STRING` gives `text`. A temporal call (`AS OF`) appends one summary row with the `bool` column `truncated_before_horizon`. Reducers are case-insensitive: `'SUM'`, `'COUNT'`, `'MIN'`, `'MAX'`, and `'MEAN'` (or `'AVG'`). The `result` type follows the reducer and the attribute type: | Reducer | Integer attribute | Float attribute | | ------------- | -------------------------------------- | ------------------------------- | | `COUNT` | `bigint` | `bigint` | | `SUM` | `bigint`, exact | `double precision` | | `MIN` / `MAX` | the attribute's own column type, exact | the attribute's own column type | | `MEAN` | `double precision` | `double precision` | `SUM`, `MEAN`, `MIN`, and `MAX` accept integer and float attributes only. `COUNT` accepts every attribute type. Another reducer over a `STRING` or `BYTES` attribute is refused at plan time with a type mismatch error. An integer `SUM` adds exactly, so `2^53 + 1` stays `9007199254740993`. A `SUM` past the `bigint` range is refused with SQLSTATE `22003`. `MIN` and `MAX` sort `NaN` above every other float, as PostgreSQL does. ### `ARRAY_ELEMENTWISE` — between two arrays of the same shape ```sql SELECT * FROM ARRAY_ELEMENTWISE('current_grid', 'baseline_grid', 'sub', 'temperature'); ``` Operations are `'add'`, `'sub'`, `'mul'`, and `'div'`, case-insensitive. The arrays must share a schema shape. The result has `coords` and `attrs` columns, both JSON. On integer attributes, `add`, `sub`, and `mul` are exact 64-bit integers, and a result past the `bigint` range is refused with SQLSTATE `22003`. `div`, and every operation on a float attribute, yields a 64-bit float. Division by zero yields `NULL`. `ARRAY_AGG` and `ARRAY_ELEMENTWISE` return rows of their own shape, not dimensions and attributes. `ARRAY_AGG` rows hold `result`, after `group` when the call groups by a dimension. `ARRAY_ELEMENTWISE` rows hold `coords` and `attrs`. Every `SELECT` clause applies to those rows, as it does to `ARRAY_SLICE` rows: `WHERE`, computed columns, `GROUP BY`, `ORDER BY`, `DISTINCT`, and `LIMIT`. A temporal call ends with one summary row that sets `truncated_before_horizon`. ```sql SELECT "group" AS day, ROUND(result, 4) AS mean_nir FROM ARRAY_AGG('scene', 'nir', 'mean', 't') WHERE result > 0.2 ORDER BY day; ``` ## Maintenance ```sql SELECT ARRAY_FLUSH('spatial_grid'); -- force memtable flush SELECT ARRAY_COMPACT('spatial_grid'); -- merge tile versions, reclaim space ``` `ARRAY_FLUSH` returns one object `{"flushed": 1}` on success. `ARRAY_COMPACT` returns one object `{"compacted": n}`, where `n` is `1` when a merge ran and `0` when there was nothing to merge. A failure raises an error. Compaction also runs automatically in the background. ## Bitemporal Queries Every array cell carries two times: - **System time** — when the value was written (audit trail, compliance, point-in-time recovery) - **Valid time** — when the value represents (forecasts, backdated corrections, scientific replays) ```sql -- Read cells as the array existed in the past SELECT * FROM ARRAY_SLICE('data', '{x: [0, 99], y: [0, 99]}', ['value']) AS OF SYSTEM TIME 1700000000000; -- Read cells whose valid-time interval includes a given moment SELECT * FROM ARRAY_SLICE('forecast', '{x: [0, 99], y: [0, 99]}', ['temp']) AS OF VALID TIME 1700000000000; -- Both clauses combined SELECT * FROM ARRAY_SLICE('forecast', '{x: [0, 99], y: [0, 99]}', ['temp']) AS OF SYSTEM TIME 1700000000000 AS OF VALID TIME 1700000001000; ``` A time is an integer in milliseconds since the Unix epoch, `NOW()`, or an ISO-8601 string such as `'2024-01-15T00:00:00Z'`. System-time–based retention is the path to GDPR and data-minimization compliance: `audit_retain_ms` makes tiles older than the window eligible for irreversible purge during compaction. ## Cross-Engine Queries Array cells carry surrogate identity like the rows of the other engines. An `ARRAY_SLICE` or `ARRAY_PROJECT` call can be a `JOIN` source. A slice row holds one field per dimension and attribute, keyed by name, so a join key reads them directly. A slice row has no `id` column. ```sql -- Join slice cells to a collection on a dimension value SELECT c.x, c.y, c.attr1, s.name FROM ARRAY_SLICE('spatial_data', '{x: [0, 999], y: [0, 999]}', ['attr1']) AS c JOIN sites s ON c.x = s.grid_x; ``` See [Architecture Overview](../architecture/overview) for the cross-engine identity model. ## Performance - **Tile-level parallelism** — each tile is read and processed on its own core - **Compression** — typical 5–20× depending on data homogeneity - **Range queries** — Z-order layout gives cache-friendly access; ND-MBR per-tile stats prune irrelevant tiles before decompression - **Sparse-friendly** — only materialized cells are stored; implicit zeros and empty regions cost nothing --- # Graph Engine (docs/storage-engines/graph) --- title: Graph Engine description: CSR adjacency index with 13 algorithms, Cypher-subset MATCH, and GraphRAG fusion. --- # Graph Engine The graph engine uses a native CSR (Compressed Sparse Row) adjacency index — not recursive JOINs. At 1 billion edges, CSR uses ~10 GB vs ~60 GB for naive adjacency lists. Sub-millisecond multi-hop traversals, 13 native algorithms, Cypher-subset pattern matching, and GraphRAG fusion. ## When to Use - Knowledge graphs and entity relationships - Social networks and recommendation - Fraud detection (pattern matching) - Supply chain and dependency analysis - RAG pipelines with graph context (GraphRAG) ## Graph is an Overlay Graph edges are an overlay on document collections. Any collection can have graph edges — you don't create a separate "graph collection." ```sql CREATE COLLECTION people; INSERT INTO people (id, name) VALUES ('alice', 'Alice'); INSERT INTO people (id, name) VALUES ('bob', 'Bob'); GRAPH INSERT EDGE IN 'people' FROM 'alice' TO 'bob' TYPE 'knows' PROPERTIES { since: 2020, weight: 0.9 }; -- The IN '' clause is required — edges live on a named collection. ``` ## Traversal ```sql -- BFS traversal GRAPH TRAVERSE IN 'people' FROM 'alice' DEPTH 3; GRAPH TRAVERSE IN 'people' FROM 'alice' DEPTH 2 LABEL 'follows' DIRECTION out; -- Follow any of several labels GRAPH TRAVERSE IN 'people' FROM 'alice' DEPTH 2 LABEL 'follows', 'knows' DIRECTION out; -- Immediate neighbors GRAPH NEIGHBORS IN 'people' OF 'bob' LABEL 'follows' DIRECTION both; -- Shortest path GRAPH PATH IN 'people' FROM 'alice' TO 'charlie' MAX_DEPTH 5 LABEL 'knows'; ``` Every walk requires `IN ''` and reads only that collection's edges. `LABEL` takes one or more quoted labels: an edge passes when its label is any listed label. An omitted `LABEL` follows every edge. See [Graph Queries](/docs/sql/graph-queries) for the full syntax. ## MATCH Pattern Queries Cypher-subset pattern matching: ```sql -- Friend-of-friend MATCH (a:Person)-[:knows]->(b:Person)-[:knows]->(c:Person) WHERE a.name = 'Alice' RETURN b.name, c.name; -- Variable-length paths MATCH (u:User)-[:follows*2..3]->(recommended:User) WHERE u.id = 'you' RETURN DISTINCT recommended.id LIMIT 10; -- Anti-join MATCH (a:User)-[:follows]->(b:User) WHERE NOT EXISTS { MATCH (b)-[:blocked_by]->(a) } RETURN a.id, b.id; -- OPTIONAL MATCH MATCH (a:Person)-[:knows]->(b:Person) OPTIONAL MATCH (b)-[:works_at]->(c:Company) RETURN a.name, b.name, c.name; ``` ## 13 Algorithms ```sql GRAPH ALGO PAGERANK ON 'social' DAMPING 0.85 ITERATIONS 20 TOLERANCE 1e-7; GRAPH ALGO PAGERANK ON 'social' PERSONALIZATION {"alice": 1.0, "bob": 0.5}; GRAPH ALGO WCC ON 'knowledge_graph'; GRAPH ALGO SSSP ON 'routes' FROM 'city:chicago'; GRAPH ALGO COMMUNITY ON 'products' ITERATIONS 10 RESOLUTION 1.0; GRAPH ALGO BETWEENNESS ON 'network' SAMPLE 500; GRAPH ALGO KCORE ON 'collaboration'; GRAPH ALGO TRIANGLES ON 'social' MODE global; GRAPH ALGO DIAMETER ON 'web'; ``` **Personalized PageRank** biases node importance toward seed nodes via the `PERSONALIZATION` clause — a JSON object mapping node IDs to seed weights. | Algorithm | Computes | | ----------------- | -------------------------------------------- | | PageRank | Node importance via link structure | | WCC | Weakly connected components | | Label Propagation | Community detection via label spreading | | LCC | Local clustering coefficient | | SSSP | Single-source shortest path (Dijkstra) | | Betweenness | Bridge node identification | | Closeness | How close a node is to all others | | Harmonic | Closeness for disconnected graphs | | Degree | Connection count (in/out/both) | | Louvain | Community detection via modularity | | Triangles | Triangle count (per-node or global) | | Diameter | Longest shortest path | | k-Core | Coreness decomposition | ## GraphRAG Combines vector similarity with graph traversal in one query: ```sql GRAPH RAG FUSION ON entities QUERY $embedding VECTOR_FIELD 'embedding' VECTOR_TOP_K 50 EXPANSION_DEPTH 2 EDGE_LABEL 'related_to' FINAL_TOP_K 10 RRF_K (60.0, 35.0); ``` 1. Vector search finds semantically similar seed nodes 2. BFS expands seeds along edges 3. RRF merges vector rank with graph hop distance ## Graph Statistics The collection name is an optional single-quoted literal: ```sql SHOW GRAPH STATS; -- tenant-wide aggregate SHOW GRAPH STATS 'collection_name'; SHOW GRAPH STATS 'collection_name' VERBOSE; SHOW GRAPH STATS 'collection_name' AS OF SYSTEM TIME ; ``` Returns live edge counters and optional cardinality details: - Omitting the collection name returns tenant-wide aggregate edge counts - `VERBOSE` adds a per-edge-type (label) breakdown — one row per `(collection, label, edge_count)` - `AS OF SYSTEM TIME ` retrieves historical counts (O(1) lookup from WAL snapshots) --- # Full-Text Search Engine (docs/storage-engines/fts) --- title: Full-Text Search Engine description: Block-Max WAND BM25 with 27-language support, CJK tokenization, fuzzy matching, and hybrid vector fusion. --- # Full-Text Search Engine Block-Max WAND (BMW) optimized BM25 ranking with 16 Snowball stemmers, 27-language stop words, CJK bigram tokenization, posting compression, fuzzy matching, and native hybrid fusion with vector search. ## When to Use - Text search across documents, articles, products, logs - Search-as-you-type with fuzzy matching - Multilingual content search (including CJK, Arabic, Hindi) - Hybrid retrieval: keyword matching + semantic similarity ## SQL Usage ```sql CREATE COLLECTION articles; CREATE SEARCH INDEX ON articles FIELDS title, body ANALYZER 'english' FUZZY true; -- Basic search SELECT title, bm25_score(body, 'distributed database') AS score FROM articles WHERE text_match(body, 'distributed database') ORDER BY score DESC LIMIT 20; -- Fuzzy search SELECT title FROM articles WHERE text_match(title, 'databse', { fuzzy: true, distance: 2 }); -- Hybrid BM25 + vector (RRF) SELECT title, rrf_score( vector_distance(embedding, $query_vec), bm25_score(body, 'distributed systems') ) AS score FROM articles LIMIT 10; -- Synonyms CREATE SYNONYM GROUP db_terms AS ('database', 'db', 'datastore'); ``` ## Analyzers | Analyzer | Behavior | | ------------ | ----------------------------------------------- | | `standard` | NFD normalize, lowercase, English stop/stem | | `simple` | Lowercase + whitespace split | | `keyword` | Entire input as a single token | | `cjk_bigram` | CJK bigram tokenization | | `ngram:2:4` | Character n-grams (min:max) | | `edge_ngram` | Prefix-anchored n-grams for autocomplete | 16 language-specific analyzers: `ar`, `da`, `nl`, `en`, `fi`, `fr`, `de`, `hu`, `it`, `no`, `pt`, `ro`, `ru`, `es`, `sv`, `tr`. CJK text is automatically routed to bigram tokenizer regardless of configured analyzer. Optional dictionary segmentation via feature gates: `lang-ja`, `lang-zh`, `lang-ko`, `lang-th`. ## Internals - **BMW scoring** — WAND pivot selection + 128-doc block pruning via precomputed upper bounds - **Posting compression** — Delta-encoded, variable-width bitpacked doc IDs with SIMD unpack (SSE2/NEON) - **SmallFloat fieldnorms** — 1-byte length quantization (4x space reduction) - **LSM storage** — In-memory memtable → immutable segments → level-based compaction (8x8 tiering) - **AND-first with OR fallback** — Tries AND; falls back to OR with coverage penalty if zero results - **Phrase proximity boost** — Consecutive tokens at consecutive positions get up to 3x score boost --- # CRDT Engine (docs/storage-engines/crdt) --- title: CRDT Engine description: Loro-backed conflict-free replicated data types for offline-first edge sync with cloud consistency. --- # CRDT Engine The CRDT engine provides conflict-free replication for offline-first applications. Locally, writes are available immediately (AP). Globally, deltas are committed through Multi-Raft consensus (CP). SQL constraints are enforced at sync time. ## How It Works 1. Device writes locally — available immediately, no network required 2. Write produces a CRDT delta (Loro) 3. When connectivity returns, delta syncs to Origin via WebSocket 4. Origin validates SQL constraints (UNIQUE, FK, CHECK) at Raft commit 5. If constraints pass, delta is committed and replicated 6. If constraints fail, Origin sends a typed `CompensationHint` back to the device ## Conflict Resolution Declarative conflict policies per collection: ```sql -- Last-writer-wins (default) CREATE COLLECTION notes WITH (conflict_policy = 'lww'); -- Rename suffix for UNIQUE conflicts CREATE COLLECTION profiles WITH (conflict_policy = 'rename_suffix'); ``` The `PolicyRegistry` stores per-collection resolution strategies. Available policies: `lww` (last-writer-wins), `rename_suffix` (append suffix on UNIQUE conflict), `cascade_defer` (retry with backoff for FK violations), `custom` (webhook), `escalate_to_dlq` (send to dead-letter queue). ## Constraint Validation SQL constraints are checked on Origin at sync time, not on the device: - **UNIQUE** — duplicate key → `CompensationHint::Rename` or `CompensationHint::Merge` - **FK** — dangling reference → `CompensationHint::CreateParent` or `CompensationHint::Discard` - **CHECK** — constraint violation → `CompensationHint::Adjust` The application handles compensation — no silent data loss. ## Dead-Letter Queue Deltas that persistently fail constraint validation are routed to a dead-letter queue with diagnostic metadata. Operators can inspect, replay, or discard them. ## Related - [CRDT Sync](/docs/crdt-sync/overview) — Full sync protocol and offline patterns - [Document Engine](/docs/storage-engines/document) — Schemaless documents with CRDT sync --- # HNSW Index (docs/indexes/hnsw-index) --- title: HNSW Index description: Hierarchical Navigable Small World graph for approximate nearest neighbor search on vector embeddings. --- # HNSW Index HNSW (Hierarchical Navigable Small World) is a multi-layer proximity graph for approximate nearest neighbor search. It provides logarithmic search complexity with high recall. ## Creating an HNSW Index ```sql CREATE VECTOR INDEX idx_embed ON articles METRIC cosine DIM 384; -- With explicit parameters CREATE VECTOR INDEX idx_embed ON articles METRIC cosine DIM 384 M 16 EF_CONSTRUCTION 200; ``` ## Parameters | Parameter | Default | Description | | ------------------ | ------- | ------------------------------------------------------------- | | `METRIC` | — | Distance metric: `l2`, `cosine`, `inner_product`, `manhattan`, `chebyshev`, `hamming`, `jaccard`, `pearson` | | `DIM` | — | Vector dimension (must match your embeddings) | | `M` | 16 | Max connections per node per layer. Higher = more accurate, more memory | | `EF_CONSTRUCTION` | 200 | Search width during index build. Higher = slower build, better graph quality | ## How It Works - **Construction** — Vectors inserted at full precision (FP32/FP16) to maintain structural integrity - **Search** — Traverses quantized copies for speed, then re-ranks top candidates against full-precision vectors - **Layers** — Upper layers provide coarse navigation; bottom layer is fully connected ## Quantization Add quantization to reduce memory: | Quantization | Memory reduction | Recall impact | | ------------ | ---------------- | ------------- | | SQ8 | ~4x | Minimal | | PQ | ~4-8x | ~5% loss | | IVF-PQ | ~16 bytes/vector | ~5-15% loss | ## Search ```sql -- k-NN search SEARCH articles USING VECTOR(embedding, ARRAY[0.1, 0.3, ...], 10); -- With pre-filtering SELECT * FROM articles WHERE category = 'ml' AND id IN (SEARCH articles USING VECTOR(embedding, $vec, 10)); ``` --- # CSR Index (docs/indexes/csr-index) --- title: CSR Index description: Compressed Sparse Row adjacency index for cache-resident graph traversal. --- # CSR Index CSR (Compressed Sparse Row) is the graph engine's core index format. It stores adjacency data in contiguous arrays for cache-resident traversal. ## Layout ``` CsrIndex (per tenant): out_offsets: Vec [num_nodes + 1] — offset into target array per node out_targets: DenseArray [num_edges] — destination node IDs (contiguous, mmap-capable) out_labels: DenseArray [num_edges] — edge labels (parallel array) out_weights: Option> — optional, allocated only when weighted in_offsets / in_targets / in_labels / in_weights — symmetric for inbound ``` ## Tenant Partitioning The in-memory index is `ShardedCsrIndex` — one `CsrIndex` per tenant. Algorithms and traversals receive a single tenant's partition; there is no lexical tenant prefix on node names. Each `CsrIndex` is assigned a unique partition tag at construction, and public APIs that return dense node indices hand out `LocalNodeId { id, partition_tag }`. Using a node id from one partition with another partition's API panics at the boundary. ## Memory Efficiency At 1 billion edges, CSR uses ~10 GB vs ~60 GB for naive adjacency lists (6x improvement). Node IDs are interned as `u32`, labels as `u32`. ## Storage Edges are persisted in a redb B-Tree with forward and reverse indexes, both keyed by `(tenant_id: u32, "src\x00label\x00dst")` tuples. Tenant isolation is structural (first-class key component), not lexical. The CSR index is built at query time for bulk operations. Writes go to a mutable buffer and become visible immediately. Compaction merges the buffer into dense CSR arrays when the buffer exceeds 10% of the dense size. ## Graph Operations The CSR index supports all traversal and algorithm operations: - BFS/DFS traversal - Shortest path (Dijkstra) - All 13 native graph algorithms - MATCH pattern matching - GraphRAG fusion --- # R*-tree Index (docs/indexes/rtree-index) --- title: R*-tree Index description: Spatial index for range queries, nearest neighbor, and OGC predicate evaluation. --- # R*-tree Index The R*-tree is the spatial engine's primary index. It supports range queries, nearest neighbor search, and spatial predicate evaluation. ## Creating a Spatial Index ```sql -- Automatic via SPATIAL_INDEX column modifier (spatial peer engine) CREATE COLLECTION locations ( geom GEOMETRY SPATIAL_INDEX, name VARCHAR ) WITH (engine='spatial'); -- Or add to any collection CREATE SPATIAL INDEX ON restaurants FIELDS location; ``` ## Operations - **Range query** — `ST_DWithin`, `ST_Within`, `ST_Intersects` - **Nearest neighbor** — `ORDER BY ST_Distance(geom, point) LIMIT k` - **Bulk load** — Optimized for batch inserts - **Spatial join** — R*-tree probe join between two collections ## Query Execution When a spatial predicate is present, the R*-tree narrows the candidate set before the columnar sparse index does final refinement. Queries without spatial predicates read directly from the columnar memtable — the R*-tree is not involved. ```sql -- R*-tree lookup → sparse refinement → result SELECT name FROM locations WHERE ST_DWithin(geom, ST_Point(-73.98, 40.75), 500); -- No spatial predicate → direct columnar scan SELECT name FROM locations WHERE name LIKE 'Park%'; ``` --- # B-tree Index (docs/indexes/btree-index) --- title: B-tree Index description: redb B-Tree indexes for metadata lookups and secondary indexes on document collections. --- # B-tree Index B-tree indexes power metadata lookups and secondary indexes on document collections. Backed by redb's ACID B-Tree storage. ## Creating Indexes ```sql -- Secondary index on a document collection CREATE INDEX ON users FIELDS email; -- Compound index CREATE INDEX ON orders FIELDS customer_id, status; -- Unique index CREATE UNIQUE INDEX ON users FIELDS email; ``` ## When Used - Point lookups on document collections (`WHERE email = 'alice@example.com'`) - Range scans (`WHERE age > 25 AND age < 40`) - Sorting (`ORDER BY created_at DESC`) - Constraint enforcement (UNIQUE) ## Graph Edge Storage Graph edges are persisted in redb B-Trees with forward and reverse indexes, keyed by `(tenant_id: u32, "src\x00label\x00dst")` tuples. Tenant isolation is a first-class key component, not a lexical prefix; the composite portion enables prefix scans for outbound traversal within a tenant. --- # Inverted Index (docs/indexes/inverted-index) --- title: Inverted Index description: LSM-based inverted index for full-text search with Block-Max WAND scoring. --- # Inverted Index The inverted index maps terms to document IDs for full-text search. It uses an LSM architecture with posting compression and Block-Max WAND scoring. ## Creating a Search Index ```sql CREATE SEARCH INDEX ON articles FIELDS title, body ANALYZER 'english' FUZZY true; ``` ## Architecture **Memtable** — Writes accumulate in-memory (`HashMap>`). When the memtable exceeds the threshold (32M posting entries or 100K unique terms), it flushes to an immutable segment. **Segments** — Compressed on-disk segments with delta-encoded, bitpacked posting lists. Level-based compaction (8 levels, 8 segments per level). **Query merge** — Searches merge the active memtable with all persisted segments. ## Posting Compression - Delta encoding for sorted doc IDs - Variable-width bitpacking (3-byte header: `[count: u16][bit_width: u8]`) - SIMD-accelerated unpack (SSE2 on x86_64, NEON on AArch64) - SmallFloat fieldnorms (1 byte per document, 4x space reduction) ## Block-Max WAND Posting lists are split into 128-document blocks with precomputed `block_max_tf` and `block_min_fieldnorm`. During scoring, blocks that can't beat the current top-k threshold are skipped entirely. --- # Hash Index (docs/indexes/hash-index) --- title: Hash Index description: O(1) hash-based index for key-value point lookups. --- # Hash Index The hash index provides O(1) point lookups by user-defined key. It is the primary index for KV collections. ## How It Works Keys are hashed to locate the value directly — no tree traversal. This provides constant-time reads regardless of collection size. ## Creating a KV Collection ```sql CREATE COLLECTION sessions (key TEXT PRIMARY KEY) WITH (engine='kv'); ``` The `PRIMARY KEY` column is automatically hash-indexed. ## Secondary Indexes KV collections can also have secondary B-tree indexes on value fields: ```sql CREATE INDEX ON sessions FIELDS role; SELECT key, user_id FROM sessions WHERE role = 'admin'; ``` ## TTL Native TTL with an index-backed expiry wheel. Keys expire automatically: ```sql INSERT INTO sessions { key: 'sess_abc', user_id: 'alice', ttl: 3600 }; ``` --- # Bitemporal Queries (docs/temporal/bitemporal) --- title: Bitemporal Queries description: Track data along system time (when written) and valid time (when valid). Audit trails, backdated corrections, and compliance-grade history across multiple engines. --- # Bitemporal Queries Bitemporal databases track data along two independent time dimensions: - **System time** — when the database recorded the value. Stored *in the key* (structural), derived from the WAL LSN at Raft commit. Used for audit trails and asking "what did the database think was true at moment X?". - **Valid time** — when the value represents. Stored *in the value*, client/device-assigned. Used for forecasts, backdated corrections, and asking "what was true in the world at moment X?". Closed-open intervals: `[from, to)`; an open upper bound is `i64::MAX`. ## Supported Engines | Engine | System Time | Valid Time | Example use case | | ------------------------------------------------------------ | :---------: | :--------: | --------------------------------- | | [Graph](../storage-engines/graph) (edges + nodes) | Yes | Yes | Entity-relationship timelines | | [Document (strict)](../storage-engines/document) | Yes | Yes | Versioned profiles, ledgers | | [Document (schemaless)](../storage-engines/document) | Yes | Yes | Event logs with backdated entries | | [Columnar](../storage-engines/columnar) | Yes | Yes | Audit tables, corrected metrics | | [Timeseries](../storage-engines/timeseries) | Yes | Yes | Forecast corrections, data repair | | [Array](../storage-engines/array) (tile-level versioning) | Yes | Yes | Historical spatial snapshots | **Index engines (Vector, Full-Text Search, Spatial R\*-tree, Key-Value)** do not carry temporal columns themselves — they index records that live in data-bearing collections. To query at a point in time, attach the index to a `bitemporal=true` collection; `AS OF` filtering happens at the collection layer, not the index. See [Index engines and temporal composition](#index-engines-and-temporal-composition). ## SQL Syntax `AS OF` clauses sit in the `FROM` part of a query. Times must be one of: 1. Integer milliseconds since Unix epoch (e.g., `1700000000000`) 2. `NOW()` — current time 3. ISO-8601 string literal (e.g., `'2024-01-15T00:00:00Z'`) ```sql -- Read the database state as of a past system time SELECT * FROM collection AS OF SYSTEM TIME 1700000000000; -- Read rows whose valid-time interval includes a given moment SELECT * FROM collection AS OF VALID TIME 1700000000000; -- Both: rows that were valid AND in the system at a point SELECT * FROM collection AS OF SYSTEM TIME 1700000000000 AS OF VALID TIME 1700000001000; ``` ## Writes A write never rewrites history. Each write closes the row's current version and, for an insert or update, adds a new one at the statement's system time. - `UPDATE … WHERE` and `DELETE … WHERE` match the current version of each row, in autocommit and inside `BEGIN … COMMIT` alike. - `DELETE` closes the matched rows' current versions. `AS OF SYSTEM TIME` before the delete still returns them. - `TRUNCATE` closes every current version, the same as `DELETE` with no `WHERE`. The history stays readable with `AS OF`. - Only the retention purge (`audit_retain_ms`) removes old versions. An indexed equality under `AS OF` reads the versioned secondary index at the query's time, so it returns the rows as they stood then. ## Examples ### Audit Trail (System Time) ```sql CREATE COLLECTION user_accounts ( id UUID DEFAULT gen_uuid_v7(), email VARCHAR, balance DECIMAL, created_at TIMESTAMP DEFAULT now() ) WITH (engine='document_strict', bitemporal=true); INSERT INTO user_accounts (email, balance) VALUES ('alice@example.com', 100.00); UPDATE user_accounts SET balance = 150.00 WHERE email = 'alice@example.com'; -- Database state 10 minutes ago SELECT email, balance FROM user_accounts AS OF SYSTEM TIME '2026-06-07T11:50:00Z'; -- → alice@example.com, 100.00 -- Current state SELECT email, balance FROM user_accounts; -- → alice@example.com, 150.00 ``` ### Backdated Corrections (Valid Time) ```sql CREATE COLLECTION sensor_readings ( ts TIMESTAMP TIME_KEY, location VARCHAR, temperature FLOAT ) WITH (engine='timeseries', bitemporal=true); -- Original reading INSERT INTO sensor_readings (ts, location, temperature, valid_time) VALUES ('2026-04-01T10:00:00Z', 'warehouse-a', 21.5, '2026-04-01T10:00:00Z'); -- Discover it was wrong; insert a correction valid as-of April 2nd INSERT INTO sensor_readings (ts, location, temperature, valid_time) VALUES ('2026-04-01T10:00:00Z', 'warehouse-a', 22.3, '2026-04-02T15:30:00Z'); -- What we knew on April 1st (before correction) SELECT location, temperature FROM sensor_readings WHERE ts BETWEEN '2026-04-01' AND '2026-04-02' AS OF VALID TIME '2026-04-01T10:00:00Z'; -- What we know now (after correction) SELECT location, temperature FROM sensor_readings WHERE ts BETWEEN '2026-04-01' AND '2026-04-02' AS OF VALID TIME '2026-04-02T15:30:00Z'; ``` ### Bitemporal Array Snapshot ```sql CREATE ARRAY climate_grid DIMS (lon INT64 [-180..180], lat INT64 [-90..90]) ATTRS (temp_c FLOAT64) TILE_EXTENTS (64, 64) WITH (audit_retain_ms = 7776000000); -- 90 days -- Cells as committed yesterday SELECT lon, lat, temp_c FROM ARRAY_SLICE( 'climate_grid', '{lon: [-10, 9], lat: [0, 19]}', ['temp_c'] ) AS OF SYSTEM TIME '2026-06-06T00:00:00Z'; ``` ### Lineage and Compliance ```sql SELECT status, _ts_system FROM transactions WHERE id = 'txn-1' AS OF SYSTEM TIME NULL -- returns every system-time version, ascending ORDER BY _ts_system ASC; ``` `AS OF SYSTEM TIME NULL` returns every system-time version of each matching row, ordered ascending. Each version row carries the user columns plus three synthetic temporal columns: `_ts_system`, `_ts_valid_from`, and `_ts_valid_until`. Unbounded valid-time ends surface as the raw `i64::MIN` / `i64::MAX` sentinels (matching the Columnar and Timeseries engines). It is supported on the Document (strict and schemaless), Columnar, and Timeseries engines, and on `ARRAY_SLICE`. An `ARRAY_SLICE` version row carries the dimension and attribute columns plus `_ts_system` only. It is not supported on the Graph engine or on `ARRAY_AGG`, nor when reading through a database clone. Those return a typed error rather than collapsing to a single version. ## Index Engines and Temporal Composition Vector, FTS, KV, and Spatial don't carry temporal columns — by design. They are **index engines** that point at records living in data-bearing engines. Indexes don't have time; the records they reference do. To query any of these "as of", attach the index to a collection with `bitemporal=true`. The collection holds the payload + temporal columns, the index returns candidate IDs, and `AS OF` filters at the collection layer. ### Bitemporal Vector Search ```sql CREATE COLLECTION product_embeddings ( id UUID DEFAULT gen_uuid_v7(), product_id UUID, description TEXT, embedding FLOAT[384], updated_at TIMESTAMP DEFAULT now() ) WITH (engine='document_strict', bitemporal=true); CREATE VECTOR INDEX idx_product_vec ON product_embeddings METRIC cosine DIM 384; -- Nearest neighbors as of 30 days ago SELECT p.product_id, p.description, vector_distance(p.embedding, $query_vec) AS score FROM product_embeddings p AS OF SYSTEM TIME '2026-05-08T00:00:00Z' WHERE p.id IN ( SEARCH product_embeddings USING VECTOR(embedding, $query_vec, 20) ) ORDER BY score LIMIT 10; ``` The vector index narrows the candidate set; the `AS OF SYSTEM TIME` clause on the collection removes candidates that didn't exist at that system time. ### Bitemporal Full-Text Search ```sql CREATE COLLECTION articles ( id UUID DEFAULT gen_uuid_v7(), title VARCHAR, body TEXT, published_at TIMESTAMP ) WITH (engine='document_strict', bitemporal=true); CREATE SEARCH INDEX ON articles FIELDS title, body ANALYZER 'english'; SELECT id, title FROM articles AS OF SYSTEM TIME '2026-06-06T00:00:00Z' WHERE text_match(body, 'distributed consensus raft') ORDER BY bm25_score(body, 'distributed consensus raft') DESC LIMIT 20; ``` ### Bitemporal Spatial Queries ```sql CREATE COLLECTION store_locations ( id UUID DEFAULT gen_uuid_v7(), name VARCHAR, location GEOMETRY, opened_at TIMESTAMP, closed_at TIMESTAMP ) WITH (engine='document_strict', bitemporal=true); CREATE SPATIAL INDEX ON store_locations FIELDS location; SELECT id, name, ST_Distance(location, ST_Point(-73.990, 40.750)) AS dist_m FROM store_locations AS OF SYSTEM TIME 1704067200000 WHERE ST_DWithin(location, ST_Point(-73.990, 40.750), 5000) ORDER BY dist_m; ``` ### Temporal Key-Value: Use `document_strict` The KV engine targets O(1) point lookups and doesn't carry temporal columns. For versioned config, auditable feature flags, or time-stamped session state, use a `document_strict` collection with a unique index — O(1) lookup is preserved, temporal history comes from the document layer: ```sql CREATE COLLECTION config_entries ( id UUID DEFAULT gen_uuid_v7(), key VARCHAR, value TEXT, updated_at TIMESTAMP DEFAULT now() ) WITH (engine='document_strict', bitemporal=true); CREATE UNIQUE INDEX ON config_entries(key); INSERT INTO config_entries (key, value) VALUES ('feature_x_enabled', 'true') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value; SELECT value FROM config_entries WHERE key = 'feature_x_enabled'; -- What was the value 7 days ago? SELECT value FROM config_entries AS OF SYSTEM TIME '2026-05-31T00:00:00Z' WHERE key = 'feature_x_enabled'; ``` ## GDPR and Data Minimization `audit_retain_ms` enforces automatic purge of old versions during compaction: ```sql CREATE COLLECTION user_activity ( user_id UUID, action VARCHAR, ts TIMESTAMP TIME_KEY ) WITH (engine='columnar', audit_retain_ms=2592000000); -- 30 days ``` Tiles or row-versions older than the window are irreversibly purged. Historical queries beyond the retention window return no rows for that range. ## Performance Notes - **System time queries** read from historical snapshots — performance depends on snapshot availability for the requested time - **Valid time queries** scan all versions and filter — slower than single-version reads - **Both clauses** intersect — slower still, but produce precise audit trails For large collections with heavy correction traffic: archive old versions to L2 (S3) cold storage periodically, reduce `audit_retain_ms` once the compliance window expires, and rely on columnar compression to keep storage overhead low. --- # SQL Reference Index (docs/sql/index) --- title: SQL Reference Index description: Complete index of NodeDB SQL features — standard SQL, engine extensions, DDL, DML, and known gaps. --- # SQL Reference NodeDB exposes a PostgreSQL-compatible SQL surface over pgwire, HTTP, and the native protocol. All features below are available in every deployment mode (Origin cloud, Origin local, NodeDB-Lite where noted). ## Core SQL | Page | What it covers | | ---- | -------------- | | [Overview](overview) | Query execution model, PG compatibility basics, isolation level | | [DDL](ddl) | Collections, indexes, triggers, functions, materialized views, cron, backup | | [SELECT](select) | Filtering, aggregates, window functions, CTEs, recursive CTEs, set operations | | [INSERT & UPSERT](insert-upsert) | INSERT, ON CONFLICT, UPSERT, COPY FROM | | [UPDATE & DELETE](update-delete) | UPDATE, UPDATE … FROM, DELETE, RETURNING, MERGE, transactions | | [JOINs & Aggregations](joins-aggregations) | Inner/outer/semi/anti joins, LATERAL, GROUP BY ROLLUP/CUBE/GROUPING SETS | | [Functions](functions) | Scalar, aggregate, date/time, KV atomic, timeseries, vector, FTS, CRDT | ## Engine-Specific SQL | Page | What it covers | | ---- | -------------- | | [Vector Search](vector-search) | ANN, filtered search, quantization, vector-primary collections | | [Full-Text Search](fulltext-search) | BM25, fuzzy, NOT operator, synonyms, hybrid search | | [Graph Queries](graph-queries) | Edge ops, traversal, MATCH patterns, algorithms, GraphRAG | | [Spatial Queries](spatial-queries) | OGC predicates, proximity, geofencing, H3, spatial joins | | [CRDT Operations](crdt-operations) | crdt_state(), crdt_apply(), conflict policies | | [Fusion & RRF](fusion-rrf) | Two-source and three-source Reciprocal Rank Fusion, FUSION DSL | ## SQL Extensions | Page | What it covers | | ---- | -------------- | | [JSON Operators](json-operators) | `->`, `->>` `#>`, `#>>`, `@>`, `<@`, `?`, `?|`, `?&` | | [COPY](copy) | COPY FROM (import), COPY TO (export), NDJSON / CSV / JSON array | | [LISTEN / NOTIFY](listen-notify) | Async pgwire notifications, transaction buffering, tenant scoping | | [Custom Types](custom-types) | CREATE TYPE AS ENUM, CREATE TYPE AS composite, ALTER TYPE ADD VALUE | | [Window Frames](window-frames) | ROWS, RANGE, GROUPS frame modes with all boundary combinations | | [Lateral Subqueries](lateral-subqueries) | LATERAL FROM, JOIN LATERAL, planning modes | | [Recursive CTEs](recursive-cte) | WITH RECURSIVE, value-generating forms, validation rules | | [Grouping Sets](grouping-sets) | GROUP BY ROLLUP, CUBE, GROUPING SETS, GROUPING() function | ## Diagnostics | Page | What it covers | | ---- | -------------- | | [EXPLAIN](explain) | Query plans, cross-shard dispatch, session variables, introspection | ## Known Gaps Features not yet available: - **Transactional DDL** — `CREATE COLLECTION`, `CREATE INDEX`, and other DDL statements auto-commit and cannot be rolled back inside a multi-statement transaction. - **`EXPLAIN ANALYZE`** — per-operator runtime stats require Data Plane instrumentation not yet wired. `EXPLAIN` (plan-only) works. - **Custom types as pgwire wire-format codecs** — enum and composite types are stored and queryable, but the pgwire layer sends them as `TEXT` rather than their registered OID binary format. - **`ALTER TYPE` beyond `ADD VALUE`** — renaming labels, dropping labels, and reordering composite fields are not yet supported. - **`ALTER TYPE … RENAME VALUE`** — blocked by the same gap above. - **`DROP TYPE` cascade** — `DROP TYPE` is protected; it fails if the type is in use. Cascade dropping the dependent collections first is required manually. - **`CHECK` constraints, `FOREIGN KEY`, `REFERENCES`** — rejected at DDL time. See [DDL](ddl) for the canonical replacements. - **`UPDATE/DELETE … JOIN` syntax** — rewrite as a subquery. `UPDATE … FROM` is supported; `UPDATE … JOIN` is not. - **Full `ALTER TABLE` / `ALTER COLLECTION`** — `ADD COLUMN` and `DROP COLUMN` work; renaming columns, changing column types, and adding/dropping constraints are not yet supported. - **`COPY FROM STDIN`** — the streaming STDIN form is handled only by the backup/restore path. File-path `COPY FROM` and `COPY TO` work. - **`LISTEN` on non-collection channels** — `LISTEN` subscribes to a collection's change stream. Arbitrary string channel names (Postgres style) are not supported. - **Prepared statements for DDL** — only DML (SELECT, INSERT, UPDATE, DELETE) and some DQL statements support the extended-query (prepared) protocol. --- # SQL Overview (docs/sql/overview) --- title: SQL Overview description: NodeDB uses SQL as its primary query language, extended with engine-specific syntax for vectors, graphs, spatial, and more. --- # SQL Overview NodeDB uses SQL as its primary query language. Whether you connect via `ndb`, `psql`, or HTTP — the same SQL works everywhere. ## Query Execution ``` ndb CLI (NDB protocol) ──┐ psql (pgwire) ──┼──► SQL Parser ──► EngineRules ──► PhysicalPlan ──► Data Plane HTTP (REST/JSON) ──┘ ``` Three doors, one room. Same parser, same optimizer, same execution engine. ## Standard SQL Support NodeDB supports standard SQL with high PostgreSQL compatibility: - SELECT with WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET - JOINs (INNER, LEFT, RIGHT, CROSS, SEMI, ANTI) - Window functions (ROW_NUMBER, RANK, LAG, LEAD, SUM OVER) - CTEs (WITH, WITH RECURSIVE) - Subqueries and derived tables - Set operations (UNION, INTERSECT, EXCEPT) - Transactions with savepoints (BEGIN, COMMIT, ROLLBACK, SAVEPOINT) - Prepared statements ## Engine-Specific Extensions Beyond standard SQL, NodeDB extends the language for each engine: - **Vector** — `vector_distance()` with `<->` / `<=>` / `<#>` operators, ANN-aware `ORDER BY ... LIMIT k` - **Graph** — `GRAPH TRAVERSE`, `GRAPH ALGO`, `MATCH` patterns - **Full-Text** — `text_match()`, `bm25_score()`, `search_score()` - **Spatial** — `ST_DWithin()`, `ST_Contains()`, `ST_Distance()`, etc. - **Timeseries** — `time_bucket()`, `ts_rate()`, continuous aggregates - **KV** — `KV_INCR()`, `KV_CAS()`, sorted indexes, rate gates - **CRDT** — `crdt_state()`, `crdt_apply()` ## PostgreSQL Compatibility These standard Postgres surface elements work natively over pgwire — no rewriting, no extension. ### Identifiers vs. Literals `"quoted"` is a case-preserved identifier; `'quoted'` is a string literal. `SELECT "userId"` projects the column named `userId` exactly; `SELECT 'userId'` returns the constant string. ### Pattern Matching ```sql SELECT * FROM users WHERE name LIKE 'Ali%'; -- case-sensitive SELECT * FROM users WHERE email ILIKE '%@EXAMPLE.COM'; -- case-insensitive ``` ### JSON Operators ```sql doc -> 'addr' -- field as JSON doc ->> 'name' -- field as text doc #> '{addr,city}' -- nested path as JSON doc #>> '{addr,city}' -- nested path as text doc @> '{"role":"admin"}' -- left contains right doc <@ '{"role":"admin"}' -- left contained in right doc ? 'email' -- top-level key exists doc ?| ARRAY['phone','email'] -- any key exists doc ?& ARRAY['name','email'] -- all keys exist ``` See [JSON Operators](json-operators) for full reference and examples. ### Full-Text Search (Postgres syntax) ```sql SELECT * FROM articles WHERE to_tsvector('english', body) @@ to_tsquery('english', 'transformer & attention'); ``` NodeDB also exposes `text_match()`, `bm25_score()`, and `search_score()` for finer control — see [Full-Text Search](fulltext-search). ### Vector Distance Operators | Operator | Function | Metric | | -------- | ------------------------------ | --------------------- | | `<->` | `vector_distance` | L2 (default) | | `<=>` | `vector_cosine_distance` | Cosine | | `<#>` | `vector_neg_inner_product` | Negative inner product | ```sql SELECT id FROM articles ORDER BY embedding <=> $query LIMIT 10; ``` ## Isolation Level Every transaction block is a serializable snapshot transaction. `BEGIN`, `START TRANSACTION`, `SET TRANSACTION` and `SET SESSION CHARACTERISTICS AS TRANSACTION` accept `SERIALIZABLE`, `REPEATABLE READ`, `READ COMMITTED` and `READ UNCOMMITTED`. Every level runs serializable, and `SHOW transaction_isolation` reports `serializable`. - A block reads one snapshot, taken at its first statement and not at `BEGIN`. - Every read in the block sees that snapshot plus the block's own writes. - `COMMIT` checks, at the moment the writes apply, that nothing the transaction read or overwrote changed after its snapshot. If something changed, `COMMIT` fails with SQLSTATE `40001`. Retry the whole block. - A read-only block commits without validation and never fails with `40001`. - A snapshot older than `[tuning.network] txn_snapshot_max_age_secs` (default 300) fails the next statement with `40001`. - A write that cannot be buffered inside a block is refused with SQLSTATE `25001`. - An autocommit statement reads the current state at a per-statement cut. - `AS OF SYSTEM TIME` works on every collection. --- # DDL (docs/sql/ddl) --- title: DDL description: CREATE, ALTER, and DROP statements for collections, indexes, triggers, functions, and more. --- # DDL (Data Definition Language) ## Database Management ```sql -- Create database with optional quota settings CREATE DATABASE emp_prod WITH ( max_memory_bytes = 1073741824, max_storage_bytes = 10737418240, max_qps = 1000, max_connections = 100, cache_weight = 1, priority_class = 'standard', maintenance_cpu_pct = 25 ); -- Drop database DROP DATABASE emp_prod; -- errors if non-empty DROP DATABASE emp_prod CASCADE; -- cascades drop to all collections DROP DATABASE emp_prod FORCE; -- synonym for CASCADE: forces materialization of dependent clones, then drops -- Rename database ALTER DATABASE emp_prod RENAME TO emp_prod_old; -- Set or update quota ALTER DATABASE emp_prod SET QUOTA ( max_memory_bytes = 2147483648, max_qps = 2000, cache_weight = 2 ); -- Enable DML audit ALTER DATABASE emp_prod SET AUDIT_DML = 'writes'; -- 'none' | 'writes' | 'all' -- Set idle session timeout ALTER DATABASE emp_prod SET IDLE_TIMEOUT 1800; -- seconds; 0 = disabled -- Clone database CLONE DATABASE staging FROM emp_prod AS OF SYSTEM TIME 1730000000000; CLONE DATABASE preview FROM emp_prod AS OF LATEST; -- Force materialization of a clone (blocks until complete) ALTER DATABASE staging MATERIALIZE; -- Mirror database MIRROR DATABASE emp_eu FROM emp_prod MODE = async; MIRROR DATABASE emp_eu FROM emp_prod MODE = sync; -- Promote mirror to writable ALTER DATABASE emp_eu PROMOTE; -- Move tenant between databases (offline, requires all sessions drained) MOVE TENANT acme FROM emp_us TO emp_eu; -- Set per-tenant quota within a database ALTER TENANT acme IN DATABASE emp_prod SET QUOTA ( max_memory_bytes = 536870912, max_qps = 500, max_connections = 50, max_vector_dim = 1536, max_graph_depth = 5 ); -- Session management USE DATABASE emp_prod; -- or pgwire \c emp_prod SHOW DATABASES; SHOW DATABASE LINEAGE FOR staging; SHOW DATABASE MIRROR STATUS FOR emp_eu; SHOW DATABASE QUOTA FOR emp_prod; SHOW DATABASE USAGE FOR emp_prod; SHOW TENANT QUOTA FOR acme IN DATABASE emp_prod; SHOW TENANT USAGE FOR acme IN DATABASE emp_prod; SHOW SESSIONS; SHOW SESSIONS IN DATABASE emp_prod; KILL SESSION '550e8400-e29b-41d4-a716-446655440000'; SHOW AUDIT IN DATABASE emp_prod WHERE event_type = 'database_cloned'; -- Role and access GRANT DATABASE_OWNER ON DATABASE emp_prod TO alice; GRANT DATABASE_EDITOR ON DATABASE emp_prod TO bob; GRANT DATABASE_READER ON DATABASE emp_prod TO charlie; GRANT CREATE COLLECTION ON DATABASE emp_prod TO developers_role; GRANT SELECT ON DATABASE emp_prod TO analysts_role; GRANT SELECT ON COLLECTION users TO analysts_role; GRANT SELECT ON TABLE users TO analysts_role; ALTER USER alice SET DEFAULT DATABASE emp_prod; -- API keys with database scope CREATE API KEY prod_key FOR alice WITH DATABASES (emp_prod, emp_staging); ALTER API KEY prod_key SET DATABASES (emp_prod); SHOW API KEYS; -- Service accounts with database scope CREATE SERVICE ACCOUNT sa_prod FOR DATABASE emp_prod; ALTER SERVICE ACCOUNT sa_prod SET DATABASES (emp_prod, emp_staging); DROP SERVICE ACCOUNT sa_prod; -- OIDC / SSO providers CREATE OIDC PROVIDER corp_sso ISSUER 'https://idp.corp.com' JWKS_URI 'https://idp.corp.com/.well-known/jwks.json' AUDIENCE 'nodedb-prod' CLAIM MAPPING WHEN groups = 'eng' ADD DATABASES [1]; ALTER OIDC PROVIDER corp_sso SET CLAIM MAPPING WHEN groups = 'eng' ADD DATABASES [1, 2]; DROP OIDC PROVIDER IF EXISTS corp_sso; SHOW OIDC PROVIDERS; ``` See the administration guides for detailed walkthroughs: [Database Management](../administration/databases), [Database Clone](../administration/database-clone), [Database Mirror](../administration/database-mirror), [Move Tenant](../administration/move-tenant), [Quotas](../administration/quotas), [Session Management](../administration/session-management), [OIDC / SSO](../administration/oidc-sso). ## Collections ```sql -- Schemaless document (default) CREATE COLLECTION users; -- Strict document CREATE COLLECTION orders ( id TEXT PRIMARY KEY, customer_id TEXT, total FLOAT, status TEXT, created_at TIMESTAMP ) WITH (engine='document_strict'); -- Key-Value CREATE COLLECTION sessions (key TEXT PRIMARY KEY) WITH (engine='kv'); -- Columnar (plain analytics) CREATE COLLECTION logs (ts TIMESTAMP TIME_KEY, host VARCHAR, level VARCHAR, message VARCHAR) WITH (engine='columnar'); -- Timeseries (peer engine, append-only with retention + continuous aggregates) CREATE COLLECTION metrics (ts TIMESTAMP TIME_KEY, host VARCHAR, cpu FLOAT) WITH (engine='timeseries', partition_by='1h', retention='90d'); -- Spatial (peer engine, R-tree + geohash + OGC predicates) CREATE COLLECTION locations (geom GEOMETRY SPATIAL_INDEX, name VARCHAR) WITH (engine='spatial'); -- Convenience alias for timeseries CREATE TIMESERIES metrics; DROP COLLECTION users; -- soft-delete: tombstoned, still restorable UNDROP COLLECTION users; -- restore while within the retention window DROP COLLECTION users PURGE; -- admin-only: immediate hard-delete, not restorable SHOW COLLECTIONS; DESCRIBE users; ``` `DROP COLLECTION` is two-phase. A plain drop marks the collection as tombstoned and enqueues background L2 cleanup after a configurable retention window; within that window, `UNDROP COLLECTION` restores the collection and its data. Admins can bypass the window with `DROP ... PURGE`. ```sql -- Retention window knobs ALTER SYSTEM SET collection_gc_retention = '7d'; ALTER TENANT acme SET collection_gc_retention = '24h'; -- Inspect the lifecycle SELECT name, dropped_at, size_bytes_estimate FROM _system.dropped_collections; SELECT * FROM _system.l2_cleanup_queue; ``` Dropping a collection also cascades downstream catalog state: dependent materialized views are unregistered, change-stream consumer groups are torn down, and the L2 cleanup worker reclaims segment files. ## Constraint Policy NodeDB accepts a deliberately small subset of SQL constraints in `CREATE COLLECTION` / `CREATE TABLE`. Anything outside that subset is rejected with SQLSTATE `0A000` (`feature_not_supported`) — the parser tells you the canonical replacement instead of silently stripping the constraint. **Accepted:** inline ` PRIMARY KEY` on a single column. The named column becomes the row identity; without one, NodeDB auto-injects `_rowid INT64 PRIMARY KEY`. **Rejected at DDL time:** | Form | Replacement | | ------------------------------------------ | ---------------------------------------------------------- | | Table-level `PRIMARY KEY (col)` | Inline form: ` PRIMARY KEY` | | Named `CONSTRAINT pk_x PRIMARY KEY (col)` | Inline form | | Inline or table-level `UNIQUE` | `CREATE UNIQUE INDEX ON tbl(col)` | | Inline or table-level `CHECK (...)` | Application-side validation (typeguards on schemaless docs) | | `FOREIGN KEY (...) REFERENCES ...` | Application-side enforcement | | Column-level `REFERENCES other(col)` | Application-side enforcement | These are launch-frozen choices. UNIQUE/CHECK/FK/REFERENCES would each pull in a fixed semantic that's expensive to walk back, and the canonical replacements (unique indexes, app-side validation) cover the same use cases without locking the engine into a particular cross-row enforcement strategy. ## Schema Evolution ```sql ALTER TABLE orders ADD COLUMN priority INT; ALTER COLLECTION orders ADD COLUMN region STRING DEFAULT 'us-east'; ALTER COLLECTION orders DROP COLUMN region; ``` ## Storage Conversion ```sql CONVERT COLLECTION cache TO kv; CONVERT COLLECTION users TO document_strict; CONVERT COLLECTION logs TO document_schemaless; ``` On a bitemporal collection, `CONVERT` to `document_schemaless` or `document_strict` rewrites every version of every row, with its own system and valid times, so `AS OF` reads return the same rows after the conversion. `CONVERT` to `kv` is refused before any row moves, because a key-value collection holds no row versions. ## Indexes ```sql CREATE INDEX idx_email ON users(email); CREATE INDEX IF NOT EXISTS idx_email ON users(email); CREATE UNIQUE INDEX ON users(username); CREATE VECTOR INDEX ON articles METRIC cosine DIM 384 M 16 EF_CONSTRUCTION 200; CREATE SEARCH INDEX ON articles FIELDS title, body ANALYZER 'english' FUZZY true; CREATE SPATIAL INDEX ON locations(geom); CREATE SORTED INDEX lb ON scores (score DESC) KEY player_id; DROP INDEX idx_email; DROP INDEX IF EXISTS idx_email; -- Rebuild all indexes on a collection (non-blocking concurrent path recommended) REINDEX CONCURRENTLY articles; -- Rebuild a specific named index only REINDEX INDEX idx_email CONCURRENTLY users; -- Blocking rebuild (holds write lock for the duration — use only in maintenance windows) REINDEX articles; ``` `CREATE INDEX ... IF NOT EXISTS` and `DROP INDEX ... IF EXISTS` make DDL idempotent — re-running a script does not error if the index already exists (or does not exist). `REINDEX CONCURRENTLY` builds the new index in a shadow location while reads and writes continue against the live index. Cutover is a single atomic swap. Supported for HNSW vector indexes, FTS LSM indexes, and Graph CSR indexes. Secondary B-tree indexes use the blocking path regardless of `CONCURRENTLY` (rebuild is fast for B-tree). ## Triggers ```sql -- ASYNC (default): Event Plane, zero write-latency impact CREATE TRIGGER notify AFTER INSERT ON orders FOR EACH ROW $$ BEGIN INSERT INTO notifications (user_id, message) VALUES (NEW.customer_id, 'Order placed'); END; $$; -- SYNC: same transaction, ACID CREATE TRIGGER enforce AFTER UPDATE ON accounts FOR EACH ROW WITH (EXECUTION = SYNC) $$ BEGIN IF NEW.balance < 0 THEN RAISE EXCEPTION 'Negative balance'; END IF; END; $$; DROP TRIGGER notify ON orders; SHOW TRIGGERS; ``` The op tag (INSERT vs UPDATE) is derived from storage prior-bytes, not the surface SQL verb. An `UPSERT` or `INSERT ... ON CONFLICT (pk) DO UPDATE` that overwrites an existing row fires `AFTER UPDATE`; the same statement against a non-existent key fires `AFTER INSERT`. `ON CONFLICT DO NOTHING` emits no event on conflict. ## Functions & Procedures ```sql -- SQL expression (inlined, zero overhead) CREATE FUNCTION full_name(first VARCHAR, last VARCHAR) RETURNS VARCHAR LANGUAGE SQL IMMUTABLE AS $$ first || ' ' || last $$; -- Procedural CREATE PROCEDURE transfer_funds(from_id UUID, to_id UUID, amount DECIMAL) BEGIN UPDATE accounts SET balance = balance - amount WHERE id = from_id; UPDATE accounts SET balance = balance + amount WHERE id = to_id; END; CALL transfer_funds('acc_a', 'acc_b', 50.00); ``` ## Change Streams & Topics ```sql CREATE CHANGE STREAM order_events ON orders WITH (URL = 'https://hooks.example.com/orders'); CREATE CONSUMER GROUP processors ON order_events; CREATE TOPIC alerts WITH (RETENTION = '1 hour'); PUBLISH TO alerts 'message'; ``` ## Materialized Views ```sql CREATE MATERIALIZED VIEW order_stats AS SELECT status, COUNT(*), SUM(total) FROM orders GROUP BY status; REFRESH MATERIALIZED VIEW order_stats; CREATE CONTINUOUS AGGREGATE cpu_hourly ON cpu_metrics BUCKET '1h' AGGREGATE avg(cpu) AS avg_cpu GROUP BY host WITH (refresh_interval = '1m'); REFRESH CONTINUOUS AGGREGATE cpu_hourly; ``` ## Cron Scheduler ```sql CREATE SCHEDULE nightly_cleanup CRON '0 2 * * *' AS BEGIN DELETE FROM sessions WHERE expires_at < now(); END; ``` ## Backup & Restore ```sql BACKUP TENANT acme TO '/backups/acme.bak'; RESTORE TENANT acme FROM '/backups/acme.bak'; RESTORE TENANT acme FROM '/backups/acme.bak' DRY RUN; PURGE TENANT acme CONFIRM; ``` --- # SELECT (docs/sql/select) --- title: SELECT description: Query data with filtering, aggregation, window functions, CTEs, and subqueries. --- # SELECT ```sql SELECT [DISTINCT] FROM [WHERE ] [GROUP BY ] [HAVING ] [ORDER BY [ASC|DESC], ...] [LIMIT ] [OFFSET ] ``` ## Filtering ```sql SELECT * FROM users WHERE age > 30 AND status = 'active'; SELECT * FROM users WHERE name LIKE 'Ali%'; SELECT * FROM users WHERE email ILIKE '%@EXAMPLE.COM'; SELECT * FROM orders WHERE total BETWEEN 10 AND 100; SELECT * FROM users WHERE role IN ('admin', 'editor'); SELECT * FROM users WHERE deleted_at IS NULL; ``` ## Aggregates ```sql SELECT status, COUNT(*), AVG(age), MIN(salary), MAX(salary) FROM employees WHERE department = 'sales' GROUP BY status HAVING COUNT(*) > 5; SELECT COUNT(DISTINCT user_id) FROM orders; ``` ## Window Functions ```sql SELECT id, ROW_NUMBER() OVER (ORDER BY created_at) AS rn, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank, LAG(salary, 1) OVER (ORDER BY created_at) AS prev_salary, SUM(amount) OVER (ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM employees; ``` `ROWS`, `RANGE`, and `GROUPS` frame modes are all supported. See [Window Frames](window-frames) for the full frame syntax and all boundary combinations. ## CTEs & Subqueries ```sql WITH active AS (SELECT id FROM users WHERE status = 'active') SELECT * FROM orders WHERE user_id IN (SELECT id FROM active); -- Recursive CTE WITH RECURSIVE subordinates AS ( SELECT id, name, manager_id FROM employees WHERE id = 'emp_root' UNION ALL SELECT e.id, e.name, e.manager_id FROM employees e JOIN subordinates s ON e.manager_id = s.id ) SELECT * FROM subordinates; ``` See [Recursive CTEs](recursive-cte) for the full reference including value-generating forms, cycle prevention, and validation rules. ## Set Operations ```sql SELECT id FROM collection_a UNION ALL SELECT id FROM collection_b; SELECT id FROM collection_a INTERSECT SELECT id FROM collection_b; SELECT id FROM collection_a EXCEPT SELECT id FROM collection_b; ``` ## Computed Columns ```sql SELECT price * qty AS total, UPPER(name) AS name_upper, CASE WHEN price > 100 THEN 'expensive' ELSE 'cheap' END AS tier FROM orders; ``` --- # INSERT & UPSERT (docs/sql/insert-upsert) --- title: INSERT & UPSERT description: Insert documents, upsert with merge semantics, and bulk import. --- # INSERT & UPSERT ## INSERT ```sql -- Single row INSERT INTO users (id, name, email) VALUES ('u1', 'Alice', 'alice@example.com'); -- Multiple rows INSERT INTO users (id, name) VALUES ('u1', 'Alice'), ('u2', 'Bob'); -- Object literal syntax (schemaless collections) INSERT INTO users { name: 'Alice', email: 'alice@example.com', age: 30 }; -- INSERT ... SELECT INSERT INTO archive SELECT * FROM orders WHERE created_at < '2025-01-01'; ``` Plain `INSERT` is strict: a duplicate primary key raises `unique_violation` (SQLSTATE `23505`). Use `ON CONFLICT` or `UPSERT` for "insert if absent" or "insert or overwrite" semantics. ## INSERT ... ON CONFLICT ```sql -- Skip rows that would collide with an existing PK (no error) INSERT INTO users (id, name) VALUES ('u1', 'Alice') ON CONFLICT DO NOTHING; -- Overwrite selected fields on conflict. EXCLUDED refers to the incoming row; -- bare column names refer to the existing row. INSERT INTO users (id, name, login_count) VALUES ('u1', 'Alice', 1) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, login_count = users.login_count + EXCLUDED.login_count; ``` `ON CONFLICT DO UPDATE` fires `AFTER UPDATE` triggers (not `AFTER INSERT`) when a row is overwritten — the trigger op tag is derived from storage prior-bytes, not the surface SQL verb. ## UPSERT Insert or overwrite if the primary key already exists: ```sql UPSERT INTO users (id, name, role) VALUES ('u1', 'Alice', 'admin'); -- Object literal syntax UPSERT INTO users { id: 'u1', name: 'Alice', role: 'admin' }; ``` `UPSERT` is equivalent to `INSERT ... ON CONFLICT () DO UPDATE SET = EXCLUDED.`. It fires `AFTER UPDATE` on overwrite and `AFTER INSERT` on first write. ## Bulk Import ```sql -- Auto-detected format (NDJSON, JSON array, or CSV) COPY users FROM '/path/to/users.ndjson'; COPY users FROM '/path/to/users.csv' WITH (FORMAT csv); ``` See [COPY](copy) for the full syntax, all format options, and `COPY TO` for export. --- # UPDATE & DELETE (docs/sql/update-delete) --- title: UPDATE & DELETE description: Point and bulk mutations, transactions, and limitations. --- # UPDATE & DELETE ## UPDATE ```sql UPDATE users SET role = 'admin' WHERE id = 'u1'; UPDATE users SET status = 'inactive' WHERE last_login < '2025-01-01'; ``` ## DELETE ```sql DELETE FROM users WHERE id = 'u1'; DELETE FROM orders WHERE status = 'cancelled'; TRUNCATE users; ``` ## Transactions ```sql BEGIN; INSERT INTO orders (id, total) VALUES ('o1', 99.99); UPDATE inventory SET stock = stock - 1 WHERE id = 'item1'; COMMIT; -- Rollback BEGIN; DELETE FROM users WHERE id = 'u1'; ROLLBACK; -- Savepoints BEGIN; SAVEPOINT sp1; INSERT INTO users (id, name) VALUES ('u1', 'Alice'); ROLLBACK TO sp1; COMMIT; ``` ## Atomic Transfers ```sql -- Fungible (currency, resources) SELECT TRANSFER('wallets', 'player-A', 'player-B', 'gold', 500); -- Non-fungible (unique items) SELECT TRANSFER_ITEM('inventory', 'inventory', 'sword-of-doom', 'player-A', 'player-B'); ``` ## RETURNING `UPDATE` and `DELETE` support a `RETURNING` clause to get the affected rows back in the same round-trip. ```sql -- UPDATE: returns the post-update image UPDATE users SET role = 'admin' WHERE id = 'u1' RETURNING *; UPDATE users SET status = 'inactive' WHERE last_login < '2025-01-01' RETURNING id, status; -- DELETE: returns the pre-delete image DELETE FROM orders WHERE id = 'o1' RETURNING *; DELETE FROM orders WHERE status = 'cancelled' RETURNING id, total; ``` `RETURNING *` projects all columns. `RETURNING col1, col2` projects named columns. Arithmetic expressions in `RETURNING` are not supported — bare column names and `*` only. Works in both simple-query and extended-query (prepared statement) protocols. ## UPDATE … FROM `UPDATE … FROM` updates rows in the target collection based on matching rows in one or more source collections. This is the standard alternative to `UPDATE … JOIN` syntax. ```sql -- Apply a price increase from a pricing table UPDATE products p SET price = pricing.new_price FROM pricing WHERE p.id = pricing.product_id; -- Update orders using data from a users table UPDATE orders o SET region = u.region FROM users u WHERE o.user_id = u.id; -- Use a CTE as the source WITH discounts AS ( SELECT user_id, 0.10 AS pct FROM promotions WHERE active = true ) UPDATE orders o SET total = o.total * (1 - d.pct) FROM discounts d WHERE o.user_id = d.user_id; ``` Constraints: - Exactly one source table (or CTE) is supported. - The `WHERE` clause must contain an equi-join predicate between target and source (`target.col = source.col`). - Inline subqueries in `FROM` are not supported; use a CTE. - `FROM` source collections cannot themselves contain `JOIN`s. ## MERGE `MERGE` is a single-statement upsert/delete driven by a source query. It evaluates `WHEN MATCHED` and `WHEN NOT MATCHED` clauses to decide what to do with each row from the source. ```sql MERGE INTO orders AS target USING staging_orders AS source ON target.id = source.id WHEN MATCHED THEN UPDATE SET total = source.total, status = source.status WHEN NOT MATCHED THEN INSERT (id, user_id, total, status) VALUES (source.id, source.user_id, source.total, source.status); ``` ### WHEN NOT MATCHED BY SOURCE Optionally delete (or update) target rows that have no corresponding source row: ```sql MERGE INTO inventory AS target USING new_stock AS source ON target.sku = source.sku WHEN MATCHED THEN UPDATE SET qty = source.qty WHEN NOT MATCHED BY TARGET THEN INSERT (sku, qty) VALUES (source.sku, source.qty) WHEN NOT MATCHED BY SOURCE THEN DELETE; ``` ### MERGE clause kinds | Clause | Fires when | Allowed actions | | ----------------------------- | ------------------------------------------------------- | ------------------------ | | `WHEN MATCHED` | Source row matches a target row | `UPDATE SET …`, `DELETE` | | `WHEN NOT MATCHED [BY TARGET]`| Source row has no corresponding target row | `INSERT` | | `WHEN NOT MATCHED BY SOURCE` | Target row has no corresponding source row | `UPDATE SET …`, `DELETE` | Each clause may include an optional `AND ` condition: ```sql MERGE INTO accounts AS t USING updates AS s ON t.id = s.id WHEN MATCHED AND s.balance > 0 THEN UPDATE SET balance = s.balance WHEN MATCHED AND s.balance <= 0 THEN DELETE WHEN NOT MATCHED THEN INSERT (id, balance) VALUES (s.id, s.balance); ``` ## Limitations - `UPDATE/DELETE … JOIN` syntax is not supported. Use `UPDATE … FROM` or a subquery: `DELETE FROM orders WHERE user_id IN (SELECT id FROM users WHERE ...)` - `UPDATE/DELETE` on timeseries collections is not supported (append-only). Use retention policies. --- # JOINs & Aggregations (docs/sql/joins-aggregations) --- title: JOINs & Aggregations description: Inner, outer, semi, and anti joins. Aggregate functions and GROUP BY. --- # JOINs & Aggregations ## JOINs ```sql -- Inner join SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id; -- Left join SELECT u.name, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id; -- Cross join SELECT * FROM sizes CROSS JOIN colors; -- Semi join (EXISTS) SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id); -- Anti join (NOT EXISTS) SELECT * FROM users u WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id); ``` JOINs work across collections of different storage types — you can join a KV collection with a strict document collection. ### Unqualified Column Names An unqualified column in a join resolves to the one relation that has it. This applies to the SELECT list, WHERE, ON, GROUP BY, HAVING, ORDER BY, and aggregate arguments. | The column is… | Result | | ----------------------------------------------------------- | ------------------------------ | | Declared by exactly one relation | Resolves to that relation | | Declared by two or more relations | Refused: SQLSTATE `42702` | | Declared by none, and exactly one relation is schemaless | Resolves to the schemaless one | | Declared by none, and two or more relations are schemaless | Refused: SQLSTATE `42702` | | Accepted by no relation | Refused: SQLSTATE `42703` | A declared column wins over a schemaless relation. A schemaless collection accepts any field name, so when two schemaless collections are joined, NodeDB cannot know which one holds a field. The query is refused rather than reading NULL from the wrong side: ```text ERROR: column reference "region" is ambiguous SQLSTATE: 42702 ``` Qualify the column with its table name or alias: ```sql -- Refused when both events and devices are schemaless SELECT region, COUNT(*) FROM events e JOIN devices d ON e.device_id = d.id GROUP BY region; -- Qualified: reads region from devices SELECT d.region, COUNT(*) FROM events e JOIN devices d ON e.device_id = d.id GROUP BY d.region; ``` `USING (col)` names the column on both sides, so it is never ambiguous. Both sides must have the column. ### Derived Tables A subquery can be a join side. It works on either side and in every join type: inner, `LEFT`, `RIGHT`, `FULL`, and `CROSS`. It can also be any side of a multi-way join. ```sql -- Join each customer to the total of their orders SELECT c.region, t.total FROM customers c JOIN (SELECT cust, SUM(amount) AS total FROM orders GROUP BY cust) t ON c.id = t.cust; -- A derived table on the FROM side, with its own WHERE, ORDER BY and LIMIT SELECT c.id, o.id FROM (SELECT id FROM customers WHERE region = 'east' ORDER BY id LIMIT 10) c JOIN orders o ON o.cust = c.id; -- Aggregate over a join with a derived side SELECT c.region, SUM(t.total) FROM customers c JOIN (SELECT cust, SUM(amount) AS total FROM orders GROUP BY cust) t ON c.id = t.cust GROUP BY c.region; ``` - **Alias:** a derived side must have one. The alias qualifies its columns, so `t.total` reads the column the subquery projects. An unqualified column resolves to the derived side when that side is the only relation that projects it, as described above. - **Access rules:** row-level security and redaction apply to the collections the subquery reads. - **No correlation:** a derived side cannot refer to another relation of the same FROM clause. Such a query is refused with SQLSTATE `42601`. Use `JOIN LATERAL`, described below, to correlate a subquery with the rows before it: ```text ERROR: invalid reference to FROM-clause entry for table "c": a subquery in FROM cannot refer to other relations of the same query level; write JOIN LATERAL (SELECT ...) to correlate it SQLSTATE: 42601 ``` ## LATERAL Joins `LATERAL` allows the right-hand subquery to reference columns from the outer table. See [Lateral Subqueries](lateral-subqueries) for the full reference. Quick example: ```sql -- Top 3 most recent orders for each user SELECT u.id, u.name, o.id AS order_id, o.created_at FROM users u JOIN LATERAL ( SELECT id, created_at FROM orders WHERE user_id = u.id ORDER BY created_at DESC LIMIT 3 ) AS o ON true; -- LEFT JOIN LATERAL — preserve users with no orders SELECT u.id, o.last_order_at FROM users u LEFT JOIN LATERAL ( SELECT MAX(created_at) AS last_order_at FROM orders WHERE user_id = u.id ) AS o ON true; ``` ## Aggregate Functions | Function | Description | | ----------------------- | ----------------------- | | `COUNT(*)` | Row count | | `COUNT(DISTINCT col)` | Distinct count | | `SUM(col)` | Sum | | `AVG(col)` | Average | | `MIN(col)` / `MAX(col)` | Minimum / Maximum | ## Approximate Aggregates Mergeable across shards, usable in continuous aggregation: | Function | Description | | ------------------------------- | ------------------ | | `approx_count_distinct(col)` | HyperLogLog | | `approx_percentile(col, p)` | t-digest | | `approx_topk(col, k)` | SpaceSaving | ## Weighted Random Selection ```sql SELECT * FROM WEIGHTED_PICK('loot_table', weight => 'drop_rate', count => 1); SELECT * FROM WEIGHTED_PICK('gacha_pool', weight => 'probability', count => 10, SEED => 'player:pull'); ``` --- # Functions Reference (docs/sql/functions) --- title: Functions Reference description: Built-in scalar, aggregate, and engine-specific SQL functions. --- # Functions Reference ## String Functions `LENGTH`, `SUBSTR`, `UPPER`, `LOWER`, `TRIM`, `LTRIM`, `RTRIM`, `CONCAT` (or `||`), `REPLACE`, `SPLIT` ## Numeric Functions `ABS`, `CEIL`, `FLOOR`, `ROUND`, `SQRT`, `POWER`, `MOD` (or `%`), `GREATEST`, `LEAST` ## Date/Time Functions | Function | Description | | ------------------------------- | -------------------------------------- | | `NOW()` | Current UTC timestamp | | `CURRENT_TIMESTAMP()` | Alias for NOW() | | `EXTRACT(field FROM ts)` | Extract year, month, day, hour, etc. | | `DATE_TRUNC(unit, ts)` | Truncate to unit boundary | | `DATE_FORMAT(ts, fmt)` | Format timestamp as string | | `time_bucket(interval, ts)` | Truncate to interval boundary | `time_bucket` accepts the interval as a string in any of these forms: short (`'1s'`, `'5m'`, `'15m'`, `'1h'`, `'6h'`, `'1d'`, `'1w'`), long / Postgres-style (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 hours 30 minutes'`, optionally with an `INTERVAL` prefix), ISO 8601 (`'PT5M'`, `'P1D'`), or a bare integer (milliseconds). ## Type Functions `CAST(expr AS type)`, `TRY_CAST(expr AS type)`, `expr::type` ## ID Generation `gen_uuid_v7()` — time-ordered UUID v7 ## KV Atomic Functions | Function | Description | | -------------------------------------- | ------------------------------ | | `KV_INCR(coll, key, delta [, TTL])` | Atomic increment | | `KV_DECR(coll, key, delta)` | Atomic decrement | | `KV_INCR_FLOAT(coll, key, delta)` | Float increment | | `KV_CAS(coll, key, expected, new)` | Compare-and-swap | | `KV_GETSET(coll, key, new)` | Atomic get-and-set | ## Leaderboard Functions | Function | Description | | --------------------------- | ------------------------ | | `RANK(index, key)` | Player's rank | | `TOPK(index, k)` | Top-k entries (TVF) | | `RANGE(index, min, max)` | Score range query (TVF) | | `SORTED_COUNT(index)` | Total entries | ## Rate Limiting Functions | Function | Description | | ---------------------------------------------- | -------------------------- | | `RATE_CHECK(gate, key, max_count, window_secs)` | Check and consume | | `RATE_REMAINING(gate, key, max_count, window_secs)` | Check remaining budget | | `RATE_RESET(gate, key)` | Reset a cooldown | ## Transfer Functions | Function | Description | | ------------------------------------------------------ | -------------------- | | `TRANSFER(coll, source, dest, field, amount)` | Fungible transfer | | `TRANSFER_ITEM(src_coll, dst_coll, item, src, dst)` | Non-fungible transfer| ## Timeseries Functions `ts_rate`, `ts_delta`, `ts_moving_avg`, `ts_ema`, `ts_interpolate`, `ts_percentile`, `ts_correlate`, `ts_lag`, `ts_lead`, `ts_rank`, `ts_stddev`, `ts_derivative`, `ts_zscore`, `ts_bollinger_upper/lower/mid/width`, `ts_moving_percentile` ## Vector Functions `vector_distance(col, vec)`, `rrf_score(vector_distance, bm25_score [, k1, k2])` ## Full-Text Functions `text_match(col, query)`, `bm25_score(col, query)`, `search_score(col, query)` ## Document Navigation `doc_get(payload, path)`, `doc_exists(payload, path)`, `doc_array_contains(payload, path, value)` ## CRDT Functions `crdt_state(coll, id)`, `crdt_apply(coll, id, delta)` --- # Vector Search Queries (docs/sql/vector-search) --- title: Vector Search Queries description: Nearest neighbor search, filtered vector search, and multi-vector queries. --- # Vector Search Queries ## Nearest Neighbor ```sql SELECT id, vector_distance(embedding, ARRAY[0.1, 0.3, -0.2, ...]) AS dist FROM articles ORDER BY dist LIMIT 10; ``` Returns the 10 nearest neighbors by the metric configured on the index (l2, cosine, inner_product, manhattan, chebyshev, hamming, jaccard, or pearson). The planner detects `ORDER BY vector_distance(...) LIMIT k` and rewrites it into an ANN top-k plan. The `SEARCH()` function is an alias for full-text search; vector search uses `ORDER BY vector_distance(...)` instead. ## Filtered Vector Search ```sql SELECT title, vector_distance(embedding, ARRAY[0.1, 0.3, ...]) AS score FROM articles WHERE category = 'machine-learning' ORDER BY score LIMIT 10; ``` The engine builds a Roaring Bitmap of matching IDs and selects the optimal strategy: pre-filter (selective filters), post-filter (broad filters), or brute-force (very selective). ## Distance Function ```sql SELECT id, vector_distance(embedding, $query_vec) AS dist FROM articles ORDER BY dist LIMIT 10; ``` ### Operator Forms | Operator | Function | Metric | | -------- | ------------------------------ | ----------------------- | | `<->` | `vector_distance` | L2 | | `<=>` | `vector_cosine_distance` | Cosine | | `<#>` | `vector_neg_inner_product` | Negative inner product | ```sql SELECT id FROM articles ORDER BY embedding <=> $query_vec LIMIT 10; ``` ### ANN Tuning (Named Arguments) `vector_distance` and its cosine / inner-product peers accept named tuning arguments via `=>`. JSON-string options are not accepted — every option is a typed, closed-set named argument: ```sql SELECT id, vector_distance( embedding, $query_vec, quantization => 'rabitq', oversample => 4, ef_search => 128, target_recall => 0.95 ) AS dist FROM articles ORDER BY dist LIMIT 10; ``` | Argument | Type | Notes | | ------------------- | ------- | ------------------------------------------------------------------------------------- | | `quantization` | string | `none`, `sq8`, `pq`, `binary`, `ternary`, `rabitq`, `bbq`, `opq` | | `oversample` | u8 | Candidates fetched before re-ranking. Default `3`. Final rerank set is `oversample × ef_search`. | | `query_dim` | u32 | Coarse-to-fine on first-N dims of Matryoshka embeddings. `None` = full dimensionality. | | `meta_token_budget` | u8 | MetaEmbed multivec scoring budget for MaxSim / PLAID | | `ef_search` | u32 | HNSW / Vamana search-time beam width. Default `64`. | | `target_recall` | f32 | Adaptive recall target. The cost-model planner picks oversample / ef_search to hit this. | Unknown names, duplicate keys, positional 3rd args, or wrong operators (`=` instead of `=>`) all return typed errors that list the canonical names. ### Quantization Choice | Codec | Bits/dim | Recall (typ.) | When to pick it | | --------- | -------- | ------------- | -------------------------------------------------------------- | | `none` | 32 | 100% | Small index (< 1M vectors), latency not critical | | `sq8` | 8 | ~99% | Balanced default for medium index sizes | | `pq` | ~2 | ~95% | Large memory-bound indexes; classic Product Quantization | | `opq` | ~2 | ~96% | PQ + learned random rotation; minor accuracy bump over `pq` | | `rabitq` | 1 | ~97% | Frontier 1-bit with `O(1/√D)` error bound (SIGMOD 2024) | | `bbq` | 1 | ~98% | Centroid-asymmetric 1-bit + 14-byte corrective; oversample-rerank | | `binary` | 1 | ~85% | Hamming-only, no rerank — for ultra-cold tiers | | `ternary` | 1.58 | ~96% | BitNet-style `{-1, 0, +1}` — cold/hot pack for AVX-512 | The cost-model planner (`target_recall`) will pick `oversample` and `ef_search` automatically once you set the recall target. Manually set those two only when you need a hard latency ceiling. ## Index Implementations You don't pick the underlying index directly — it's chosen by the planner from collection metadata + workload signals: - **HNSW** — in-memory hierarchical graph, the default for moderate-size indexes - **Vamana / DiskANN** — flat-beam SSD-resident graph for billion-scale on a single node (`Tier 2` of the vector frontier) - **NaviX adaptive-local filtered traversal** (VLDB 2025) — switches per-hop between standard / directed / blind heuristics based on local selectivity. Replaces classic ACORN-1 filtered ANN. - **SIEVE workload-driven subindex collections** — the planner builds specialized HNSW subindices for stable predicates (e.g. `tenant_id`) and routes filtered queries to them. - **MetaEmbed multi-vector + ColBERT MaxSim + PLAID** (ICLR 2026) — learnable Meta Tokens replace per-token explosion; budgeted MaxSim at query time via `meta_token_budget`. - **Matryoshka adaptive-dim querying** — coarse-to-fine ranking on the first-N dimensions of MRL embeddings via `query_dim`. - **SPFresh streaming updates** (SOSP 2023) — LIRE topology-aware local rebalancing; no full-rebuild stalls when vectors are added/removed. ## Vector-Primary Collections By default, vectors are an *index* attached to a column on a normal collection — the document/strict store is the source of truth, and the vector index is a side path. For pure-vector workloads (RAG corpora, recommendation memory, embedding stores) you can flip a collection into **vector-primary** mode, where the vector index becomes the primary access path and the document store is a metadata sidecar: ```sql CREATE COLLECTION corpus ( id UUID DEFAULT gen_uuid_v7(), embedding FLOAT[384], title TEXT, tenant_id UUID, created_at TIMESTAMP DEFAULT now() ) WITH ( engine='vector', vector_field='embedding', dim=384, metric='cosine', storage_dtype='bf16', quantization='rabitq', m=32, ef_construction=200, payload_indexes=['tenant_id', 'created_at'] ); ``` | Option | Notes | | ----------------- | -------------------------------------------------------------------- | | `engine` | `'vector'` selects vector-primary mode and implies `primary='vector'`. | | `vector_field` | Required. Column name of the embedding. | | `dim` | Required. Embedding dimensionality. | | `metric` | `'cosine'`, `'l2'`, `'inner_product'`, etc. | | `storage_dtype` | Raw HNSW storage precision: `'F32'` (4 B/dim, default), `'F16'` (2 B/dim), `'BF16'` (2 B/dim bfloat16, better dynamic range, preferred for embeddings). | | `quantization` | Storage-level codec (same vocabulary as the query-time arg above). | | `m`, `ef_construction` | HNSW build-time parameters. | | `payload_indexes` | Per-field equality / range / boolean indexes over the metadata sidecar for filtered ANN. Replaces Pinecone metadata filters. | In vector-primary mode the planner treats the vector index as the source of truth for IDs; metadata fetches only happen for hit IDs. Cross-engine queries, CRDT sync, and SQL semantics all keep working. `engine='vector'` implies `primary='vector'`. It requires `vector_field` and `dim`, and a missing one is refused with SQLSTATE `42601`. `engine='vector'` with a different `primary` is a contradiction and is refused the same way. `DESCRIBE` reports the collection's engine as `vector`. Default `primary='document'` is unchanged: the existing `CREATE VECTOR INDEX ON ...` syntax continues to work for vector-as-side-index workloads. A document collection searched through a vector index uses `engine='document_schemaless'`, never `engine='vector'`. ## Hybrid Vector + Text (RRF) ```sql SELECT title, rrf_score( vector_distance(embedding, $query_vec), bm25_score(body, 'transformer attention') ) AS score FROM articles LIMIT 10; ``` Reciprocal Rank Fusion merges BM25 text results with vector similarity in a single pass. ## Multiple vector columns per collection A collection can carry several vector indexes, one per embedding column — name the column in parentheses after the collection. Each index gets its own metric and parameters; queries pick the column they search: ```sql CREATE VECTOR INDEX idx_text ON products (text_embedding) METRIC cosine DIM 384; CREATE VECTOR INDEX idx_image ON products (image_embedding) METRIC cosine DIM 512; -- Search the text-embedding index: SELECT id FROM products ORDER BY text_embedding <=> $text_vec LIMIT 10; -- ...or the image-embedding index: SELECT id FROM products ORDER BY image_embedding <-> $image_vec LIMIT 10; ``` Omitting `()` targets the collection's default (unnamed) vector field — fine when there's only one embedding column (as in the `CREATE VECTOR INDEX idx_embed ON articles ...` examples above). --- # Full-Text Search Queries (docs/sql/fulltext-search) --- title: Full-Text Search Queries description: BM25 text matching, fuzzy search, highlighting, and synonyms in SQL. --- # Full-Text Search Queries ## Basic Search ```sql SELECT title, bm25_score(body, 'distributed database rust') AS score FROM articles WHERE text_match(body, 'distributed database rust') ORDER BY score DESC LIMIT 20; ``` ## Fuzzy Search ```sql SELECT title FROM articles WHERE text_match(title, 'databse', { fuzzy: true, distance: 2 }); ``` ## CJK Search CJK text is automatically tokenized via character bigrams: ```sql SELECT title FROM articles WHERE text_match(body, '全文検索'); ``` ## NOT Operator Exclude documents that match specific terms using the `NOT` keyword or the `-` prefix (Lucene-style, no space before the term). Both forms require at least one positive term — a query consisting only of negations is rejected. ```sql -- Exclude documents that mention 'python' SELECT title FROM articles WHERE text_match(body, 'rust NOT python'); -- Multiple exclusions SELECT title FROM articles WHERE text_match(body, 'database NOT mysql NOT oracle'); -- Lucene-style dash prefix (equivalent to NOT) SELECT title FROM articles WHERE text_match(body, 'database -mysql -oracle'); ``` Parenthesised NOT groups are not supported. Use flat negations: ```sql -- Not supported: rust NOT (python OR ruby) -- Supported: rust NOT python NOT ruby SELECT title FROM articles WHERE text_match(body, 'rust NOT python NOT ruby'); ``` ## Synonym Groups A synonym group makes the FTS engine treat a set of terms as interchangeable during indexing and querying. When a document contains any term in the group it also matches queries for any other term in the group. ```sql -- Define synonyms CREATE SYNONYM GROUP db_terms AS ('database', 'db', 'datastore'); CREATE SYNONYM GROUP ml_terms AS ('machine learning', 'ml', 'artificial intelligence', 'ai'); -- Now a query for 'db' also matches documents that contain 'database' or 'datastore' SELECT title FROM articles WHERE text_match(body, 'db performance'); ``` ### Managing synonym groups ```sql -- List all groups SHOW SYNONYM GROUPS; -- Drop a group DROP SYNONYM GROUP db_terms; DROP SYNONYM GROUP IF EXISTS ml_terms; ``` Synonym group names are case-insensitive. Terms within a group are stored lowercased. Duplicate terms within the same group are rejected at creation time. ## Hybrid Search (BM25 + Vector) ```sql SELECT title, rrf_score( vector_distance(embedding, $query_vec), bm25_score(body, 'distributed systems') ) AS score FROM articles LIMIT 10; ``` --- # Graph Queries (docs/sql/graph-queries) --- title: Graph Queries description: GRAPH commands, MATCH pattern matching, and algorithm execution in SQL. --- # Graph Queries ## Edge Operations ```sql GRAPH INSERT EDGE IN 'edges' FROM 'alice' TO 'bob' TYPE 'knows' PROPERTIES { since: 2020 }; GRAPH DELETE EDGE IN 'edges' FROM 'alice' TO 'bob' TYPE 'knows'; ``` The `IN ''` clause is **required** — edges are overlays on a named document collection. Statements without `IN` fail to parse. ## Traversal ```sql GRAPH TRAVERSE IN 'edges' FROM 'alice' DEPTH 3; GRAPH TRAVERSE IN 'edges' FROM 'alice' DEPTH 2 LABEL 'follows' DIRECTION out; GRAPH TRAVERSE IN 'edges' FROM 'alice' DEPTH 2 LABEL 'follows', 'knows' DIRECTION out; GRAPH NEIGHBORS IN 'edges' OF 'bob' LABEL 'follows' DIRECTION both; GRAPH PATH IN 'edges' FROM 'alice' TO 'charlie' MAX_DEPTH 5 LABEL 'knows', 'works_with'; GRAPH TRAVERSE IN 'edges' FROM 'alice' DEPTH 2 LABEL 'follows' EDGE WHERE since >= 2020 AND active = TRUE; GRAPH PATH IN 'roads' FROM 'a' TO 'z' MAX_DEPTH 6 EDGE WHERE "kind" IN ('road', 'rail') AND NOT (closed = TRUE); ``` Syntax: ```sql GRAPH TRAVERSE IN '' FROM '' [DEPTH ] [LABEL '