# ChloeDB
> ChloeDB is a search database with SQL: full text (BM25), vectors, graphs and structured fields in tables, embedded in a process (Rust, Python, JavaScript, Java) or served by chloedb-server over HTTP, gRPC and MCP, on one machine or a cluster. Its SQL is its own dialect, not Postgres: MATCH and bm25 for words, similarity for meaning, rrf to fuse them.
An agent connected to a chloedb-server over MCP (`{server}/v1/mcp`) gets these documents through its `search_docs` tool and its prompts. [Build with an AI agent](https://chloetech-ai.github.io/chloedb/guide/agents.md) says how to connect one and the prompts that work. The rendered site is https://chloetech-ai.github.io/chloedb/site/docs/.
---
# ChloeDB documentation
ChloeDB is an embedded search database with SQL: full text, structured columns, vectors and graph edges over the same rows, in one file, combined in one query by one planner. It runs inside your program like SQLite, or as a server and a cluster with the same SQL.
## Where to start
| you are making | start with | then |
|---|---|---|
| a Python app, script or notebook, with the database in your process | [the quickstart's Python section](../quickstart.md#chloedb-from-python-with-no-server) (`pip install chloedb`, no server) | [Python](../chloedb/python.md), the [search guide](search.md), and [Build a search page](search-page.md) for a web app |
| a JavaScript or TypeScript app (Node, Bun, Deno, a framework's server code) | [JavaScript](../chloedb/javascript.md): `npm install chloedb` and a database in your process | the [search guide](search.md), whose queries run as `await db.query(sql, params)` |
| a server that several programs, languages or machines use | [the quickstart](../quickstart.md): install `chloedb-server`, a table, a search, the command center | [chloedb-server](../chloedb/server.md), and [Build an app on chloedb-server](../chloedb/build-an-app.md) for an app over its HTTP API |
| a cluster: shards, replicas, failover | [Operate a cluster](operate-cluster.md), on one machine first | [Runbooks](../chloedb/runbooks.md) and [cluster limits](../chloedb/cluster-limits.md) |
| retrieval for a language model | [Retrieval for RAG](rag.md) | [LangChain, LangGraph, LlamaIndex](frameworks.md) |
| a move from Elasticsearch or OpenSearch | [the OpenSearch API](../chloedb/opensearch.md): `--opensearch-listen` answers OpenSearch's REST API, so an app on an OpenSearch or Elasticsearch 7 client indexes and searches unchanged, and its [differences](../chloedb/opensearch.md#differences) say what it refuses | the [search guide](search.md) for the same searches in SQL, and [multi-tenant isolation](../chloedb/security.md#api-keys-and-scopes) for an index per customer |
| a move from PostgreSQL's SQL | [Differences from PostgreSQL](../chloedb/query-language.md#differences-from-postgresql): what answers otherwise and what is refused, with what to write instead | [Following Postgres](../chloedb/postgres.md) copies a Postgres database in and keeps it current |
| long-term memory for Claude Code | [Install ChloeCtx](../chloectx/setup.md): it plugs into Claude Code, and needs neither chloedb-server nor Python | [ChloeCtx](../chloectx/index.md) |
Something failed? [Troubleshooting](../chloedb/troubleshooting.md) has the usual messages, each with what to do, and `chloedb-server doctor` checks this machine for their causes.
## Cookbook
Complete programs for common jobs. Each one runs, as written, every time the code changes.
## Use it from
| | |
|---|---|
| [Python](../chloedb/python.md) | `import chloedb`: a database in your process, or a client of a server, with the same methods; [DataFrames](../chloedb/frames.md) too |
| [JavaScript](../chloedb/javascript.md) | Node, Bun and Deno in-process, or a `fetch` client for any runtime |
| [Java](../chloedb/java.md) | in-process over JNI, and a JDBC driver |
| [HTTP and gRPC](../chloedb/server.md) | chloedb-server, its command center, and a cluster of them |
## Apps
[Apps on a cluster](apps.md) run beside chloedb-server and show in its command center: the [crawler](../chloedb/crawler.md), [Sheets](../chloedb/sheets.md) and [ChloeCtx](../chloectx/index.md), memory for Claude Code.
## How these pages are tested
The guide and cookbook pages are run as scripts: [`docs/guide/run.py`](run.py) runs every code block on a page, in order, in an empty directory, against the programs built from the same commit, and checks the output shown under a block against what it printed. A page that says so at its top has passed. The reference pages (SQL, server, clients, apps) are rendered from the Markdown in [`docs/chloedb/`](../chloedb/index.md) and [`docs/chloectx/`](../chloectx/index.md).
---
# Quickstart: a first search in five minutes
This page takes you from nothing to a full-text search with SQL in about five minutes, with nothing to compile. You install ChloeDB's server, make a table, put a few rows in it, search them, and open the command center in a browser. The last section does the same from Python, with the database inside your process and no server at all.
You need macOS 11 or later (Apple silicon or Intel), or Linux on x86-64 or aarch64 with glibc 2.35 or later (Ubuntu 22.04, Debian 12 and newer), and `curl`. On Windows, use WSL 2 or Docker.
## In one minute
Two commands: install, then start a server with a demo catalogue of 20,000 products.
```sh
# install
curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh
```
```sh norun
chloedb-server --demo
```
It makes `demo.chloedb` in the current directory and says, once it is ready, where to open it and what to try:
```text
ChloeDB 0.3.11 is ready: demo.chloedb, 1 table (products), 20,000 rows
Open http://127.0.0.1:7700
Query curl -s http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' -d '{"sql": "SELECT * FROM products LIMIT 3"}'
Load a file curl -s 'http://127.0.0.1:7700/v1/import?table=NAME' -H 'content-type: text/csv' --data-binary @FILE.csv
Stop Ctrl+C (the next start opens it as it was)
```
Your own data needs no schema. Drop a CSV, JSON, Parquet or SQLite file on **Import** in the command center, or send it with the `Load a file` line above (`?table=movies` makes the table `movies` from the file's columns), or load it before you start the server:
```sh norun
chloedb-server import movies.csv --db movies.chloedb # makes the table movies from the file's columns
chloedb-server --db movies.chloedb
```
`chloedb-server` with no `--db` serves `chloedb.chloedb` in the current directory, made empty on the first start. The rest of this page goes step by step, with the choices each step has.
## 1. Install the server
Pick one. Each gives you a `chloedb-server` program, prebuilt (a download of about 50 MB), in under a minute.
**The install script** puts it in `~/.local/bin` (it says what to add to your `PATH` if that folder is not on it yet). It checks the download against the release's SHA-256 and, where [GitHub's CLI](https://cli.github.com) (`gh`) is installed, its provenance (from 0.3.8 to 0.3.10, that this repository's release workflow built it; from 0.3.11, that the public copy of the releases published it, as [SECURITY.md](../SECURITY.md#checking-what-you-download) explains), and changes nothing else. [Read it](install.sh) first if you like.
```sh
# install
curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh
```
If it stops behind a proxy or a firewall, or names no version, [Troubleshooting](chloedb/troubleshooting.md#the-install-script-stops-could-not-tell-which-chloedb-server-release-is-the-newest) says what to do: in short, name the version after the pipe, `curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION=0.3.11 sh`.
**pipx, uv or pip** : the same server, from [PyPI](https://pypi.org/project/chloedb-server/), which asks GitHub nothing, on the same Macs and on Linux with glibc 2.34 or later. `pipx install` and `uv tool install` put `chloedb-server` on your `PATH`; `uvx chloedb-server` runs it without installing it.
```sh
# install
pipx install chloedb-server # or: uv tool install chloedb-server
```
In a virtualenv, pip puts it in the virtualenv's `bin`, on your `PATH` while the virtualenv is active; `"chloedb[server]"` installs the Python package beside it, for the last section of this page:
```sh
# install
python3 -m venv .venv && . .venv/bin/activate
pip install chloedb-server # or: pip install "chloedb[server]"
```
**Homebrew** is not available yet: there is no tap to install from. Use the install script above, which works on the same Macs and Linux machines.
**Docker**: skip to [ChloeDB in Docker](#chloedb-in-docker) below, which runs the same steps against the image.
**By hand**: each `chloedb-server-v` [release](https://github.com/chloetech-ai/chloedb-releases/releases) has an archive per platform (`linux-x86_64`, `linux-aarch64`, `macos-arm64`, `macos-x86_64`) with a `.sha256` beside it:
```sh
# install
v=0.3.11 p=macos-arm64
curl -fLO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz
tar xzf chloedb-server-$p.tar.gz && mkdir -p ~/.local/bin && mv chloedb-server-$p/chloedb-server ~/.local/bin/
```
From 0.3.8 each archive also has GitHub's build provenance and an SBOM of what is compiled into it: [checking what you download](../SECURITY.md#checking-what-you-download) shows the `gh attestation verify` command that checks them (the install script runs it for you where `gh` is installed).
Check that it runs:
```sh
chloedb-server --version
```
If it does not, or a later step stops with an error, [Troubleshooting](chloedb/troubleshooting.md) has the usual messages and what to do; `chloedb-server doctor` checks this machine for their causes.
## 2. Start it
A database is a file, with its write-ahead log and the server's own logs beside it (`quickstart.chloedb-wal`, `quickstart.chloedb.logs`). Give the server a path that does not exist yet and it creates an empty database there; it listens on `127.0.0.1:7700`, which only this machine can reach.
```sh
mkdir -p chloedb-quickstart && cd chloedb-quickstart
chloedb-server --db quickstart.chloedb > server.log 2>&1 &
server=$!
until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done
```
For a server you keep, rather than this try, add two flags. `--alerts alerts.json` keeps the alert rules and routes you make in that file: without it a server on its own keeps them in memory, and a restart loses them ([alerts](chloedb/server.md#alerts)). `--environment production` (or `staging`, `dev`) names what it is: the command center shows it in its header and, on production, asks for a reason before each change. A server with none is shown as a sandbox when you reach it on this machine, and as production from another.
Everything below talks to it over HTTP with JSON. To keep the commands short, `sql` sends the statement it reads from its input to `POST /v1/sql`, which runs any statement:
```sh
sql() { curl -sS http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' --data-binary @-; echo; }
```
## 3. Make a table and fill it
Every column is indexed for what its type is for: `TEXT` for full-text search (words stemmed, so "jackets" finds "jacket"), `KEYWORD` for exact values and facets, numbers for ranges and sorting.
```sh
sql <<'EOF'
{"sql": "CREATE TABLE products (id KEYWORD PRIMARY KEY, title TEXT, body TEXT, category KEYWORD, price FLOAT)"}
EOF
```
Rows go in with SQL (`INSERT INTO products VALUES (...)`), from files (`chloedb-server import`), or as JSON documents to `POST /v1/write`:
```sh
curl -sS http://127.0.0.1:7700/v1/write -H 'content-type: application/json' --data-binary @- <<'EOF'
{"ops": [
{"op": "upsert", "table": "products", "doc": {"id": "p1", "title": "Waterproof hiking jacket", "body": "A light shell that keeps rain out on long hikes.", "category": "outdoor", "price": 129.0}},
{"op": "upsert", "table": "products", "doc": {"id": "p2", "title": "Insulated winter jacket", "body": "Warm down jacket for cold city winters.", "category": "outdoor", "price": 189.0}},
{"op": "upsert", "table": "products", "doc": {"id": "p3", "title": "Trail running shoes", "body": "Grippy, waterproof shoes for muddy trails.", "category": "footwear", "price": 99.0}},
{"op": "upsert", "table": "products", "doc": {"id": "p4", "title": "Leather office shoes", "body": "Classic shoes for the office.", "category": "footwear", "price": 149.0}},
{"op": "upsert", "table": "products", "doc": {"id": "p5", "title": "Rain cover for backpacks", "body": "Waterproof cover that fits 20 to 40 litre packs.", "category": "outdoor", "price": 19.0}}
]}
EOF
echo
sql <<'EOF'
{"sql": "INSERT INTO products (id, title, body, category, price) VALUES ('p6', 'Wool hiking socks', 'Warm socks that dry fast on wet hikes.', 'footwear', 15.0)"}
EOF
```
Each answer says how many rows it wrote (`"written"`), and the rows are durable once it returns.
## 4. Search
The rows that mention "waterproof", best match first. `MATCH` finds them, `bm25` ranks them:
```sh
sql <<'EOF'
{"sql": "SELECT id, title, score() FROM products WHERE MATCH(body, 'waterproof') ORDER BY bm25(body, 'waterproof') DESC LIMIT 5"}
EOF
```
The answer's `rows` are the matches, in the order of its `columns` (`"objects": true` beside `"sql"` gives each row as an object instead); `stats` says how the planner ran the statement, step by step.
Full text and structured filters in one statement, which the planner runs together: waterproof things under 100 that are not shoes.
```sh
sql <<'EOF'
{"sql": "SELECT id, title, price FROM products WHERE MATCH(body, 'waterproof') AND price < 100 AND category <> 'footwear'"}
EOF
```
Typos are forgiven when you ask: `fuzzy => 1` lets each word be one edit away, so "jaket" finds the jackets.
```sh
sql <<'EOF'
{"sql": "SELECT id, title FROM products ORDER BY bm25(title, 'jaket', fuzzy => 1) DESC LIMIT 3"}
EOF
```
Facets are a `GROUP BY` over the matches:
```sh
sql <<'EOF'
{"sql": "SELECT category, COUNT(*), AVG(price) FROM products WHERE MATCH(body, 'waterproof OR warm') GROUP BY category ORDER BY 2 DESC"}
EOF
```
## 5. Open the command center
Open [http://127.0.0.1:7700](http://127.0.0.1:7700) in a browser. The command center opens on **Start here**, which walks through the first steps and ticks each one off once it is done; once they are, the same address opens **Home**, the server's health. If the crawler, Sheets or ChloeCtx were installed beside `chloedb-server` (`install.sh --with`), the server started them too, as [apps](chloedb/server.md#apps-the-server-starts) (unless it was given `--start-apps off`), and their tables (`crawl_*`, `sheets_*`, `ctx_*`) are listed apart from yours, under Tables of apps. **Tables** lists `products`: its page searches it from one box (by words, by meaning, or both), shows its rows, how full each field is, and what uses it, and **Save as a saved search** keeps the query as a stored function that SQL, HTTP, Python, JavaScript and agents (over MCP) all call. The **SQL workbench** runs any SQL you type and shows the plan the planner chose; **Ask** (Ctrl+J) answers a question in words by querying the tables, with an Anthropic API key (the server's, or one you give the tab). The older query console is still at [/classic](http://127.0.0.1:7700/classic). With `--demo 20000`, a new database starts with a catalogue of 20,000 products to try it on; here a second server, on port 7710, so that both run at once:
```sh
chloedb-server --db demo.chloedb --demo 20000 --listen 127.0.0.1:7710 --grpc off > demo.log 2>&1 &
demo=$!
until curl -sf http://127.0.0.1:7710/livez > /dev/null; do sleep 0.2; done
curl -sS http://127.0.0.1:7710/v1/sql -H 'content-type: application/json' \
-d "{\"sql\": \"SELECT title, price FROM products WHERE MATCH(body, 'waterproof jacket') ORDER BY bm25(body, 'waterproof jacket') DESC LIMIT 5\"}"; echo
```
When you are done, stop the servers (the databases stay in their files, and the next start opens them as they were):
```sh
kill $server $demo
```
## ChloeDB from Python, with no server
The Python package runs a database inside your process, the way `sqlite3` runs SQLite. It is a prebuilt wheel for CPython 3.10 and later on the same platforms as the server: macOS 11 or later, and Linux with glibc 2.28 or later (release 0.2.0's wheels need 2.35). Install it from PyPI:
```sh
# install
python3 -m venv .venv && . .venv/bin/activate
pip install chloedb
```
```sh
python3 - <<'EOF'
import chloedb
db = chloedb.open("books.chloedb", schema={
"table": "books", "key": "id",
"fields": [
{"name": "id", "type": "keyword"},
{"name": "title", "type": "text"},
{"name": "year", "type": "int"},
],
})
db.upsert([
{"id": "b1", "title": "The river and the dragon", "year": 1999},
{"id": "b2", "title": "Winter garden", "year": 2005},
{"id": "b3", "title": "Dragons of the northern rivers", "year": 2011},
])
print(db.query("SELECT id, title FROM books WHERE MATCH(title, 'dragon') AND year > 2000").rows)
# a typo, forgiven: each word may be an edit or two away, by its length
print(db.query("SELECT id, title FROM books WHERE MATCH(title, :q, fuzzy => 'auto') "
"ORDER BY bm25(title, :q) DESC", q="dragn").rows)
db.close()
EOF
```
```text output
[['b3', 'Dragons of the northern rivers']]
[['b1', 'The river and the dragon'], ['b3', 'Dragons of the northern rivers']]
```
`chloedb.open` creates the database the first time and opens it after; one process at a time may open it to write. A schema with an embedded vector field that names a model ChloeDB knows (`"embed": {"from": ["title"], "model": "potion-retrieval-32M"}`) works on a new machine as written: the first open downloads the model once (about 130 MB, each file checked against its pinned SHA-256) and says so; `CHLOEDB_FETCH_MODELS=0` turns that off. The same methods talk to a server: `chloedb.connect("http://127.0.0.1:7700")` in place of `chloedb.open(...)`. [Python](chloedb/python.md) goes on from here, and [Build a search page](guide/search-page.md) makes a search box with typos, highlights and filters from these pieces.
## ChloeDB in Docker
The image `ghcr.io/chloetech-ai/chloedb-server` (Linux, x86-64 and arm64) keeps its database in `/data`: mount a volume there to keep it. Inside a container the server listens on all of the container's interfaces, which it allows only with a token, so pick one. Publishing the port on `127.0.0.1` keeps it to this machine.
```sh
# install
docker run -d --name chloedb --user 10001:10001 -p 127.0.0.1:7700:7700 -e CHLOEDB_TOKEN=pick-a-secret -v chloedb:/data \
ghcr.io/chloetech-ai/chloedb-server:0.3.11
```
Then every request sends the token, and the console asks for it once:
```sh
sql() { curl -sS http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' -H 'authorization: Bearer pick-a-secret' --data-binary @-; echo; }
```
and steps 3 to 5 run as written (the `/v1/write` call needs the same `authorization` header). Arguments after the image replace its default ones (`--db /data/chloedb.chloedb --listen 0.0.0.0:7700 --grpc 0.0.0.0:7701`): add `--demo 20000` by passing `--db /data/demo.chloedb --listen 0.0.0.0:7700 --demo 20000`. For [OpenSearch's API](chloedb/opensearch.md) too, publish its port and give the defaults again with it: `-p 127.0.0.1:9200:9200` before the image, and `--db /data/chloedb.chloedb --listen 0.0.0.0:7700 --opensearch-listen 0.0.0.0:9200` after it (the token is its password, with any user name). `docker rm -f chloedb` stops it; the volume keeps the database.
## Next
- [The query language](chloedb/query-language.md): every function, with vectors (`similarity`), hybrid ranking, graph traversal, joins and aggregates.
- [The server](chloedb/server.md): loading files (`chloedb-server import`), schemas, embedded vector fields, API keys, replication and shards.
- [Python](chloedb/python.md), [JavaScript](chloedb/javascript.md) and [Java](chloedb/java.md): the database in your process.
- [SQLite](chloedb/sqlite.md), [Parquet and S3](chloedb/parquet.md) and [Postgres](chloedb/postgres.md): bring your data in.
---
# Build with an AI agent
An agent such as Claude Code can do most of what this documentation describes for you. It can load a file, make it searchable by words and by meaning, answer questions from your rows with citations, write the search page or the code of your app, find out why a query is slow, and look after a server. This page shows how to connect one, the prompts that work, and what a good agent does with each, so you can tell when it goes wrong. The server gives your agent the same prompts as slash commands, and the documentation it needs as a tool.
## Connect your agent
Start a server, if one is not running yet. With no flags it serves `chloedb.chloedb` in the current directory, at `http://127.0.0.1:7700`:
```sh
chloedb-server > server.log 2>&1 &
until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done
```
Then add it to your agent as an MCP server. For Claude Code:
```sh norun
claude mcp add --transport http chloedb http://127.0.0.1:7700/v1/mcp
```
A server with a token needs a key in the header: `--header "Authorization: Bearer $CHLOEDB_KEY"`. A client that starts its MCP servers as commands (Claude Desktop, Cursor and most others) runs `chloedb-server mcp`, which passes each message on to the server:
```json norun
{
"mcpServers": {
"chloedb": {
"command": "chloedb-server",
"args": ["mcp", "--url", "http://127.0.0.1:7700"],
"env": {"CHLOEDB_KEY": "your key, or leave it out for a server without a token"}
}
}
}
```
What the agent can change is decided by the key it connects with, not by what you ask it: a read key explores, a write key loads rows, and an admin key also makes tables ([agents over MCP](../chloedb/server.md#agents-over-mcp)). Even with an admin key, an agent cannot drop a table or delete every row on its own. The server refuses, and the agent files the change for you to approve ([agents and administration](../chloedb/server.md#agents-and-administration)).
The server tells a connected agent the prompts below. In Claude Code they are slash commands, such as `/mcp__chloedb__load-a-file data/movies.csv`, each with the steps listed under it. You can also list them yourself:
```sh
curl -s http://127.0.0.1:7700/v1/mcp -H 'content-type: application/json' \
-d '{"jsonrpc": "2.0", "id": 1, "method": "prompts/list"}' \
| python3 -c 'import json, sys; print("\n".join(p["name"] for p in json.load(sys.stdin)["result"]["prompts"]))'
```
```text output
explore
load-a-file
search
answer-with-citations
search-page
app-code
change-a-table
slow-query
check-the-server
```
## Prompts that work
Each prompt below is written as you would type it. Under it is what a good agent does, and the server sends those steps along when you use the slash command. Words in braces, such as `{path}`, are yours to fill in.
### Explore what is there
```text prompt=explore
Look at what is in my ChloeDB and tell me what I could search for, with an example query for each table.
```
1. `whoami` says what the key may do, and `list_tables` gives each table's `CREATE TABLE` statement, its key, its vector fields and their models.
2. A few rows of each table (`SELECT * FROM t LIMIT 3`), and the values of its `KEYWORD` fields (`SELECT genre, COUNT(*) FROM t GROUP BY genre`).
3. For each table, a search by its words (`MATCH` and `bm25` over its `TEXT` fields) and, when it has an embedded `VECTOR` field, one by meaning (`similarity`), each run once so the example is known to work.
4. ChloeDB's SQL is its own dialect, not Postgres. Before writing anything unusual, the agent looks up the syntax with `search_docs` and checks the statement with `check_sql`.
### Load a file and search it by meaning
```text prompt=load-a-file
Load {path} into ChloeDB as a table I can search by words and by meaning.
```
1. It looks at the file's first lines and its size, and names the table after the file unless you said otherwise.
2. A file of up to a few megabytes goes through the `import` tool, its text as `data`, with `create: true`. The table is made from the file's columns: numbers become `INT` or `FLOAT`, short labels `KEYWORD`, and prose `TEXT`. A cell that says it has no value (`N/A`, `null`, `-`) in a column of numbers or dates is `NULL`, so nothing needs cleaning first. A table with prose also gets `emb`, a vector of that prose by `potion-retrieval-32M`, which the server downloads once (about 130 MB) and fills in. The answer's `create_table` is the statement it made.
3. A larger file is sent from the shell instead, which needs an admin key on a server with a token: `curl -s --data-binary @{path} -H 'content-type: text/csv' 'http://127.0.0.1:7700/v1/import?table=NAME'`. The content type is `text/tab-separated-values` for TSV and `application/x-ndjson` for JSON Lines. With the server stopped, `chloedb-server import {path} --db chloedb.chloedb` does the same ([loading rows](../chloedb/server.md#loading-rows)).
4. Search by meaning works once the model has arrived. Until then such a query answers 503 `unavailable`, saying how far the download is, or, when it failed, when the server tries again by itself. The agent waits, and `list_models` shows the download, rather than fetching the model itself. Search by words works at once.
5. It ends with one search by words and one by meaning, so you see the table work.
### Search, and say why each row matched
```text prompt=search
Search the {table} table for "{question}", by meaning and by words together, and tell me why each result matched.
```
1. Words and meaning fused: `SELECT ... FROM {table} ORDER BY rrf(bm25(body, :q, fuzzy => 'auto'), similarity(emb, :q)) DESC LIMIT 10`, with `:q` the text itself, which the server embeds with the field's own model. `body` stands for the table's `TEXT` fields, and `emb` for its vector field (`list_tables` names both).
2. `fuzzy => 'auto'` takes typos: a word in no row is read as the words near it.
3. A condition on structured fields goes in `WHERE` (`genre = 'scifi' AND year > 2000`), not in the text.
4. To say why a row matched, the agent runs `explain` with `hits`, which gives each top row's scores, or compares the row's words with the question's ([ranking](../chloedb/query-language.md#rrfs1-s2--reciprocal-rank-fusion)).
5. `MATCH(field, 'a b c')` keeps only rows with every word. When it finds nothing, the answer's `hint` suggests `OR` or `min => 2`.
### Answer a question from my rows, with citations
```text prompt=answer-with-citations
Answer this from the rows in my ChloeDB, citing the rows each claim comes from: {question}
```
1. It finds the rows as in the search above, eight or so, with their keys.
2. It answers from those rows only, marking each claim with its row as `[1]`, `[2]`, and lists the rows cited with their keys. When the rows do not answer the question, it says so rather than answering from what it knows.
3. In your own code, Python's `db.ask(question, table=...)` does the same in one call. It returns the answer with its `sources`, written by a language model through the query's `llm()`, with `ANTHROPIC_API_KEY` ([Python](../chloedb/python.md#querying)). A whole pipeline, with documents split into chunks and grounded claims, is in [Retrieval for RAG](rag.md).
### Build a search page
```text prompt=search-page
Build me a search page for the {table} table: a search box that forgives typos and finds things by meaning, with filters, that I open in my browser.
```
1. **The page cannot call chloedb-server from the browser.** The server refuses requests from a page on another origin, a page opened from a file included, and sends no CORS headers. A page written to `fetch` the server's `/v1/query` therefore fails with a CORS error. The page calls a small app instead, and the app calls the server ([why](../chloedb/javascript.md#why-a-page-cannot-call-chloedb-server)).
2. The app can be Python's standard library and `chloedb` (`pip install chloedb`): `chloedb.connect("http://127.0.0.1:7700")` and an `http.server` handler that serves the page and answers `/search?q=` with `db.search(q, table="{table}", where=..., limit=20)`. `db.search` fuses words and meaning and forgives typos. [Build a search page](search-page.md) is that app in full, with highlights, "did you mean", filters with counts, and "more like this".
3. In a JavaScript app, the route does the same with the `chloedb` package's client ([a search box in a web app](../chloedb/javascript.md#a-search-box-in-a-web-app)).
4. Filters come from the table's `KEYWORD` fields, with their counts (`SELECT genre, COUNT(*) FROM {table} WHERE MATCH(...) GROUP BY genre`).
5. It starts the app, opens the page (or fetches it with `curl`), runs a search with a typo in it, and gives you the address.
### Write the code of my app
```text prompt=app-code
Write {language} code that uses ChloeDB to {task}.
```
1. It chooses between the database in the app's own process (`chloedb.open(path)` in Python, `open()` in JavaScript, `Db` in Rust) and a client of a running server (`chloedb.connect(url)`). It uses the server when more than one process uses the data, or when the command center should show it.
2. It looks up the client's methods in that language's page, and does not guess them from other databases: [Python](../chloedb/python.md), [JavaScript](../chloedb/javascript.md), [Rust](../chloedb/rust.md), [Java](../chloedb/java.md).
3. Queries take named parameters (`:q`) bound in a mapping, never values pasted into the SQL.
4. It runs the code once against a real database and shows what it printed.
### Change a table
```text prompt=change-a-table
In ChloeDB, change the {table} table: {change}.
```
1. It reads the table's statement (`describe_table`) and finds the syntax with `search_docs` (`ALTER TABLE ... ADD`, a field's options, an embedded field).
2. It checks the statement with `check_sql` before running it with `execute`. An added field fills in for the rows already there, and an embedded vector field computes its vectors in the background.
3. It does not drop a table or a field, or delete or update every row, on its own: the server refuses an agent that tries (`change_request_required`). It asks you, or files the change for an admin to approve with `propose_change`.
### Find out why a query is slow
```text prompt=slow-query
This ChloeDB query is slow. Find out why and make it faster: {sql}
```
1. `explain` shows how the query runs: the plan of each segment, the rows a filter kept, and whether ranking stopped early (`MaxScore`). `queries` shows the latest and slowest statements, with their times.
2. The usual cause is a condition the indexes cannot answer, which tests every row the other conditions keep: a function or arithmetic of a column (`lower(brand) = 'acme'`), a `LIKE '%tent%'` or an `ILIKE` on a field without a substring index, or a comparison of a `TEXT` field's stored text ([statement shape](../chloedb/query-language.md#statement-shape)). Others are a ranking by an expression that every row must compute, and a `LIMIT` much larger than the page shows.
3. It changes one thing at a time, and times the query before and after with the same parameters.
### Check the server
```text prompt=check-the-server
Check my ChloeDB server's health and tell me what needs attention, and what to do about each thing.
```
1. `health`, `alerts` and `events` (with an admin, `ops` or `propose` key) say how the server is and what has changed.
2. For each problem, `runbook` finds what to do.
3. It acts only within what its key allows alone: a contain rule, a cancelled query, an alert silenced for a while, each with a reason. Anything bigger it files with `propose_change` for a person to approve ([agents and administration](../chloedb/server.md#agents-and-administration)).
## What every agent should know
The server tells a connected agent these at the start. They are written here for an agent that reads this page instead.
- **The SQL is ChloeDB's own.** `MATCH(field, 'words')` filters by text, `ORDER BY bm25(field, 'words') DESC` ranks by it, `similarity(emb, :q)` ranks by meaning, and `rrf(...)` fuses rankings. `search_docs` finds the syntax of anything else in the [SQL reference](../chloedb/query-language.md), and `check_sql` checks a statement without running it.
- **Errors say what to do.** Every error has a stable `error_code`, whether trying again can work (`retryable`), a `hint`, and the documentation section that explains it (`docs`). A retryable error is waited out, not worked around ([error codes](../chloedb/server.md#agents-and-administration)).
- **Meaning comes by itself.** A table made from a file with prose gets a vector of it, which the server fills in once its model has downloaded. Nothing needs to be fetched or configured by hand.
- **Pages call an app, not the server.** See [Build a search page](#build-a-search-page) above.
- **Writes are safe to send again with a key.** A write through a coordinator that answers `write_in_doubt` is sent again with the answer's `idempotency_key` ([failover](../chloedb/server.md#failover)).
- **Ask before anything that loses data.** The server holds such a change for a person anyway.
## Tell your coding agent about ChloeDB
A coding agent working on your app, with no MCP server, reads the documentation as text:
- [llms.txt](https://chloetech-ai.github.io/chloedb/llms.txt) lists every page with a line on what it covers.
- [llms-full.txt](https://chloetech-ai.github.io/chloedb/llms-full.txt) is the whole documentation in one file.
For a project that uses ChloeDB, a few lines in its `CLAUDE.md` or `AGENTS.md` keep the agent on the right path:
```text norun
This project uses ChloeDB (https://chloetech-ai.github.io/chloedb/llms.txt), a search database
with its own SQL dialect, not Postgres: MATCH and bm25 for words, similarity for meaning, rrf to
fuse them. Look up syntax in its SQL reference rather than guessing. The server runs at
http://127.0.0.1:7700 (MCP: /v1/mcp). Browser pages call our app's routes, never the server.
```
---
# Concepts
ChloeDB is a search engine and a database in one library. This page names the parts you meet when you use it: the file, tables and their fields, the three kinds of index every row gets, scores, the planner, and the server that serves the same database to many clients or many machines. [How ChloeDB works](../chloedb/index.md) goes deeper into each.
## One database, one file
A database is one file plus a write-ahead log beside it (`books.chloedb` and `books.chloedb-wal`), the way SQLite keeps one in WAL mode, and a small directory (`-readers`) where processes that read it keep their place. Your program opens it as a library, from Rust, [Python](../chloedb/python.md), [JavaScript](../chloedb/javascript.md) or [Java](../chloedb/java.md), with no server and no configuration. The same file can be served by [chloedb-server](../chloedb/server.md) when many clients, or many machines, need it.
```python
import os
import chloedb
db = chloedb.open("notes.chloedb", schema={
"table": "notes", "key": "id",
"fields": [{"name": "id", "type": "keyword"}, {"name": "body", "type": "text"}],
})
db.insert({"id": "n1", "body": "Water the tomatoes before nine."})
print(sorted(f for f in os.listdir(".") if f.startswith("notes")))
db.close()
print(sorted(f for f in os.listdir(".") if f.startswith("notes")))
```
```text output
['notes.chloedb', 'notes.chloedb-readers', 'notes.chloedb-wal']
['notes.chloedb', 'notes.chloedb-readers', 'notes.chloedb-wal']
```
Writes are transactions with snapshot isolation: a query sees the database as it was when it started, readers never wait for the writer, and a crash leaves the last committed state. One process writes a database at a time; other processes can open it read-only and follow its commits. Back up a database that is in use with `checkpoint`, not by copying its files ([backups](../chloedb/python.md#backing-up-and-damaged-files)).
## Tables, fields and keys
A database holds tables, and a table has typed fields and, usually, a primary key. A table is created from a schema, a JSON object as above or SQL:
```sql norun
CREATE TABLE books (
id KEYWORD PRIMARY KEY,
title TEXT,
author KEYWORD,
genres KEYWORD[],
year INT,
rating FLOAT,
emb VECTOR OPTIONS(embed = 'title', model = 'potion-retrieval-32M')
);
```
| type | holds | searched with |
|---|---|---|
| `TEXT` | words, analysed (lowercased, stemmed, stopwords dropped) | `MATCH`, `bm25` |
| `KEYWORD`, `KEYWORD[]` | exact values: ids, tags, names | `=`, `IN`, `LIKE 'p%'`, `GROUP BY` |
| `INT`, `FLOAT`, `BOOL`, `TIMESTAMP` | numbers, flags and times | ranges, `ORDER BY`, aggregates |
| `JSON` | documents whose keys no schema names | `attrs.color = 'red'` |
| `VECTOR` | embeddings, given or computed by a model | `similarity`, `distance` |
| `SPARSE` | learned term weights (SPLADE and the like) | `similarity` |
| `EDGES` | typed, weighted links to other rows | `REACHABLE`, `PATH`, `ppr` |
| `MEDIA` | images and sounds, by URI | the vectors and text made from them |
A vector field with `embed` is filled by an embedding model from other fields when a row is written, so you insert text and search by meaning. The model runs inside ChloeDB or behind an API (OpenAI, Cohere, Voyage, Gemini, Ollama). Inside it, every build runs `potion-retrieval-32M`, a fast static model; BERT models such as `bge-small-en-v1.5` run only in a build from source with the `bert` feature, which the prebuilt server, wheels, npm package and Docker image leave out ([a BERT model does not run](../chloedb/troubleshooting.md#a-bert-model-such-as-bge-small-does-not-run)). The [SQL reference](../chloedb/query-language.md#columns-and-types) lists every type and option.
## Every row, indexed three ways
Each row is indexed by every kind of index its fields call for, in the same place, so one query can use them all:
- **Full text**: posting lists of each word's rows, compressed, and scored with BM25.
- **Columns**: each field's values stored by column, for filters, sorting, facets and aggregates.
- **Vectors**: an HNSW graph (or a flat or IVF index) over each vector field, for nearest neighbours.
Rows can also hold **edges** to other rows, which turn a table into a graph that the same queries walk ([graphs](../chloedb/graphs.md)).
Rows are written into immutable **segments**. A new row goes to the write-ahead log and a memory table first; full memory tables are written as segments, and segments are merged in the background, as Lucene and SQLite's FTS5 do. You do not manage segments, but `EXPLAIN` shows a plan for each.
## Queries, scores and the planner
Everything is SQL. Search is a set of functions inside it: `MATCH` selects rows with words, `bm25`, `similarity` and others score them, `rrf` and weighted sums blend scores, and `score()` is the score a row was ranked by. A ranking can multiply in a column (`* (1 + 0.1 * rating)`), decay with age, run a learned model, or rerank its top rows with a cross-encoder. The [search guide](search.md) shows each in use.
A cost-based **planner** decides, for each segment and from exact statistics, how to run each part of a statement: which condition to read from an index, which to test row by row, whether to search vectors before a filter or within it. You write what you want, and `EXPLAIN` says what it chose.
## From a file to a cluster
The same database, and the same SQL, run three ways:
| | how | when | start with |
|---|---|---|---|
| **In your process** | `chloedb.open("books.chloedb")` | one program owns the data: an app, a notebook, an agent | [Python](../quickstart.md#chloedb-from-python-with-no-server) or [JavaScript](../chloedb/javascript.md) |
| **One server** | `chloedb-server --db books.chloedb` | many clients, other languages, a browser UI, a web app with several worker processes | [the quickstart](../quickstart.md) |
| **A cluster** | a coordinator over shards, each with replicas | more data or traffic than one machine holds, or a copy to fail over to | [Operate a cluster](operate-cluster.md) |
One process at a time writes a database file, so a program whose processes all write it, such as a web app run by several workers or a reloader, serves it with a server and uses the clients ([Build a search page](search-page.md) does). [chloedb-server](../chloedb/server.md) serves a database over HTTP JSON and gRPC, with a command center in the browser for queries, health and performance, and an agent that answers questions by writing SQL. Several servers run as shards behind a coordinator that answers like one database, and a primary ships its writes to replicas. The Python, JavaScript and Java clients have the same methods for a file and a server, so code moves from one to the other unchanged.
## Apps on a cluster
Some programs built on ChloeDB run beside a server and appear in its command center: the [crawler](../chloedb/crawler.md), which turns a site into a table, [Sheets](../chloedb/sheets.md), spreadsheets whose cells are rows, and [ChloeCtx](../chloectx/index.md), long-term memory for Claude Code. [Apps on a cluster](apps.md) says how they attach. ChloeCtx also runs on its own, beside Claude Code on your machine, with no server: [Install ChloeCtx](../chloectx/setup.md).
---
# Build an app on chloedb-server
A shop in one page: search, stock that never oversells, holds that expire, and click events counted exactly once. Each part is a few lines of SQL or JSON over HTTP, with links to the reference for the rest.
## Run a server
Download the server for your machine (no Rust or build needed), and start it on a new database:
```sh
v=0.3.11 p=linux-x86_64 # or linux-aarch64, macos-arm64, macos-x86_64
curl -LO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz
tar xzf chloedb-server-$p.tar.gz && cp chloedb-server-$p/chloedb-server ./chloedb-server
./chloedb-server --db shop.chloedb --seq-no
```
The server listens on `http://127.0.0.1:7700` (HTTP JSON, and the command center in a browser) and on 7701 (gRPC). A second server on the same machine, for your tests say, needs both ports of its own: `--listen` moves only the HTTP one, and a second server left on 7701 stops with "the address is in use", so give it `--grpc` another port too, or `--grpc off`. A new `--db` starts with no tables. `--seq-no` numbers every write, which the stock below needs. [Run it](server.md#run-it) has the options, the source build (`cd chloedb-server && cargo build --release`) and the image.
## Make the tables
`POST /v1/sql` takes one statement:
```sh
sql() { curl -s localhost:7700/v1/sql -H 'content-type: application/json' -d "$(jq -n --arg s "$1" '{sql: $s}')"; echo; }
sql "CREATE TABLE listings (id KEYWORD PRIMARY KEY, title TEXT, body TEXT, category KEYWORD,
price FLOAT, stock INT DEFAULT 0,
emb VECTOR OPTIONS(embed = 'title, body', model = 'potion-base-8M'))"
sql "CREATE TABLE holds (id KEYWORD PRIMARY KEY, listing KEYWORD NOT NULL, buyer KEYWORD NOT NULL,
until TIMESTAMP) OPTIONS(expire_by = 'until')"
sql "CREATE TABLE buyers (id KEYWORD PRIMARY KEY, views INT DEFAULT 0)"
sql "CREATE TABLE events (id INT PRIMARY KEY, buyer KEYWORD NOT NULL, listing KEYWORD, kind KEYWORD,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP) OPTIONS(shard_by = 'buyer')"
```
- `TEXT` is searched by words, `KEYWORD` is matched whole (filters, facets), and every column is indexed.
- `emb` is computed by the server from the title and body when a row is written, by a small model (potion-base-8M, 30 MB) that it downloads from Hugging Face when the table is created. Rows written before the model is ready get their vectors once it is; `GET /v1/schema` shows it `"loaded": true`.
- `expire_by` makes a hold vanish at its `until`. `shard_by` keeps a buyer's events on one shard [once there are several](#grow-to-a-cluster).
The [query language](query-language.md#tables) has every type and option.
## Write rows
`POST /v1/write` applies a list of operations in one transaction:
```sh
curl -s localhost:7700/v1/write -H 'content-type: application/json' -d '{"ops": [
{"op": "upsert", "table": "listings", "doc": {"id": "l1", "title": "Red camping tent", "body": "Two-person tent, light and waterproof", "category": "outdoor", "price": 89.0, "stock": 3}},
{"op": "upsert", "table": "listings", "doc": {"id": "l2", "title": "Blue desk lamp", "body": "LED lamp with a dimmer", "category": "home", "price": 24.5, "stock": 10}},
{"op": "upsert", "table": "listings", "doc": {"id": "l3", "title": "Trail running shoes", "body": "Light shoes for wet trails", "category": "outdoor", "price": 120.0, "stock": 0}}
]}'
# {"written":3,"seq_no":5,...}
```
`insert` fails when the key exists, `upsert` replaces the row, `set` changes one column, `add` adds to a number (and creates the row with `doc` when it is missing), and `delete` removes a row by `key`. A 200 answer means the rows are durable. Files load through [`/v1/import`](server.md#loading-rows) (JSONL, CSV, Parquet, SQLite).
## Search
```sh
q() { curl -s localhost:7700/v1/query -H 'content-type: application/json' -d "$1"; echo; }
# words, ranked by BM25, in stock, cheapest first among equals
q '{"sql": "SELECT id, title, price FROM listings WHERE MATCH(title, :q) AND stock > 0 ORDER BY bm25(title, :q) DESC, price LIMIT 10",
"params": {"q": "tent"}, "objects": true}'
# {"columns":["id","title","price"],"rows":[{"id":"l1","price":89.0,"title":"Red camping tent"}],...}
# meaning, not words: the vector of the query text by the field's model, fused with BM25
q '{"sql": "SELECT id, title FROM listings ORDER BY rrf(bm25(body, :t), similarity(emb, :v)) DESC LIMIT 10",
"params": {"t": "shelter for two", "v": {"embed": "shelter for two"}}, "objects": true}'
# facets: how many listings per category
q '{"sql": "SELECT category, COUNT(*) FROM listings GROUP BY category", "objects": true}'
# as you type: "camping te" filters by its last word as a prefix and ranks by the words typed whole
q '{"sql": "SELECT id, title FROM listings WHERE MATCH(title, :typed) AND stock > 0 ORDER BY bm25(title, :whole) DESC, price LIMIT 10",
"params": {"typed": "camping te*", "whole": "camping"}, "objects": true}'
# the words a search matched, marked in each text
curl -s localhost:7700/v1/highlight -H 'content-type: application/json' \
-d '{"table": "listings", "field": "title", "query": "camping te*", "texts": ["Red camping tent"]}'
# {"texts":["Red camping tent"],...}
```
Rows come as lists in the order of `columns`, or as objects with `"objects": true`. A prefix filters but scores nothing in `bm25`, so a query ranked by `bm25(title, 'te*')` alone returns no rows: rank by the words typed whole, or by a column while the first word is being typed ([full text](query-language.md#full-text-match)). `POST /v1/correct` gives a "did you mean" ([did you mean](query-language.md#did-you-mean-correcting-a-querys-words)). A page in a browser cannot send these requests itself from another origin: chloedb-server refuses every `POST` from a page of another site, a query too, and sends no CORS headers, so your app's server code queries it and answers the page ([a search box in a web app](javascript.md#a-search-box-in-a-web-app)). Typo tolerance, synonyms, phrase and prefix search, geographic and time decay, and reranking by a model are in the [query language](query-language.md).
## Read one row by its key
```sh
curl -s localhost:7700/v1/kv/listings/l1
# {"found":true,"key":"l1","row":{"id":"l1",...,"stock":3},"seq_no":5,"table":"listings",...}
```
No SQL is parsed: a read by key costs about what a key-value store's does ([rows by key](server.md#rows-by-key)).
## Sell stock without overselling
Read the row with its `seq_no`, then write it back only if nobody wrote it since (`if_seq_no`). Of several buyers racing for the last item, exactly one write applies; the others get 409 and read again.
```python
import json, urllib.request, urllib.error
def call(method, path, body=None):
req = urllib.request.Request("http://127.0.0.1:7700" + path, method=method,
data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"})
with urllib.request.urlopen(req) as r:
return json.loads(r.read())
def buy(listing):
while True:
got = call("GET", f"/v1/kv/listings/{listing}")
if got["row"]["stock"] <= 0:
return False # sold out
op = {"op": "set", "table": "listings", "key": listing, "field": "stock",
"value": got["row"]["stock"] - 1, "if_seq_no": got["seq_no"]}
try:
call("POST", "/v1/write", {"ops": [op]})
return True
except urllib.error.HTTPError as e:
if e.code != 409: # 409: someone bought meanwhile
raise
```
The Python package's client has the same calls (`chloedb.connect(url).get("l1", table="listings")`, `.write(ops)`); it needs only the standard library ([Python](python.md#a-server-from-python)). More in [conditional writes](server.md#conditional-writes).
## Hold an item for ten minutes
```sh
until=$(python3 -c 'import datetime as d; print((d.datetime.now(d.timezone.utc) + d.timedelta(minutes=10)).isoformat())')
curl -s localhost:7700/v1/write -H 'content-type: application/json' \
-d '{"ops": [{"op": "insert", "table": "holds", "doc": {"id": "h1", "listing": "l1", "buyer": "b7", "until": "'"$until"'"}}]}'
```
From `until` on, the hold is gone from every query, count and read by key, with nothing to clean up. `SELECT COUNT(*) FROM holds WHERE listing = 'l1'` is the number of live holds.
## Count events exactly once
Clicks and views come from a log (Kafka, a queue, a file). Send them to `POST /v1/stream` as NDJSON, each with its place in the log (`source`): the server keeps each source's last offset in the same transaction as the rows, so an event sent twice, after a crash or a retry, is skipped rather than counted again.
```sh
printf '%s\n' \
'{"source": {"name": "clicks/0", "offset": 0}, "ops": [{"op": "insert", "table": "events", "doc": {"id": 1, "buyer": "b7", "listing": "l1", "kind": "view"}}, {"op": "add", "table": "buyers", "key": "b7", "field": "views", "value": 1, "doc": {"id": "b7"}}]}' \
'{"source": {"name": "clicks/0", "offset": 1}, "ops": [{"op": "insert", "table": "events", "doc": {"id": 2, "buyer": "b8", "listing": "l2", "kind": "view"}}, {"op": "add", "table": "buyers", "key": "b8", "field": "views", "value": 1, "doc": {"id": "b8"}}]}' |
curl -s localhost:7700/v1/stream -H 'content-type: application/x-ndjson' --data-binary @-
# {"batch":1,...,"written":4,"skipped":0,...}
curl -s localhost:7700/v1/sources/clicks/0
# {"name":"clicks/0","offset":1,...}: resume from offset 2
```
Send the same lines again and the answer says `"written":0,"skipped":4`. [Streams](server.md#streams) has Kafka consumers and the change feed.
## When a write fails
An error means nothing of the write was applied, with one exception on a cluster (the last below):
- **429**: the server refused the request for its load before doing anything (it is behind on flushing writes to disk, or its write queue is full). The [Python](python.md#a-server-from-python) and [JavaScript](javascript.md#a-server-from-javascript) clients send it again after the answer's `Retry-After`, for up to 10 seconds, and so does a coordinator for its shards; from `curl`, wait a second and send it again.
- **A lost answer** (a timeout, a dropped connection): send the request again with the same `"idempotency_key"`. A server that applied it answers its first answer instead of applying it twice. Keys are kept for an hour.
- **409 with `if_seq_no`**: the row changed; read it again.
- **`"partial": true`**, on a cluster: some shards took their part of the write and keep it, and the others did not. The answer names each shard's part and an `idempotency_key` (yours, or one the coordinator made): send the same request again with that key, and only the shards that did not take their part apply it. [When a write fails](server.md#when-a-write-fails) has the details.
## Grow to a cluster
Several servers as shards, and one more as a coordinator, answer like one database: the same tables, SQL and HTTP API. Stop the server above, then:
```sh
./chloedb-server --db s0.chloedb --seq-no --listen 127.0.0.1:7710 --grpc 127.0.0.1:7711 &
./chloedb-server --db s1.chloedb --seq-no --listen 127.0.0.1:7720 --grpc 127.0.0.1:7721 &
./chloedb-server --shards http://127.0.0.1:7711,http://127.0.0.1:7721 --listen 127.0.0.1:7700 &
```
- Rows go to shards by their key, or by the `shard_by` column, so a buyer's events sit on one shard.
- A shard added later starts as the first ones did: here on a new database with no `--schema`, since this cluster began with no tables. The coordinator gives it the cluster's tables, and a rebalance [moves slots](server.md#moving-slots) onto it while rows keep being written:
```sh
./chloedb-server --db s2.chloedb --seq-no --listen 127.0.0.1:7730 --grpc 127.0.0.1:7731 &
curl -s localhost:7700/v1/admin/shards -H 'content-type: application/json' -d '{"servers": ["http://127.0.0.1:7731"]}'
curl -s localhost:7700/v1/admin/rebalance -X POST
```
- [Replicas](server.md#replication-a-primary-and-its-replicas) of each shard take over when its primary fails.
Through a coordinator, a few things work differently:
- **Graph queries** (`REACHABLE`, `PATH`, `ppr`) run on one database only ([graphs on a cluster](graphs.md#on-a-cluster)).
- **`INSERT ... ON CONFLICT DO NOTHING`** and **`DO UPDATE`**, and `UPDATE` or `DELETE` with a `LIMIT`, are refused. `INSERT OR REPLACE` works.
- **A write across shards** can fail on one shard after others took their part: send it again with the key its error gives ([above](#when-a-write-fails)).
---
# Troubleshooting
The errors people meet first with ChloeDB, each with its message as the program prints it, what it means and what to do. Search this page for a few words of your message. These are the messages of release 0.3.8.
`chloedb-server doctor` checks this machine for the usual causes at once: its version against the latest release, the Python package, the models folder, port 7700 and glibc. It changes nothing, prints a `fix:` line under each check that is not `ok`, and exits 1 when one fails:
```text
$ chloedb-server doctor --offline
ok version: chloedb-server 0.3.11 (the latest release was not looked up)
ok python package: chloedb 0.3.11
warn models: no models in /home/me/.local/share/chloedb/models: a table whose vectors ChloeDB embeds needs its model
fix: chloedb-server fetch-model potion-retrieval-32M (into /home/me/.local/share/chloedb/models)
ok port: 7700 is free (the guides' servers listen there)
ok glibc: 2.39: the prebuilt programs and wheels run here
```
Without `--offline` it also asks GitHub which release is the latest, and says so when it cannot. `--python` names the interpreter whose package it checks (`python3` by default), `--models` the folder and `--port` the port.
## Installing
### The install script stops: `could not tell which chloedb-server release is the newest`
```text
chloedb install: could not tell which chloedb-server release is the newest:
https://api.github.com/repos/chloetech-ai/chloedb-releases/releases?per_page=100: The requested URL returned error: 403
https://github.com/chloetech-ai/chloedb-releases/releases/latest: The requested URL returned error: 403
https://chloetech-ai.github.io/chloedb/site/versions.json: The requested URL returned error: 403
Name the version after the pipe (the releases are https://github.com/chloetech-ai/chloedb-releases/releases, chloedb-server-v; 0.3.11 was the newest when this script was written):
curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION= sh
```
Without `CHLOEDB_VERSION`, the script asks which release is the newest, in turn: GitHub's API (`api.github.com`), then the address `github.com/chloetech-ai/chloedb-releases/releases/latest` leads to, then this website's `versions.json`, and it says which one answered. It stops as above when none did, with each address and what it said: a proxy or firewall that blocks those addresses, or no network. A proxy that blocks only `api.github.com`, or an address that has used up GitHub's 60 requests an hour for clients without an account (a shared office or school network, a CI runner), no longer stops it. Copies of the script from before 18 November 2026, when it learned the other two, stop at the API instead, with these lines:
```text
curl: (22) The requested URL returned error: 403
chloedb install: could not find a chloedb-server release on https://github.com/chloetech-ai/chloedb/releases (set CHLOEDB_VERSION to pick one)
```
In either case, name the version, and the script downloads it without asking. The archives come from `github.com`'s downloads, which often still work where the other addresses are refused. The variable goes after the pipe, where `sh` reads it; in front of `curl` it reaches only `curl`, and the script fails the same way. The last line the script prints is the command to run, with your `--with` and `CHLOEDB_INSTALL_DIR` kept:
```sh
curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION=0.3.11 sh
```
Or install the same server from PyPI, which asks GitHub nothing: `pipx install chloedb-server`, `uv tool install chloedb-server`, `pip install chloedb-server` in a virtualenv, or `uvx chloedb-server` to run it without installing it (macOS 11+, and Linux with glibc 2.34 or later). The [quickstart](../quickstart.md#1-install-the-server) has the other ways, by hand included.
### The install script's other messages
| message | what to do |
|---|---|
| `the prebuilt server needs glibc 2.35 or later (Ubuntu 22.04, Debian 12), and this machine has 2.31: ...` | the prebuilt archives need a newer Linux; the PyPI wheels need glibc 2.34; use the Docker image (`ghcr.io/chloetech-ai/chloedb-server`), or build from source |
| `this Linux has no glibc (Alpine and other musl systems): ...` | use the Docker image, or build from source |
| `Windows has no prebuilt server yet: run this inside WSL 2, or use Docker ...` | run the script inside WSL 2 |
| `could not download https://github.com/.../chloedb-server-v0.3.11/... (is 0.3.11 a released version, and does it have chloedb-server? ...)` | `CHLOEDB_VERSION` names a version that has no release, or `--with` a program that release does not have: see the [releases](https://github.com/chloetech-ai/chloedb-releases/releases) |
| `/home/me/.local/bin is not on your PATH. To add it, put this line in your shell's profile (~/.zshrc, ~/.bashrc): ...` | not an error: the server is installed; add the line it prints, then open a new terminal |
### `chloedb-server: command not found`
```text
bash: chloedb-server: command not found
```
The folder the server was installed into is not on your `PATH`: `~/.local/bin` for the install script (it printed the line to add to your shell's profile), the virtualenv's `bin` for pip (activate it: `. .venv/bin/activate`), or `pipx ensurepath` for pipx. Until then, run it by its path, `~/.local/bin/chloedb-server`.
### `ModuleNotFoundError: No module named 'chloedb'`
The Python that runs your script is not the one `chloedb` was installed into: activate the virtualenv (`. .venv/bin/activate`), or install it with that interpreter, `python3 -m pip install chloedb`. `chloedb-server doctor --python PATH` checks a given interpreter.
### `ImportError: This is chloedb 0.0.3, a placeholder ...`
pip installed the placeholder that held the name on PyPI, which it falls back to when ChloeDB has no wheel for this platform or this Python. The wheels are for CPython 3.10 or later on macOS 11 or later and on Linux x86-64 and aarch64 with glibc 2.28 or later. Check `python3 --version`; elsewhere (Windows outside WSL 2, Alpine, an older Python) [build from source](python.md#from-source). On a machine the wheels cover, `pip install --upgrade chloedb` replaces an old placeholder.
## Opening a database
### `busy: the database is open elsewhere`
```text
chloedb._native.BusyError: busy: the database is open elsewhere: process 3541 (python app.py), the parent of this process, has it open for writing. ...
ERROR chloedb_server: open recipes.chloedb: busy: the database is open elsewhere: process 2210 (python load.py) has it open for writing, and one process writes a database at a time. ...
```
One process at a time can open a database to write it, and the file is open to write already: in another process (a script still running, a chloedb-server serving it, the second process of Flask's debug reloader, another web worker), or in this process, by an earlier `open` of the same path that was not closed (a module imported twice, a notebook cell run again, a hot reload in Next.js). The message goes on to say which, from the process id the writer keeps beside the file (`this process has it open for writing already`, `process N, the parent of this process` for a reloader, or `process N has it open`, with its command on Linux), and what to do; Python and JavaScript add the fix in their own words. Before 0.3.8 it stopped at `the database is open elsewhere`.
- In one process, open the database once and share it; close it before opening it again. In JavaScript, keep it on `globalThis` (`globalThis.db ??= await open(path)`) so that a hot reload finds it.
- Under a reloader (Flask's debug mode, Django's runserver, `uvicorn --reload`), open it when a request first needs it rather than at import, or run without the reloader.
- To read it from other processes while one writes, open it read-only there: `chloedb.open(path, read_only=True)` in Python, `Database.open(path, { readOnly: true })` in JavaScript.
- To write from several processes, serve the file with `chloedb-server --db path` and use the server's clients (`chloedb.connect(url)`), as [Build a search page](../guide/search-page.md) does.
- `chloedb-server --db path` stops with the second line above while a script has the file open: stop the script first, or let it use the server too.
[Python's common errors](python.md#busyerror-busy-the-database-is-open-elsewhere) has more on each case.
### `corrupt database: no valid meta slot`
```text
_chloedb.ChloeDBError: corrupt database: no valid meta slot
ERROR chloedb_server: open recipes.jsonl: corrupt database: no valid meta slot
```
Most often the file is not a ChloeDB database at all: a JSON Lines file, a CSV or a SQLite database given where a database was expected. ChloeDB leaves that file as it was, but makes an empty `-readers` folder beside it, which you can delete. To load such a file's rows, give it to a database: `db.import_file(path)` (JSON Lines, JSON, CSV, TSV), `db.import_sqlite(path)` or `db.import_parquet(path)` in Python, `POST /v1/import` or the command center's import on a server ([loading rows](server.md#loading-rows)). A ChloeDB database that is really damaged says which file and what is damaged, and how to recover ([damaged files](python.md#backing-up-and-damaged-files)).
### `does not exist: pass a schema to create it`
```text
_chloedb.ChloeDBError: books.chloedb does not exist: pass a schema to create it
ERROR chloedb_server: rec.chloedb does not exist: pass --schema (a JSON file, or the JSON) to create it
```
The first is `chloedb.open(path)` without a schema where no database is: a misspelt path, or a script started from another folder (a relative path is read from the current directory). Give the right path, or the schema to create it. The second is `chloedb-server import --db new.chloedb rows.jsonl`: a JSON Lines, JSON or CSV file does not say its types, so a new database needs `--schema`; a SQLite or Parquet file creates its tables itself. Or create the table first (`CREATE TABLE`, from Python or on a server) and import into it: `chloedb-server import` adds the rows to the database's first table, or `--table`. A running server takes files through `POST /v1/import` and the command center's **Import a file**, which proposes the types from the file's values.
## Models and vectors
### `model potion-retrieval-32M: no .../model.safetensors (fetch it first)`
```text
{'emb': 'schema error: model potion-retrieval-32M: no /home/me/.local/share/chloedb/models/potion-retrieval-32M/model.safetensors (fetch it first)'}
```
A vector field names an embedding model that is not in the models folder. Python's `db.embed_errors` says so (above), a server's `GET /v1/schema` says it as each embedded field's `error`, with `"loaded": false`, and `GET /v1/models` lists what would open. Meanwhile the writes and queries that need the model fail:
```text
chloedb._native.BadRequestError: schema error: notes.emb is embedded by model potion-retrieval-32M, which is not open: the row would be written without its vector, which similarity() never finds. ...
chloedb._native.BadRequestError: query error: no embedded field has its model open
parameter :v: no table has a field this server can embed text for; pass a vector
```
The Python, JavaScript and Java packages download a model ChloeDB knows themselves, the first time a database that names it opens, and say so on stderr: this error then means the download failed (it says why: no network, a proxy, a file whose checksum differs) or was turned off with `CHLOEDB_FETCH_MODELS=0`. Fetch it once by hand: `chloedb-server fetch-model potion-retrieval-32M` or `python -m chloedb fetch-model potion-retrieval-32M` (about 130 MB); `HF_ENDPOINT` names a mirror of Hugging Face for the packages. The models folder is `$CHLOEDB_MODELS` when that is set, else `~/.local/share/chloedb/models` (`~/.local/share/strata/models` on a machine that has that folder from before the rename); a server takes `--models DIR`, Python `chloedb.open(..., models=DIR)` and JavaScript the `models` option. Open the database again after fetching it; a running server opens a model fetched through it (its **Models** page, or `POST /v1/admin/models/fetch`). A server fetches a model it knows by itself when a table names it (unless it runs with `--no-fetch-models`, for a machine that cannot reach huggingface.co), and fills in the vectors of the rows written meanwhile; the error shows until the download ends, and `GET /v1/schema` then says `"loaded": true`. Meanwhile each embedded field in `GET /v1/schema` and `GET /v1/tables` says how its model's download goes, as `fetch` (`queued`, `running` with `bytes` of `size`, `done`, or `failed` with its `error`), and the command center's **Add meaning** shows it (`Downloading the model potion-retrieval-32M: 40.9 MB of 125 MB…`) and offers the Meaning search once it ends.
### A BERT model such as bge-small does not run
```text
ERROR chloedb_server: schema error: model bge-small-en-v1.5 is a BERT model: build with the `bert` feature
```
The prebuilt programs (the install script's archives, the PyPI wheels, the npm package and the Docker image) are built without the `bert` feature, so the BERT models ChloeDB knows do not run in them: `bge-small-en-v1.5`, `snowflake-arctic-embed-m-v1.5`, the ColBERT model `answerai-colbert-small-v1`, and the cross-encoders `ms-marco-MiniLM-L-6-v2` and `bge-reranker-base`. `chloedb-server fetch-model bge-small-en-v1.5` downloads the model (about 133 MB) and then stops with the message above, and a table that names one lists it in Python's `db.embed_errors`, which refuses the writes that need it, while a server stores those rows without their vectors. Models of images, sound and ONNX exports need the `vision`, `audio` and `onnx` features, also left out of the prebuilt programs. `chloedb-server doctor` warns about each model in the models folder that its build cannot run, and names the feature. What to do instead:
- **A model that runs in every build**: `potion-retrieval-32M` (Model2Vec, 512 dimensions, the one the guides use) or the smaller `potion-base-8M`, and their int8 copies ([embedded vector fields](server.md#embedded-vector-fields)).
- **A hosted model**: `openai/text-embedding-3-small`, `cohere/embed-v4.0`, `voyage/voyage-3.5`, or `ollama/nomic-embed-text` from an Ollama on your own machine, with no key ([hosted models](server.md#hosted-models)). The prebuilt programs call them.
- **Your own vectors**: make them with any library (fastembed, sentence-transformers) and write them into a `VECTOR` field with its `dim` and no `embed`, then pass the query's vector the same way (`ORDER BY similarity(emb, :v)`, with `v` a list of floats or a numpy array).
- **A build from source with the feature**: `cargo build --release --bin chloedb-server --features bert` in `chloedb-server/` (`--features accelerate` on a Mac), or `MATURIN_PEP517_ARGS="--features bert" pip install ./chloedb-py` for Python ([from source](python.md#from-source)).
## Running a server
### `the address is in use`
```text
ERROR chloedb_server: listen on 127.0.0.1:7700: the address is in use, by another chloedb-server or another program (lsof -i :7700 names it): stop it, or give --listen another port
ERROR chloedb_server: listen on 127.0.0.1:7701: the address is in use, by another chloedb-server or another program (lsof -i :7701 names it): stop it, or give --grpc another port
```
Another program has the port: often a chloedb-server started earlier and still running. `lsof -i :7700` names it. A server listens on two ports, HTTP on 7700 and gRPC on 7701, so a second server on the same machine needs both moved: `--listen 127.0.0.1:7710 --grpc 127.0.0.1:7711`, or `--grpc off` when nothing uses gRPC.
A server started without `--listen` does that itself: when 7700 or 7701 is taken, it takes the first free pair ten above them (7710 and 7711, then 7720 and 7721, up to ten tries) and says so, naming the chloedb-server that has the default when it is one. The error above is for an address you gave, which it keeps to.
### `is reachable beyond this machine: set --token`
```text
ERROR chloedb_server: 0.0.0.0:7700 is reachable beyond this machine: set --token (or $CHLOEDB_TOKEN), make an API key, or pass --no-token to serve it open
```
A server that listens on an address other machines can reach (`0.0.0.0`, a LAN address, inside a container) must have a token or an API key, so that nobody else can change it. Give it `--token` (or `$CHLOEDB_TOKEN`) and send the token from every client, or listen on `127.0.0.1` ([security](server.md#security)).
### `401`: `missing or wrong token`
```text
{"error":"missing or wrong token","error_code":"unauthenticated","hint":"send Authorization: Bearer ; a key that expired or was revoked needs a new one",...}
```
The server has a token or API keys, and the request sent none, or one it does not know. Send it as `Authorization: Bearer `: `curl -H 'authorization: Bearer ...'`, `chloedb.connect(url, token=...)` in Python and `connect(url, { token })` in JavaScript, or set `$CHLOEDB_TOKEN`, which both clients read. Python raises it as `UnauthorizedError: missing or wrong token (HTTP 401)`. A key that is known but may not do what was asked gets 403 instead, naming the scope it needs: `a write statement needs a key with the write scope; "page" has read`.
### `a page from http://localhost:3000 cannot change this server`
A browser page of another origin called the server directly, and chloedb-server refuses those (403), reads included: call it from your app's own server code instead, or serve the page from the server's own origin ([JavaScript in a browser](javascript.md)).
### `URLError: `
A Python client found no server at its URL: start the server, or check the address and port its log printed (`HTTP and UI on http://127.0.0.1:7700/`). It is an `OSError`, not a `ChloeDBError` ([Python's common errors](python.md#urlerror-urlopen-error-errno-111-connection-refused)).
## ChloeCtx
`chloectx doctor` prints a line per check, `ok`, `warn` or `FAIL`, and each `FAIL` line says how to fix it: [Install ChloeCtx](../chloectx/setup.md#troubleshooting) goes through them.
---
# Search guide
This page builds a small catalogue of books and searches it every way ChloeDB can: words, phrases and typos, filters and facets, meaning, a blend of the two, and results spread across authors. Each query is SQL, and every block runs, in order, against the code it documents. The [SQL reference](../chloedb/query-language.md) has every function and option; this page shows which to reach for.
You need Python with the `chloedb` package and `chloedb-server` on your `PATH` ([quickstart](../quickstart.md)). The server program fetches the embedding model once; everything else runs in your Python process, with no server.
**Running this page's SQL yourself.** Each SQL block below is one statement, with the rows it returns under it. Pass it to the database as a string: in Python, `db.query(sql)`, with a value for each `:name` placeholder as a keyword argument (`db.query(sql, q="dragon")`); in JavaScript, `await db.query(sql, {q: "dragon"})` ([JavaScript](../chloedb/javascript.md#querying)); over HTTP, `POST /v1/sql` with `{"sql": "...", "params": {"q": "dragon"}}` to a chloedb-server that serves the file (`chloedb-server --db books.chloedb`, [HTTP API](../chloedb/server.md#http-api)). The command center's SQL workbench runs them as they are. The first search below shows the Python form.
## The catalogue
Twelve books, one JSON object a line:
```json file=books.jsonl
{"id": "b01", "title": "The River and the Dragon", "author": "Ana Ruiz", "genres": ["fantasy"], "year": 1999, "rating": 4.1, "description": "A girl follows a river north to find the dragon that drowned her village."}
{"id": "b02", "title": "Winter Garden", "author": "Tomas Berg", "genres": ["mystery"], "year": 2005, "rating": 3.8, "description": "A gardener finds a letter buried under the frozen roses and a quiet village mystery begins."}
{"id": "b03", "title": "Dragons of the Salt Coast", "author": "Ana Ruiz", "genres": ["fantasy", "adventure"], "year": 2003, "rating": 4.4, "description": "Sea dragons guard the salt flats, and a smuggler crew sails into their storm."}
{"id": "b04", "title": "The Last Lighthouse", "author": "Mei Chen", "genres": ["literary"], "year": 2018, "rating": 4.6, "description": "An old keeper writes letters to the ships that no longer pass her lighthouse."}
{"id": "b05", "title": "Machine Hearts", "author": "Jonas Abara", "genres": ["science fiction"], "year": 2021, "rating": 4.0, "description": "A repair robot learns to grieve after its owner dies on a mining station."}
{"id": "b06", "title": "Stars Over Lagos", "author": "Jonas Abara", "genres": ["science fiction", "adventure"], "year": 2016, "rating": 4.2, "description": "Engineers in Lagos build a launch site and race a rival company to orbit."}
{"id": "b07", "title": "The Cartographer's Daughter", "author": "Mei Chen", "genres": ["historical", "adventure"], "year": 2012, "rating": 4.3, "description": "A mapmaker's daughter crosses the mountains with her father's unfinished maps."}
{"id": "b08", "title": "Murder at the Observatory", "author": "Tomas Berg", "genres": ["mystery"], "year": 2019, "rating": 3.9, "description": "An astronomer is found dead beneath the telescope, and every guest saw the stars."}
{"id": "b09", "title": "Bread and Salt", "author": "Lena Novak", "genres": ["literary", "historical"], "year": 2008, "rating": 4.5, "description": "Three generations of bakers keep a village alive through war and famine."}
{"id": "b10", "title": "The Dragon Accords", "author": "Lena Novak", "genres": ["fantasy"], "year": 2022, "rating": 3.7, "description": "Diplomats negotiate a treaty between kingdoms and the last of the dragons."}
{"id": "b11", "title": "Quiet Machines", "author": "Mei Chen", "genres": ["science fiction", "literary"], "year": 2024, "rating": 4.7, "description": "Household robots begin to write poems, and a lonely engineer reads every one."}
{"id": "b12", "title": "Tides of Glass", "author": "Ana Ruiz", "genres": ["fantasy", "romance"], "year": 2011, "rating": 4.0, "description": "A glassblower falls for a sea witch who trades storms for memories."}
```
A table with a primary key, text to search, keywords and numbers to filter on, and a vector that ChloeDB computes from the title and description with a small embedding model. Fetch the model once (it is about 130 MB, kept in `~/.local/share/chloedb/models`, or wherever `CHLOEDB_MODELS` says; a machine with `~/.local/share/strata/models` from before the rename keeps using that):
```sh
chloedb-server fetch-model potion-retrieval-32M
```
```python file=load.py
import json
import chloedb
db = chloedb.open("books.chloedb", schema={
"table": "books",
"key": "id",
"fields": [
{"name": "id", "type": "keyword"},
{"name": "title", "type": "text"},
{"name": "description", "type": "text"},
{"name": "author", "type": "keyword"},
{"name": "genres", "type": "keyword", "multi": True},
{"name": "year", "type": "int"},
{"name": "rating", "type": "float"},
{"name": "emb", "type": "vector",
"embed": {"from": ["title", "description"], "model": "potion-retrieval-32M"}},
],
})
with open("books.jsonl") as f:
db.insert(json.loads(line) for line in f)
print(len(db), "books")
db.close()
```
```sh
python3 load.py
```
```text output
12 books
```
The same table in SQL, as `db.sql(...)` and a server's `POST /v1/sql` take it, is `CREATE TABLE books (id KEYWORD PRIMARY KEY, title TEXT, description TEXT, author KEYWORD, genres KEYWORD[], year INT, rating FLOAT, emb VECTOR OPTIONS(embed = 'title, description', model = 'potion-retrieval-32M'))`.
## Words: `MATCH` and `bm25`
`MATCH` says whether a row has the words; `bm25` scores how well, and `score()` is the score a row was ranked by. Both take the field to search:
```sql db=books.chloedb
SELECT id, title, score() FROM books
WHERE MATCH(description, 'village')
ORDER BY bm25(description, 'village') DESC LIMIT 5
```
```text output
id | title | score()
----+--------------------------+--------
b01 | The River and the Dragon | 1.322
b09 | Bread and Salt | 1.322
b02 | Winter Garden | 1.213
```
The same statement from Python, with the search's words as a parameter:
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
r = db.query("""SELECT id, title, score() FROM books
WHERE MATCH(description, :q)
ORDER BY bm25(description, :q) DESC LIMIT 5""", q="village")
for row in r:
print(row["id"], row["title"], round(row["score()"], 3))
```
```text output
b01 The River and the Dragon 1.322
b09 Bread and Salt 1.322
b02 Winter Garden 1.213
```
Words are stemmed, so `dragon` finds *dragons*. `MATCH` reads a small query language: words side by side must all be there, `OR` and `-` (not) combine them, quotes ask for a phrase, `*` for a prefix:
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(description, '(dragon OR robot) -sea') ORDER BY id
```
```text output
id | title
----+-------------------------
b01 | The River and the Dragon
b05 | Machine Hearts
b10 | The Dragon Accords
b11 | Quiet Machines
```
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(description, '"salt flats"') OR MATCH(title, 'mach*') ORDER BY id
```
```text output
id | title
----+--------------------------
b03 | Dragons of the Salt Coast
b05 | Machine Hearts
b11 | Quiet Machines
```
### As you type: prefixes
`bm25` reads a prefix as `MATCH` does: `drag*` ranks by the words of the field that begin *drag* ([weights, required and excluded words](../chloedb/query-language.md#weights-required-and-excluded-words)). So a search box can send what has been typed so far, its last word with a `*` while it is being typed, to both:
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(title, 'drag*') ORDER BY bm25(title, 'drag*') DESC
```
```text output
id | title
----+--------------------------
b01 | The River and the Dragon
b10 | The Dragon Accords
b03 | Dragons of the Salt Coast
```
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(title, 'salt drag*') ORDER BY bm25(title, 'salt drag*') DESC
```
```text output
id | title
----+--------------------------
b03 | Dragons of the Salt Coast
```
**Changed:** `bm25` read `drag*` as the word *drag* before, which no book has, and a ranking by `bm25` returns only the rows it scores, so the first query found nothing until the last word was whole. Against a server or package of 0.3.7 or earlier, rank by the words already typed in full, or by a column while there are none:
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(title, 'drag*') ORDER BY rating DESC
```
```text output
id | title
----+--------------------------
b03 | Dragons of the Salt Coast
b01 | The River and the Dragon
b10 | The Dragon Accords
```
A prefix is lowercased, and finds the words that start with it and the words it may be the start of whose stems do not. The index keeps stems (*mystery* as *mysteri*, *running* as *run*), so a prefix also looks up the stem of what was typed as a word, and in English the stems of what was typed completed by a common ending (`runni*` finds *running*). Every letter of a word typed keeps its rows:
```sql db=books.chloedb
SELECT id, title FROM books WHERE MATCH(description, 'mystery*')
```
```text output
id | title
----+--------------
b02 | Winter Garden
```
**Changed:** a prefix matched only the stems that start with it before, so against a server or package of 0.3.7 or earlier a word typed in full and then `*` (`mystery*`, `battery*`, `headphone*`) finds nothing, though each letter before it found the rows.
`db.search(text)` ranks with `bm25` too, so it finds nothing for a word half typed unless the word ends in `*`. To complete whole values instead (the searches people ran before, names kept as `KEYWORD`), `PREFIX(field, :typed)` reads a keyword field's sorted values, with typos if asked ([prefixes and autocomplete](../chloedb/query-language.md#prefixes-and-autocomplete)).
## Typos
`fuzzy => 'auto'` lets a word be an edit or two away, more for longer words, counted on the word as typed rather than on its stem: *choclate* is one edit from *chocolate*, though its stem, *choclat*, is three from *chocol*. Ranked, it corrects a typo rather than widening every word:
```sql db=books.chloedb
SELECT id, title FROM books ORDER BY bm25(description, 'lighthuose keeper', fuzzy => 'auto') DESC LIMIT 1
```
```text output
id | title
----+--------------------
b04 | The Last Lighthouse
```
`db.search(text)` forgives a typo in each word, as the search box on a table's page in the command center does (which, when nothing is found, also offers the correction, "did you mean", if there is one); `typos=False` searches the words as written. A query of your own that should forgive typos asks for it in its SQL, or writes `~` after a word (`dragn~`), which `bm25` reads as `fuzzy => 'auto'` for that word. With a `MATCH`, a row must have every word, each as typed or within its edits, and a `bm25` of the same text on the same field takes the `MATCH`'s `fuzzy` and ranks every row the `MATCH` keeps, the words as typed first. For the text of a search box, `MATCH(description, :q, syntax => 'plain')` reads it as words alone, so a stray quote or bracket is no error ([what a visitor typed](../chloedb/query-language.md#full-text-match)):
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
r = db.query("""SELECT id, title FROM books
WHERE MATCH(description, :q, fuzzy => 'auto')
ORDER BY bm25(description, :q) DESC LIMIT 3""", q="dragn villge")
for row in r:
print(row["id"], row["title"])
print(len(db.search("dragn villge", mode="text")), "rows from db.search")
print(len(db.search("dragn villge", mode="text", typos=False)), "rows by the words as written")
```
```text output
b01 The River and the Dragon
5 rows from db.search
0 rows by the words as written
```
[Build a search page](search-page.md) puts this behind a search box, with the matched words highlighted and "did you mean" for a misspelt word.
## Filters and facets
Text, keyword, number and list conditions mix freely in `WHERE`, and the planner picks the order. A multi-valued keyword such as `genres` matches a row when any of its values does:
```sql db=books.chloedb
SELECT id, title, year FROM books
WHERE genres = 'adventure' AND year >= 2010
ORDER BY rating DESC
```
```text output
id | title | year
----+-----------------------------+-----
b07 | The Cartographer's Daughter | 2012
b06 | Stars Over Lagos | 2016
```
Facets, the counts beside a search box, are a `GROUP BY` over the rows that match:
```sql db=books.chloedb
SELECT author, COUNT(*) AS books, AVG(rating) AS avg_rating FROM books
WHERE MATCH(description, 'dragon OR dragons OR sea OR robot')
GROUP BY author ORDER BY books DESC, author
```
```text output
author | books | avg_rating
------------+-------+-----------
Ana Ruiz | 3 | 4.167
Jonas Abara | 1 | 4
Lena Novak | 1 | 3.7
Mei Chen | 1 | 4.7
```
## Meaning: vectors
`similarity(emb, :v)` scores rows by how close their vector is to a query's. In Python a parameter `{"embed": text}` is the text's vector by the field's own model, so a question finds books that share none of its words:
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
r = db.query("SELECT id, title FROM books ORDER BY similarity(emb, :v) DESC LIMIT 3",
v={"embed": "artificial intelligence and feelings"})
for row in r:
print(row["id"], row["title"])
```
```text output
b05 Machine Hearts
b11 Quiet Machines
b06 Stars Over Lagos
```
A vector search walks 200 candidates of the field's HNSW graph by default, which is fast and on some collections finds less than you want: on GloVe-100's 1.18M word vectors it finds 0.859 of the exact top 10. `similarity(emb, :v, ef => 800)` walks 800 and found 0.942 in 1.29 ms of the server's time, where hosted Pinecone took 11.0 ms of its own for that recall ([the comparison](../site/bench-vectors.html#hosted)); `similarity(emb, :v, strategy => 'flat')` scores every row exactly.
## Similar rows: more like this
`{"vector_of": key}` is the vector a row already has, so ranking by `similarity` to it lists the rows nearest it in meaning: "more like this" under a product, "readers also liked" under a book. `id <> :id` leaves the row itself out, and any other condition goes in the same `WHERE`:
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
r = db.query("SELECT id, title FROM books WHERE id <> :id ORDER BY similarity(emb, :v) DESC LIMIT 3",
id="b01", v={"vector_of": "b01"})
for row in r:
print(row["id"], row["title"])
```
```text output
b10 The Dragon Accords
b03 Dragons of the Salt Coast
b07 The Cartographer's Daughter
```
The vector is read from the table the statement names (`{"vector_of": "b01", "table": "books"}` names one). The parameter is the same from JavaScript (`{vector_of: "b01"}`), in the `params` of a server's `POST /v1/sql`, and through a client of a server (`chloedb.connect`).
## Both: hybrid ranking
Words find exact names and rare terms; vectors find paraphrases. `rrf` fuses the two rankings by reciprocal rank, and needs no tuning:
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
q = "a story about the sea and storms"
r = db.query("""
SELECT id, title, score() FROM books
ORDER BY rrf(bm25(description, :q), similarity(emb, :v)) DESC LIMIT 3
""", q=q, v={"embed": q})
for row in r:
print(row["id"], row["title"])
```
```text output
b03 Dragons of the Salt Coast
b12 Tides of Glass
b04 The Last Lighthouse
```
When one side should count more, normalise each score to 0..1 and weigh them: `ORDER BY 0.3 * minmax(bm25(description, :q)) + 0.7 * minmax(similarity(emb, :v)) DESC`. The same blend can boost by a column, `* (1 + 0.1 * rating)`; [ranking expressions](../chloedb/query-language.md#ranking-expressions) has the rest.
For the common case, `db.search(text)` writes this query itself: BM25 over the text fields fused with the vector field's similarity.
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
for row in db.search("lonely robots", limit=2, columns=["id", "title"]):
print(row["id"], row["title"])
```
```text output
b11 Quiet Machines
b05 Machine Hearts
```
## Spread results out: `MAX k PER`
A ranking where one author fills the page reads badly. `MAX 1 PER author` keeps each author's best row and the order of the rest:
```sql db=books.chloedb
SELECT id, author, title FROM books ORDER BY rating DESC MAX 1 PER author
```
```text output
id | author | title
----+-------------+--------------------------
b11 | Mei Chen | Quiet Machines
b09 | Lena Novak | Bread and Salt
b03 | Ana Ruiz | Dragons of the Salt Coast
b06 | Jonas Abara | Stars Over Lagos
b08 | Tomas Berg | Murder at the Observatory
```
## What the planner did
Each answer says how it was found. In Python, `stats["plan"]` holds a line for each segment the query read: which conditions came from an index, which were tested row by row, and how the rows were ranked. [Reading a plan](../chloedb/query-language.md#reading-a-plan) explains the lines, and a server's `POST /v1/explain` takes the same `SELECT` and answers its plan as a tree too.
```python
import chloedb
db = chloedb.open("books.chloedb", read_only=True)
r = db.query("SELECT id FROM books WHERE MATCH(description, 'dragon') AND year > 2000 "
"ORDER BY bm25(description, 'dragon') DESC LIMIT 3")
print(r.keys)
for line in r.stats["plan"]:
print(line)
```
```text output
['b10', 'b03']
seg 0: bm25 MaxScore, filter Probe
```
## Next
- [Build a search page](search-page.md): this page's queries behind a search box in a Python web app, with highlights, did you mean and more like this.
- [Retrieval for RAG](rag.md): the hybrid query above, feeding passages to a model.
- [The SQL reference](../chloedb/query-language.md): joins, window functions, graphs, rank profiles, rerankers.
- [Python](../chloedb/python.md): queries built in Python rather than SQL text, Arrow results, writes.
---
# Build a search page
This page builds the search page of a small shop in Python: a search box that forgives typos, the words it matched highlighted in the results, "did you mean" under a misspelt search, a filter by category with the count of each, and "more like this" under every product. The web page runs on Python's own `http.server`, so it needs nothing but the standard library and `chloedb`; the [Flask version](#the-same-page-in-flask) at the end uses the same functions.
You need Python 3.10 or later with the `chloedb` package and `chloedb-server` on your `PATH`. The package's `server` extra installs both, prebuilt (from 0.3.7):
```sh
# install
python3 -m venv .venv && . .venv/bin/activate
pip install "chloedb[server]" # chloedb, and chloedb-server of the same release
```
## Why the page talks to a server
Two parts of a search page are routes of [chloedb-server](../chloedb/server.md#http-api), not methods of a database opened in your process: highlighting (`POST /v1/highlight`) and did you mean (`POST /v1/correct`). A web app also tends to run as more than one process: Flask's debug reloader runs your module twice, and gunicorn starts several workers. Only one process at a time can open a database file to write it, and a second one fails with `BusyError: busy: the database is open elsewhere`.
So the catalogue lives in chloedb-server, and the page is its client through `chloedb.connect`, which has the same methods as a database in your process (`query`, `insert`, `search`, `get`). Every process of the app can connect, and none of them holds the file. A page that needs neither highlights nor did you mean can skip the server: each process opens the file with `chloedb.open(path, read_only=True)`, and one other process writes it ([Python](../chloedb/python.md#a-database-in-your-process)).
## The catalogue
Seventeen products, one JSON object a line:
```json file=products.jsonl
{"id": "p01", "name": "Waterproof hiking jacket", "description": "A light shell jacket that keeps the rain out on long hikes.", "category": "jackets", "price": 129.0}
{"id": "p02", "name": "Insulated winter jacket", "description": "A warm down jacket for cold city winters.", "category": "jackets", "price": 189.0}
{"id": "p03", "name": "Packable rain jacket", "description": "A waterproof jacket that folds into its own pocket.", "category": "jackets", "price": 89.0}
{"id": "p04", "name": "Fleece jacket", "description": "A soft fleece layer for cold mornings and campfires.", "category": "jackets", "price": 69.0}
{"id": "p05", "name": "Kids' rain jacket", "description": "A bright waterproof jacket with a hood, for children.", "category": "jackets", "price": 49.0}
{"id": "p06", "name": "Softshell cycling jacket", "description": "A windproof jacket for cool rides, with reflective trim.", "category": "jackets", "price": 109.0}
{"id": "p07", "name": "Trail running shoes", "description": "Grippy, waterproof shoes for muddy trails.", "category": "shoes", "price": 99.0}
{"id": "p08", "name": "Leather office shoes", "description": "Classic leather shoes for the office.", "category": "shoes", "price": 149.0}
{"id": "p09", "name": "Hiking boots", "description": "Waterproof leather boots with ankle support for rocky paths.", "category": "shoes", "price": 159.0}
{"id": "p10", "name": "Wool hiking socks", "description": "Warm socks that dry fast on wet hikes.", "category": "shoes", "price": 15.0}
{"id": "p11", "name": "Rain cover for backpacks", "description": "A waterproof cover that fits 20 to 40 litre packs.", "category": "gear", "price": 19.0}
{"id": "p12", "name": "Daypack, 25 litres", "description": "A light backpack for day hikes, with a pocket for a water bladder.", "category": "gear", "price": 75.0}
{"id": "p13", "name": "Headlamp", "description": "A bright rechargeable headlamp for night hikes and camping.", "category": "gear", "price": 35.0}
{"id": "p14", "name": "Camping stove", "description": "A small gas stove that boils a litre of water in four minutes.", "category": "gear", "price": 59.0}
{"id": "p15", "name": "Down sleeping bag", "description": "A warm sleeping bag for cold nights in the mountains.", "category": "gear", "price": 219.0}
{"id": "p16", "name": "Insulated water bottle", "description": "Keeps drinks cold for a day or hot for twelve hours.", "category": "gear", "price": 25.0}
{"id": "p17", "name": "Trekking poles", "description": "Light aluminium poles that take the load off your knees on steep descents.", "category": "gear", "price": 65.0}
```
"More like this" compares products by meaning, with a vector that ChloeDB computes from each product's name and description by a small embedding model. Fetch the model once (about 130 MB, into `~/.local/share/chloedb/models`, or wherever `CHLOEDB_MODELS` says), then start the server on a new database file. It listens on `127.0.0.1:7700`, which only this machine can reach:
```sh
chloedb-server fetch-model potion-retrieval-32M
chloedb-server --db shop.chloedb > server.log 2>&1 &
server=$!
until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done
```
On your own machine, run `chloedb-server --db shop.chloedb` in a terminal of its own instead, and leave it running.
The table has the fields to show (`name`, `description`, `price`), a keyword to filter on (`category`), `body`, a text field generated from the name and the description, which is what the search box searches, and `emb`, the vector:
```python file=load.py
import json
import chloedb
db = chloedb.connect("http://127.0.0.1:7700")
db.sql("""
CREATE TABLE products (
id KEYWORD PRIMARY KEY,
name TEXT,
description TEXT,
category KEYWORD,
price FLOAT,
body TEXT OPTIONS(from = 'name, description'),
emb VECTOR OPTIONS(embed = 'name, description', model = 'potion-retrieval-32M')
)
""")
with open("products.jsonl") as f:
print(db.insert([json.loads(line) for line in f], table="products"), "products")
```
```sh
python3 load.py
```
```text output
17 products
```
## The queries, as functions
Everything the page asks the database is in one module. Values always go in as parameters (`:q`, `:category`), never into the SQL text, so nothing a visitor types can change a statement:
```python file=shop.py
"""The shop's search: what the page asks chloedb-server, as functions."""
import json
import urllib.request
import chloedb
SERVER = "http://127.0.0.1:7700"
db = chloedb.connect(SERVER)
def where(q, category=None, max_price=None):
"""The WHERE clause and parameters of a search for q."""
conds, params = ["MATCH(body, :q, syntax => 'plain', fuzzy => 'auto')"], {"q": q}
if category:
conds.append("category = :category")
params["category"] = category
if max_price is not None:
conds.append("price <= :max_price")
params["max_price"] = max_price
return " AND ".join(conds), params
def search(q, category=None, max_price=None, limit=10):
"""The products with q's words, typos forgiven, best match first."""
cond, params = where(q, category, max_price)
sql = f"""SELECT id, name, description, category, price FROM products
WHERE {cond} ORDER BY bm25(body, :q) DESC LIMIT :limit"""
return db.query(sql, params, limit=limit).dicts()
def categories(q, max_price=None):
"""How many products each category has for q: the filter's counts."""
cond, params = where(q, max_price=max_price)
sql = f"""SELECT category, COUNT(*) AS n FROM products
WHERE {cond} GROUP BY category ORDER BY n DESC, category"""
return db.query(sql, params).rows
def more_like(key, limit=3):
"""The products nearest in meaning to the product with this key."""
sql = """SELECT id, name, price FROM products WHERE id <> :key
ORDER BY similarity(emb, :v) DESC LIMIT :limit"""
return db.query(sql, key=key, v={"vector_of": key}, limit=limit).dicts()
def post(route, body):
"""Sends a JSON body to a route of the server and returns its answer."""
request = urllib.request.Request(SERVER + route, data=json.dumps(body).encode(),
headers={"content-type": "application/json"})
with urllib.request.urlopen(request) as answer:
return json.load(answer)
def highlight(q, texts):
"""Each text, HTML-escaped, with the words q matches between tags."""
answer = post("/v1/highlight", {"table": "products", "field": "body",
"query": q, "texts": texts, "size": 0})
return answer["texts"]
def did_you_mean(q):
"""q with its misspelt words corrected, or None when it has none."""
answer = post("/v1/correct", {"table": "products", "field": "body", "text": q})
return answer["text"] if answer["changed"] else None
```
The sections below try each function from Python before the page puts them together.
### Typos
`MATCH(body, :q, syntax => 'plain', fuzzy => 'auto')` keeps the products that have every word of the search, each spelt as typed or an edit away (two edits for words of six letters or more; none for words of one or two letters). `syntax => 'plain'` reads the search as its words alone, so what a visitor types is never an error: a stray quote or bracket (`rain jacket"`) is left out, and `-`, `OR` and `*` are no operators. `bm25(body, :q)` ranks them, and since it ranks the same text on the same field, it reads the words as the `MATCH` does and ranks every product the `MATCH` keeps, those spelt as typed first ([typos](../chloedb/query-language.md#typos-and-synonyms)). So "jaket" finds every jacket:
```python
import shop
for p in shop.search("jaket"):
print(p["id"], p["name"], p["price"])
```
```text output
p05 Kids' rain jacket 49.0
p02 Insulated winter jacket 189.0
p03 Packable rain jacket 89.0
p06 Softshell cycling jacket 109.0
p01 Waterproof hiking jacket 129.0
p04 Fleece jacket 69.0
```
Typos are forgiven where a query asks for it: `db.search(text)` asks for it itself (`typos=False` turns it off), as the search box on a table's page in the command center does, and a query of your own should send the box's text with `fuzzy => 'auto'`, as `shop.search` does. Every word of the search must be there; for a box where any word will do, rank with `bm25(body, :q, fuzzy => 'auto')` and leave the `MATCH` out (a ranked `bm25` returns the rows that have any of its words).
### A filter, with its counts
The filter is one more condition in the `WHERE`, and its counts are a `GROUP BY` over the same conditions, so each count is the number of products its link shows:
```python
import shop
print(shop.categories("waterprof"))
for p in shop.search("waterprof", category="shoes", max_price=150):
print(p["id"], p["name"], p["price"])
```
```text output
[['jackets', 3], ['shoes', 2], ['gear', 1]]
p07 Trail running shoes 99.0
```
### Highlights
`POST /v1/highlight` marks the words a search matches in any texts you send it, as the field's analyzer reads them, so "waterprof" marks *Waterproof* and "jaket" marks *jacket*. The answer is HTML-escaped, with `` tags around each match, ready to put in a page (`size` cuts each text to the stretch of about that many characters with the most matches; `0` keeps it whole):
```python
import shop
hits = shop.search("waterprof jaket")
for text in shop.highlight("waterprof jaket", [p["name"] for p in hits] + [p["description"] for p in hits]):
print(text)
```
```text output
Kids' rain jacket
Packable rain jacket
Waterproof hiking jacket
A bright waterproof jacket with a hood, for children.
A waterproof jacket that folds into its own pocket.
A light shell jacket that keeps the rain out on long hikes.
```
Highlighting reads typos a little more strictly than the search does: a word of four letters or fewer is marked only where it is spelt as typed.
### Did you mean
`POST /v1/correct` replaces the words of a search that no product has with the word of the field they most likely meant. It suggests a word only when it is fairly sure, which on a small catalogue means a word that many products use: one edit from what was typed, and in five products or more ([did you mean](../chloedb/query-language.md#did-you-mean-correcting-a-querys-words)). Six products say "jacket", and two say "leather", so the first typo gets a suggestion and the second does not, although the search finds both:
```python
import shop
print(shop.did_you_mean("waterprof jaket"))
print(shop.did_you_mean("lether"))
print([p["name"] for p in shop.search("lether")])
```
```text output
waterproof jacket
None
['Leather office shoes', 'Hiking boots']
```
### More like this
`{"vector_of": key}` is the stored vector of the row with that key, so ordering by `similarity(emb, :v)` lists the products nearest it in meaning. `id <> :key` leaves out the product itself, and any other condition (the same category, in stock) goes in the same `WHERE`:
```python
import shop
for p in shop.more_like("p01"):
print(p["id"], p["name"])
```
```text output
p03 Packable rain jacket
p05 Kids' rain jacket
p11 Rain cover for backpacks
```
## The page
`app.py` serves the page at `http://127.0.0.1:8000`: a form with the search box and a highest price, did you mean, the category links with their counts, and the results with their words marked and a "More like this" link each. It escapes everything it did not get from `/v1/highlight`, which escapes for it, and shows an error page when chloedb-server does not answer:
```python file=app.py
"""The shop's search page, on Python's own web server."""
import html
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlparse
import chloedb
import shop
FORM = """
Shop search
"""
def link(text, **params):
"""A link to this page with these parameters."""
return f'{html.escape(text)}'
def page(q, category, max_price, like):
lines = [FORM.format(q=html.escape(q), max_price=html.escape(max_price))]
if like:
lines.append("
More like this
")
for p in shop.more_like(like, limit=5):
lines.append(f"
{html.escape(p['name'])}, ${p['price']:.2f}
")
return "\n".join(lines)
if not q:
return "\n".join(lines)
try:
price = float(max_price) if max_price else None
except ValueError:
price = None
suggestion = shop.did_you_mean(q)
if suggestion:
lines.append(f"
Did you mean {link(suggestion, q=suggestion)}?
")
counts = [link(f"{c} ({n})", q=q, category=c, max_price=max_price) for c, n in shop.categories(q, price)]
lines.append("
")
hits = shop.search(q, category=category or None, max_price=price)
marked = shop.highlight(q, [p["name"] for p in hits] + [p["description"] for p in hits]) if hits else []
for p, name, description in zip(hits, marked, marked[len(hits):]):
lines.append(f"
{name} ${p['price']:.2f}: {description} {link('More like this', like=p['id'])}
")
if not hits:
lines.append("
No products have those words.
")
return "\n".join(lines)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
if url.path != "/":
self.send_error(404)
return
args = {k: v[0] for k, v in parse_qs(url.query).items()}
try:
text = page(args.get("q", "").strip(), args.get("category", ""),
args.get("max_price", ""), args.get("like", ""))
body = (text + "\n").encode()
except (chloedb.ChloeDBError, OSError) as e: # OSError: chloedb-server does not answer
self.send_error(503, "The search is not available", str(e))
return
self.send_response(200)
self.send_header("content-type", "text/html; charset=utf-8")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
```
Start it, and ask it for a search with a typo, as a browser would:
```sh
python3 app.py > app.log 2>&1 &
app=$!
until curl -sf http://127.0.0.1:8000/ > /dev/null; do sleep 0.2; done
curl -s 'http://127.0.0.1:8000/?q=waterprof+jaket&max_price=100'
```
```text output
...
Kids' rain jacket $49.00: A bright waterproof jacket with a hood, for children. More like this
Packable rain jacket $89.00: A waterproof jacket that folds into its own pocket. More like this
```
Open [http://127.0.0.1:8000](http://127.0.0.1:8000) in a browser and try "sleping bag", "lether", "warm" or "hiking boots" with a highest price. The server's own command center, at [http://127.0.0.1:7700](http://127.0.0.1:7700), shows the same table and the queries the page sent (**Queries**).
The browser talks only to the app, and the app to chloedb-server. That keeps the server's address and keys out of the page, and it is also the only way that works: chloedb-server refuses requests from pages of other sites, reads included ([security](../chloedb/server.md#security)).
When you are done, stop both (the catalogue stays in `shop.chloedb`):
```sh
kill $app $server
```
## The same page in Flask
The functions of `shop.py` drop into any web framework. This is the page in [Flask](https://flask.palletsprojects.com) (`pip install flask`, then `flask --app flask_app run --debug`), shortened to the search and "more like this". It is shown, not run with this page, which installs nothing but `chloedb`:
```python file=flask_app.py
from flask import Flask, render_template_string, request
import shop
app = Flask(__name__)
PAGE = """
{% if suggestion %}
{{ name | safe }} ${{ "%.2f" | format(p.price) }} More like this
{% endfor %}
{% for p in similar %}
{{ p.name }}, ${{ "%.2f" | format(p.price) }}
{% endfor %}
"""
@app.get("/")
def index():
q = request.args.get("q", "").strip()
hits = shop.search(q) if q else []
names = shop.highlight(q, [p["name"] for p in hits]) if hits else []
return render_template_string(PAGE, q=q, suggestion=q and shop.did_you_mean(q), hits=zip(hits, names), similar=[])
@app.get("/like/")
def like(key):
return render_template_string(PAGE, q="", suggestion=None, hits=[], similar=shop.more_like(key, limit=5))
```
`| safe` is for the highlighted names alone, which `/v1/highlight` has escaped already; Jinja escapes the rest. With `--debug`, Flask runs this module in two processes, one that watches the files and one that serves. Both are clients of the one chloedb-server, so the second starts as the first did. Had the module opened the file itself with `chloedb.open("shop.chloedb")`, the second would have failed with `BusyError: busy: the database is open elsewhere`, since the first holds it, and every request with it ([troubleshooting](../chloedb/troubleshooting.md#busy-the-database-is-open-elsewhere)). For an asyncio framework such as FastAPI, `chloedb.AsyncClient` has the same methods as coroutines ([from asyncio](../chloedb/python.md#from-asyncio)).
## Before other people use it
- Give chloedb-server a token before it listens beyond this machine, and the app a key: `chloedb.connect(SERVER, token=...)`, or `$CHLOEDB_TOKEN` ([security](../chloedb/server.md#security)). A key that can only read the products table is enough for this page.
- Change a product with `UPDATE` or `upsert`: `upsert` replaces the whole row, so it needs every field, while `UPDATE products SET price = 79 WHERE id = 'p03'` changes one. Writes are searchable on the next query.
- [Troubleshooting](../chloedb/troubleshooting.md) has the errors people meet first, each with its message and what to do.
## Next
- [The search guide](search.md): phrases, prefixes as you type, vectors, hybrid ranking and results spread across a field.
- [Python](../chloedb/python.md): every method of `chloedb.connect` and `chloedb.open`, and their errors.
- [The SQL reference](../chloedb/query-language.md): boosts by a column (`bm25(body, :q) * (1 + 0.1 * rating)`), synonyms and rank profiles.
---
# ChloeDB's query language
ChloeDB speaks standard SQL over the tables of a database: `SELECT` with functions for full text, vectors, rank fusion and graphs, aggregates, typo-tolerant and synonym searches, and subqueries, `WITH` and joins of a table with itself; `INSERT`, `UPDATE` and `DELETE`; `CREATE TABLE`, `ALTER TABLE` and `DROP TABLE`; and functions stored in the database (`CREATE FUNCTION`), which queries call. Text, structured and vector conditions mix freely in one statement, and the planner decides how to evaluate them together.
It reads like PostgreSQL's SQL and gives the same answers for most queries, but it is not PostgreSQL: a few expressions give other answers, some statements are refused, and no Postgres client connects to it, since ChloeDB serves no Postgres wire protocol. [Differences from PostgreSQL](#differences-from-postgresql) lists them, and [Running SQL](#running-sql) the ways a statement gets in.
## A first look
```sql
-- boolean full text and structured filters, ranked by BM25
SELECT id, title, score() FROM papers
WHERE MATCH(body, 'vaccine AND (mrna OR "messenger rna") NOT animal')
AND year BETWEEN 2019 AND 2021 AND category IN ('virology', 'immunology')
ORDER BY bm25(body, 'mrna vaccine efficacy') DESC LIMIT 10;
-- filtered vector search
SELECT id FROM papers WHERE rating >= 4
ORDER BY similarity(emb, :q) DESC LIMIT 10;
-- hybrid: a weighted sum of normalised scores, or reciprocal rank fusion
SELECT id FROM papers WHERE year >= 2015
ORDER BY 0.2 * tmm(bm25(body, :text)) + 0.8 * tmm(similarity(emb, :q)) DESC LIMIT 10;
SELECT id FROM papers WHERE year >= 2015
ORDER BY rrf(bm25(body, :text), similarity(emb, :q)) DESC LIMIT 10;
-- any expression of scores and columns
SELECT id FROM papers
ORDER BY ln(1 + bm25(body, :text)) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10;
-- facets and aggregates over any result
SELECT category, COUNT(*), AVG(rating), MAX(year) FROM papers WHERE MATCH(body, 'vaccine')
GROUP BY category HAVING COUNT(*) >= 10 ORDER BY 2 DESC LIMIT 5;
-- typos and synonyms
SELECT id FROM papers WHERE MATCH(body, 'vacine~ OR mrna', synonyms => 1) LIMIT 10;
-- a join along citations, ranked by one side
SELECT a.id, a.title, b.id AS cited, b.title AS cited_title
FROM papers a JOIN papers b ON a.cites = b.id
WHERE a.year >= 2020 ORDER BY bm25(a.body, 'mrna vaccine') DESC LIMIT 20;
```
## Statement shape
```text
[WITH name AS (SELECT ...), ...]
SELECT [DISTINCT | DISTINCT ON ()]
FROM
[JOIN
ON ...] | | (SELECT ...) AS t
[WHERE ]
[GROUP BY [HAVING ]]
[QUALIFY ]
[WINDOW name AS (), ...]
[{UNION | INTERSECT | EXCEPT} [ALL] SELECT ...]
[ORDER BY [ASC | DESC] [NULLS FIRST | LAST] [, [ASC | DESC]] [MAX k PER ]]
[PACK n TOKENS [OF ] [EXCERPT n] [DEDUPE x [ON ]] [FOLLOW [n HOP]] [WITH RECEIPT]]
[LIMIT n [OFFSET m]]
```
- **Tables by name.** A database holds one or more [tables](#tables), and a query reads the tables it names (in any case): one, or several joined, read by subqueries or named in `WITH` ([below](#subqueries-with-and-joins)).
- **Quoted names.** A table or column name in double quotes is the name inside them, so any name can be written: `"order"` (a word SQL reserves), `"doc no"`, `"say ""hi"""` (a quote doubled), and `FROM "papers"` reads papers. Python's [`table()`](python.md#queries-built-in-python) builds queries with no quoting at all.
- **Strings** are single-quoted, `'sale'`. Where a value goes, a double-quoted `"sale"` is a string too, as SQLite and MySQL read it, and a bare name is an error rather than a string: `WHERE tag = sale` says `no such column: sale`.
- **Clauses ChloeDB does not run are errors**, never ignored: `FETCH`, `FOR UPDATE`, `TOP`, `SELECT INTO`, `GROUP BY ... WITH ROLLUP` and the like. An error says where and why: the parser's give the line, the column and the token (`SQL syntax error at line 2, column 1 (near "FORM products"): ... found FORM (did you mean FROM?)`), and a misspelt column, table or function names the ones near it and what there is.
- **Conditions the indexes cannot answer** test each row the others find: a function or arithmetic of a column (`lower(brand) = 'acme'`, `price * 2 > 100`, `CAST(price AS INT) = 5`), two columns compared (`price > rating`), `LIKE` with `%` or `_` inside the pattern, `ILIKE`, `IS NULL` of a field whose index does not keep it, a `CASE`, and a comparison of a `TEXT` field, by its stored text (`title LIKE '%tent%'`, `title = 'Tent 2'`). A field with a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) answers `LIKE` and `ILIKE` itself. The other conditions of the `WHERE` still narrow the scan by their indexes, so `year = 2020 AND title LIKE '%tent%'` reads the rows of 2020 only, and a `WHERE` of such conditions alone reads every row of the table. A field that is not stored (a generated `TEXT` field, an embedded vector) has no value to test.
- **`SELECT` of no table**, `SELECT 1 + 1` or `SELECT now()`, gives one row of its values; its plan says it reads `one row of no table`. `SELECT *` of no table is an error, since there are no columns to give.
- **`CAST(x AS type)`** (or `x::type`) makes an `INT` (rounded to the nearest whole number: a `FLOAT`'s value half to even, as PostgreSQL rounds a `double precision`, so `CAST(price AS INT)` of 2.5 is 2; a number written in the statement, or a value made of such numbers alone (`CASE WHEN qty > 0 THEN 2.5 END`), half away from zero, as PostgreSQL rounds a `numeric`, so `CAST(2.5 AS INT)` is 3), a `FLOAT`, `TEXT`, and of a value a `BOOL` (`'true'`, `'yes'`, `1`) or a `TIMESTAMP` (`CAST('2026-11-02' AS TIMESTAMP)`); text that is not a number is an error.
- **`SELECT *`** returns every stored, non-vector column.
- **`score()`** is the value of the `ORDER BY` score for each row (over a `WITH` result read without an `ORDER BY`, the score the `WITH` ranked its rows by); **`hops()`** is a row's distance in a graph traversal ([below](#graphs)); **`seq_no()`** is the sequence number of the write that last changed the row, in a database that numbers its writes, for [conditional writes](server.md#conditional-writes). It is a column of a query on one table, and cannot be aggregated or ordered by. A [ranking expression](#features-the-values-a-ranking-read) that scores each row by itself is a column too (`bm25(title, :q) AS t`), and **`features()`** stands for the inputs of the query's ranking.
- **`ORDER BY`** takes one key, or several. The scan orders by the first and breaks its ties by a second that is the primary key (or, in a facet query, the group column); other keys sort the rows the `WHERE` keeps in memory, as over joined rows (`ORDER BY rating DESC, price`). Ranking by a score is always best first; a `KEYWORD` or stored `TEXT` column first sorts the rows by its text, `NULL` last either way, which the row evaluator does after reading every row the `WHERE` keeps; so does a function of a row's values without a score (`ORDER BY lower(brand)`, `ORDER BY date_trunc('day', at)`, `ORDER BY hash(id, 7)`); `ORDER BY distance(…) ASC` ranks by Euclidean distance, nearest first ([below](#similarityfield-vector-and-distancefield-vector)). `MAX k PER field` at its end keeps at most k rows of each value ([below](#at-most-k-rows-of-a-value-max-k-per)). A key may name a selected column by its alias, as in PostgreSQL: `SELECT id, bm25(name, :q) AS score FROM products ORDER BY score DESC` ranks by the `bm25` (an alias is read before a column of the same name). **Changed:** a scored alias was refused before (`no such column: score`).
- **Parameters** are `:name` placeholders, bound from the API or from the shell's `--param name=value`. A vector parameter is a JSON array.
- **Limits.** An expression nests at most 1,000 levels, counting parentheses and the operators of a chain such as `a OR b OR …` (SQLite has the same default); a long list of values belongs in `IN (…)`, which has no such limit. A `LIMIT` larger than the table returns every row that qualifies. A query ranked by a score without a `LIMIT` returns 100 rows, counted after its `OFFSET`, on one database and through a coordinator alike, and says so: its stats hold `implicit_limit: 100`, and `truncated: true` with a plan line (`no LIMIT: ...`) when more rows matched (`result.truncated` and `result.implicit_limit` in Python, `result.truncated` and `result.implicitLimit` in JavaScript). A `DELETE` is never cut by that default: `DELETE ... ORDER BY ` without a `LIMIT` is refused, since its order would only choose which rows a `LIMIT` keeps; write the match in `WHERE` (`DELETE FROM t WHERE MATCH(body, 'x')`) to delete every row that matches. (Before, it deleted the top 100.)
- **Memory and time.** What a query builds up (its groups, `COUNT(DISTINCT)` and percentile values, the rows it orders before its `LIMIT` and the rows it returns, a graph walk's nodes, a compound query's parts and join tables) is counted against a memory budget as it grows, and a query that would go past it fails with a `memory:` error naming the budget, giving back what it held, instead of the process running out of memory. chloedb-server's queries share `--query-memory-mb` ([limits](server.md#limits)). A database opened in a program (Rust's `Db`, Python's `Database`, JavaScript's and Java's) counts its queries against one budget its whole process shares: a quarter of the machine's memory (the cgroup's limit, else RAM), or `CHLOEDB_QUERY_MEMORY_MB` MiB (`0`: none), read when the first database opens; a database or a query may be given a budget of its own (`memory` in [Python](python.md#limits-memory-deadlines-interrupting) and [JavaScript](javascript.md#limits-memory-deadlines-aborting), `ExecOptions::memory` in Rust). Such a database sets no deadline, no row window and no group cap of its own, unlike a server (`--timeout-ms`, `--max-result-window`, `--max-groups`), but for JavaScript's, which answers at most the server's 10,000 rows a query and reads past them by [cursors](javascript.md#reading-past-the-window-cursors), so that code tested on one runs on the other: a query given a deadline (`timeout_ms`), or cancelled from another thread (`interrupt()`, an `AbortSignal`, `ExecOptions::cancel`), stops within a few thousand rows of it, checking between segments and every 1,024 rows it groups, orders, walks or joins.
## Columns and types
| type | indexed as | filters |
|---|---|---|
| `INT`, `FLOAT` (finite: no NaN or infinity) | frame-of-reference column with zone maps, range histogram | `=`, `!=`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IS [NOT] NULL` |
| `KEYWORD` | dictionary codes and one docID list per value; with `substring = true`, a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) too | `=`, `!=`, `IN`, `NOT IN`, `IS [NOT] NULL`, [prefixes](#prefixes-and-autocomplete) (`LIKE 'p%'`, `PREFIX`), `<`, `<=`, `>`, `>=` and `BETWEEN` (a single-valued field); `GROUP BY`; with a substring index, any `LIKE` and `ILIKE` |
| `BOOL` | an `INT` column of 1 and 0 | the field alone (`WHERE done`, `NOT done`), `=`, `!=`, `IS [NOT] TRUE`, `IS [NOT] FALSE`, `IS [NOT] NULL`; `GROUP BY` |
| `TIMESTAMP` | an `INT` column of microseconds since 1970-01-01 UTC | as `INT`, with times written as text: `at >= '2026-10-01'` |
| `TEXT` | inverted index (optionally with positions); may be generated from other text fields; with `substring = true`, a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) too | `MATCH`; with a substring index, `LIKE` and `ILIKE` |
| `VECTOR(d)` | float32 rows plus 8-bit codes (or 1-bit codes, `"codes": "binary"`, or RaBitQ codes of 1, 2 or 4 bits, `"rabitq1"`, `"rabitq2"`, `"rabitq4"`), with HNSW, IVF or flat search; may be declared as a model's embedding of other fields ([embedded vector fields](server.md#embedded-vector-fields)) | ordering by `similarity` / `distance`; a similarity graph |
| `VECTOR(d)[]` | several vectors per row (a page's patches, a song's frames): 1-bit codes searched, 8-bit codes to score (float32 too with `keep_f32`), and maps from rows to their vectors and back | ordering by `maxsim` |
| `SPARSE` | inverted index of learned term weights (SPLADE and similar) | ordering by `similarity` |
| `MEDIA` | a file by reference: URI, SHA-256, type, size; a `KEYWORD` index of the hashes | `=`, `IN` on the hash; `GROUP BY` |
| `EDGES` | out-edge CSR and reverse index per segment | `REACHABLE`, `PATH`, `ppr` |
| `JSON` | an object's keys no schema names: one sorted dictionary of `path, type, value` terms with a docID list each ([JSON fields](#json-fields-keys-no-schema-names)) | on paths (`attrs.color`): `=`, `!=`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `NOT IN`, `LIKE 'p%'`, `PREFIX`, `IS [NOT] NULL`, `IS TRUE`, the path alone |
Predicates combine with `AND`, `OR`, `NOT`, [`AT_LEAST`](#some-of-the-conditions-at_least) and parentheses, across all of these, and [`max_rows`](#as-many-as-fit-min_rows-and-max_rows) lets an `AT_LEAST` choose its count.
A `KEYWORD` compares with text: `k = 1` is an error that points to `k = '1'`, as `n = '2'` is on an `INT` (a write still stores the number 1 in a `KEYWORD` as `'1'`). `INT` values are 64-bit integers and compare exactly: `id = 9007199254740993` finds that row and not 9007199254740992, which a double cannot tell apart. Arithmetic of `INT`s (`+`, `-`, `*`, `%`) is exact while its result fits in 64 bits; a result that does not is a `FLOAT`, not an error (`n * 9223372036854775807` of an `n` of 3 is `2.7670116110564327e19`), `/` always gives a `FLOAT`, and dividing by 0 (with `/` or `%`) gives `NULL`. A client that reads such a column as integers gets a float where a result overflowed. A fraction bounds integers by rounding inward (`n > 2.5` is `n >= 3`, `n = 2.5` matches nothing). A write gives an `INT` a float with no fraction as its whole number (`2.0` is 2, as pandas writes whole numbers in a column with gaps), from SQL, JSON and CSV alike, and refuses `2.5`.
`NULL` follows SQL's three-valued logic. A comparison with a missing value is neither true nor false, and so is its negation: `rating != 2` and `NOT rating > 2` leave out the rows without a rating. Ask for them with `rating IS NULL` (`IS NOT NULL` for the others). So does a comparison no value can meet, such as `passengers != 1.5` on an `INT` field. `MATCH` and graph predicates are always true or false, so `NOT MATCH(body, 'x')` includes rows without a body. A filter on a multi-valued field holds when some value matches, and its negation when none does, so `tags != 'red'` includes rows without tags (`tags IS NULL` finds those). `rating = NULL` is an error that points to `IS NULL`. `rating IN (1, NULL)` is TRUE where the rating is 1 and UNKNOWN elsewhere, so `rating NOT IN (1, NULL)`, like `NOT IN` a subquery that returns a `NULL`, keeps no row; a multi-valued field's `IN` is TRUE or FALSE (the `NULL` matches none of its values). `LIKE '%'` and `PREFIX(f, '')` hold for every row with a value and are UNKNOWN for the others, so their `NOT` keeps no row of a single-valued field. A scalar subquery that finds no row is `NULL`, and a comparison with it keeps no row either way.
A `BOOL` is `TRUE` or `FALSE`; a write also takes 1 and 0 and the text `'true'`, `'false'`, `'t'`, `'f'`, `'1'` and `'0'`, and refuses anything else. A field named alone is a condition (`WHERE done AND NOT archived`), with `NULL` neither true nor false: `NOT done` and `done != TRUE` leave out the rows without a value, `done IS NOT TRUE` takes them in. `SUM(done)` counts the trues, and answers come back as booleans.
A `TIMESTAMP` is a moment, kept to the microsecond in UTC and written as ISO 8601 text: a date (`'2026-10-01'`, midnight UTC) or a date and time (`'2026-10-01T12:30:00Z'`, `'2026-10-01 14:30:05.25+02:00'`), with an offset or none (UTC). A number is refused, so seconds are not mistaken for microseconds. Comparisons, `BETWEEN`, `IN`, `ORDER BY`, `MIN`, `MAX` and `COUNT` work on it (`SUM` and `AVG` do not), and answers are ISO 8601 text in UTC, such as `2026-10-01T12:30:05.250Z`. In `decay(at, origin, scale)` on a `TIMESTAMP`, the origin is a time or `now()`, and the scale and offset are seconds: `decay(published, now(), 2592000)` halves a row's weight for each 30 days of age. `date_trunc`, `EXTRACT` and `strftime` take [parts of times](#parts-of-times-date_trunc-extract-and-strftime), for `GROUP BY` a day, a week or a month, and [intervals](#times-later-and-earlier-interval) move a time (`now() - INTERVAL '15 minutes'`). A `DATE` column is a `TIMESTAMP`: a date written alone is its midnight UTC, and a time given is kept. A database whose tables use `BOOL` or `TIMESTAMP` is written in [file format 3](index.md#wal-memtable-and-snapshots), which versions of ChloeDB before these types refuse.
`KEYWORD` and `INT` fields may be multi-valued (`"multi": true` in the schema): a row holds a list, such as `ARRAY['red', 'blue']`, and a filter matches a row if any of its values matches. A facet counts each distinct value once per row.
A multi-valued field also compares with a list of values as a set, by PostgreSQL's array operators. The list is `ARRAY[...]` of values or a list parameter (`:groups`), and its values are written as the field's are:
| condition | holds where | read from the index as |
|---|---|---|
| `tags @> ARRAY['red', 'sale']` | the row has every value of the list (contains all) | an `AND` of equalities; every row for an empty list |
| `tags && ARRAY['red', 'sale']` | the row has a value of the list (overlaps) | `IN` the values; no row for an empty list |
| `groups <@ :allowed` | each value of the row is in the list (contained by), on an `INT[]` field | `NOT` of the ranges between the list's values |
The list may come first: `ARRAY['red'] <@ tags` is `tags @> ARRAY['red']`. A row without values is the empty set, so `@>` an empty list and `<@` any list hold for it, and `NOT` of a set operator holds where the set operator does not, as for other conditions on a multi-valued field. `<@` is how a row lists what it needs and a query what it has: with `required INT[]` holding the groups a reader must belong to, `WHERE required <@ :user_groups` keeps the documents whose every required group is one of the user's (and those that require none), and it filters a vector or text search as any condition does. A `KEYWORD[]` field does not take `<@` yet, since its index cannot list the values outside a list; an `INT[]` of ids does. Over rows in memory (a `WITH` result), `&&` compares any two lists, and `@>` a list column with a list written out.
A `KEYWORD[]` field may hold the [semantic ID](server.md#semantic-ids) of a vector field: every prefix of a code such as `12.7.201.0`, filled in by the writer, so `sid = '12.7'` finds the rows under a prefix. `sid_at(sid, n)` is the first `n` numbers of a code (`sid_at(sid, 2)` is `'12.7'`), in `SELECT`, `WHERE` and `GROUP BY`.
A `SPARSE` value is a JSON object of terms and non-negative weights, `{"tok": 1.25, "##en": 0.4}`, as a learned sparse model (SPLADE, BGE-M3's sparse output, OpenSearch's neural sparse models) writes it. Terms are taken as given, not analysed, and weights are stored in steps of 1/1024.
A `MEDIA` value names a file, `{"uri": "https://cdn.example.com/a.png", "sha256": "…", "mime": "image/png", "bytes": 48213, "width": 640, "height": 480}`, and a write may give only its URI, `'https://cdn.example.com/a.png'`, or its bytes, `'{"data": ""}'`, for the server to fill in ([media fields](server.md#media-fields)). Its index holds the hash: `image = '9f86d0…'` finds the rows of that file. `OPTIONS(kind = 'image')` takes only images (`'audio'`, `'video'`, `'pdf'`), whose vectors a `VECTOR` field can hold: `emb VECTOR OPTIONS(embed = 'image', model = 'siglip-base-patch16-224')` ([vectors of images](server.md#vectors-of-images)), `sound_emb VECTOR OPTIONS(embed = 'recording', model = 'clap-htsat-unfused')` ([vectors of sound](server.md#vectors-of-sound)), and whose captions or transcripts a `TEXT` field can: `caption TEXT OPTIONS(derive = 'image', model = 'blip-image-captioning-base')`, `transcript TEXT OPTIONS(derive = 'recording', model = 'whisper-small')` ([text from media](server.md#text-from-media)). A language model can make a `TEXT` field of another's text, told what by a prompt: `product TEXT OPTIONS(derive = 'body', model = 'anthropic/claude-haiku-5-5', prompt = 'Name the product this review is about.')` ([text from text](server.md#text-from-text)).
### Parts of times: `date_trunc`, `EXTRACT` and `strftime`
```sql
SELECT date_trunc('day', at) AS day, COUNT(*), AVG(price), MIN(price) FROM snapshots GROUP BY day ORDER BY day;
SELECT EXTRACT(dow FROM at) AS dow, AVG(price) FROM snapshots WHERE item = 'i42' GROUP BY dow;
SELECT strftime('%Y-%m', at) AS month, SUM(price) FROM sales GROUP BY month;
SELECT date_bin('5 minutes', ts) AS b, severity, COUNT(*) FROM logs WHERE ts >= '2026-11-12' GROUP BY b, severity;
-- A moving average of daily prices: groups by day in a WITH, a window over them.
WITH daily AS (SELECT item, date_trunc('day', at) AS day, AVG(price) AS px FROM snapshots GROUP BY item, day)
SELECT item, day, px, AVG(px) OVER (PARTITION BY item ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7
FROM daily;
```
- **`date_trunc(unit, t)`** is the time cut to the start of its `second`, `minute`, `hour`, `day`, `week` (from Monday, as ISO 8601 and PostgreSQL count weeks), `month`, `quarter` or `year`, a `TIMESTAMP`. The unit is text in any case, and a plural (`'days'`) is taken too.
- **`date_bin(width, t [, origin])`** is the start of the bucket of a fixed `width` that the time is in, a `TIMESTAMP`, as PostgreSQL's `date_bin`: buckets are counted from `origin` (a `TIMESTAMP` or ISO 8601 text; 1970-01-01 without one), so `date_bin('15 minutes', at, '2026-01-01T00:05:00Z')` starts buckets at :05, :20, :35 and :50. The width is a whole number and a unit: `microseconds` (`us`), `milliseconds` (`ms`), `seconds` (`s`), `minutes` (`m`), `hours` (`h`), `days` (`d`) or `weeks` (`w`), singular or plural, as `'5 minutes'`, `'30s'` or `'1 day'`; months and years are not a fixed width, and are `date_trunc`'s. `date_bin('1 day', t)` is `date_trunc('day', t)`. OpenSearch's `date_histogram` with a `fixed_interval` runs as one.
- **`date_part(part, t)`**, and **`EXTRACT(part FROM t)`** which is the same function, is a number: `year`, `isoyear`, `quarter` (1 to 4), `month` (1 to 12), `week` (the ISO week, 1 to 53), `day` (of the month), `doy` (of the year, 1 to 366), `dow` (0 for Sunday to 6 for Saturday, as PostgreSQL counts), `isodow` (1 for Monday to 7 for Sunday), `hour`, `minute`, and as a `FLOAT`, `second` (with its fraction) and `epoch` (seconds since 1970).
- **`time_bucket(width, t)`** is another name for `date_bin(width, t)`, as TimescaleDB spells it: `time_bucket('5 minutes', ts)` gives 03:00, 03:05, 03:10. The width can also be an `INTERVAL '5 minutes'`.
- **`date_diff(unit, start, end)`** (and `datediff`) is an `INT`, how many boundaries of the unit there are from `start` to `end`, negative when `end` is earlier: `microsecond`, `millisecond`, `second`, `minute`, `hour`, `day`, `week` (from Monday), `month`, `quarter` or `year`, singular or plural. It counts as DuckDB's and Snowflake's `date_diff` do, by the two times cut to the unit, so `date_diff('month', '2026-01-31', '2026-02-01')` is 1 and `date_diff('day', '2026-01-01 23:00', '2026-01-02 01:00')` is 1; PostgreSQL has no `date_diff`, and its `end - start` is an `INTERVAL`, which ChloeDB does not have. For the whole days or seconds between two times, `date_diff('day', a, b)` or `date_diff('second', a, b)`.
- **`strftime(format, t)`** is text, written as SQLite's `strftime` writes it: `%Y` year, `%m` month 01-12, `%d` day 01-31, `%H` hour 00-23, `%M` minute, `%S` second, `%f` seconds with milliseconds (`SS.SSS`), `%j` day of the year 001-366, `%w` day of the week 0-6 from Sunday, `%u` 1-7 from Monday, `%W` week of the year 00-53 from the first Monday, `%V` the ISO week 01-53 and `%G` its year, `%s` seconds since 1970, `%F` for `%Y-%m-%d`, `%T` for `%H:%M:%S`, and `%%` for a `%`.
- **A day.** `CAST(t AS DATE)`, `DATE(t)` and `date_trunc('day', t)` are the same, the start of the time's day; ChloeDB keeps it a `TIMESTAMP` (there is no separate `DATE` type). **`CURRENT_DATE`** is the start of today, `date_trunc('day', now())`, so `WHERE at >= CURRENT_DATE - INTERVAL '7 days'` keeps the last seven days and today, and `GROUP BY CAST(at AS DATE)` counts by day.
They all read times in UTC. A `NULL` time gives `NULL`, text is read as a time (`date_trunc('month', '2026-11-05')`), and any other value is an error, as are a unit, part or directive they do not have (the message lists the ones they do).
A **`GROUP BY` of one of them over a `TIMESTAMP` field of the table** (indexed, one value per row) runs in the executor, as a `GROUP BY` of a column does: it reads the field's column, has no limit on the number of rows, and over shards each shard groups its own rows and the coordinator merges the groups. The rows without a time form the group `NULL`. Anywhere else, in `SELECT`, `WHERE` and over joined or derived rows, they are computed row by row; in `WHERE` they are a [condition the indexes cannot answer](#statement-shape), so a range of times is faster written on the field (`at >= '2026-11-01' AND at < '2026-12-01'`) than as `EXTRACT(month FROM at) = 11`. A plan that uses them needs the plan feature `dates`, which shards of a version without these functions refuse, and one with `date_bin` also needs the plan feature `date_bin`, one with `date_diff` the plan feature `sql_functions`.
### Text and numbers: `substr`, `trim`, `replace`, `concat`, `nullif`, `floor` and `ceil`
```sql
SELECT substr(sku, 1, 3) AS family, COUNT(*) FROM products GROUP BY family;
SELECT id, trim(name), replace(phone, '-', ''), concat(first, ' ', last) FROM customers;
SELECT SUM(total) / nullif(COUNT(*), 0) FROM invoices; -- NULL, not an error, for no rows
SELECT floor(price / 10) * 10 AS band, COUNT(*) FROM products GROUP BY band ORDER BY band;
```
They answer as PostgreSQL's do:
- **`substr(s, start [, count])`**, **`substring(s, start [, count])`** and **`SUBSTRING(s FROM start [FOR count])`** are the characters of `s` from the `start`-th on (the first is 1), at most `count` of them. A `start` before the first character takes as many fewer (`substr('hello', 0, 2)` is `'h'`), one past the end gives `''`, and a negative `count` is an error. They count characters, not bytes.
- **`trim(s)`**, **`ltrim(s)`** and **`rtrim(s)`** take the spaces off both ends, the start or the end; with a second argument, the characters it holds instead: `btrim('xxaxx', 'x')` is `'a'`, `ltrim(body, 'fs')` takes any `f` and `s` off the start. **`TRIM([BOTH | LEADING | TRAILING] [chars FROM] s)`** is the same, as SQL writes it. Only spaces, not tabs or line breaks, are taken without a second argument, as in PostgreSQL.
- **`replace(s, from, to)`** replaces every `from` in `s` by `to`; an empty `from` replaces nothing.
- **`concat(a, b, …)`** is its arguments as text, one after the other, leaving out the `NULL`s, so it is `''` when all are `NULL`; `a || b` is `NULL` when either is. A number or a time is written as `||` writes it.
- **`nullif(a, b)`** is `NULL` where `a = b`, and `a` elsewhere (`CASE WHEN a = b THEN NULL ELSE a END`).
- **`floor(x)`** and **`ceil(x)`** (`ceiling`) are the whole numbers below and above `x`, `INT`s as `round(x)` is: `floor(2.7)` is 2, `ceil(-2.5)` is -2. A whole number beyond an `INT`'s range is an error.
Text functions take text: a number is an error (`substr(CAST(n AS TEXT), 1, 2)` takes its digits). Any `NULL` argument gives `NULL`, except in `concat`. Over one table they are computed row by row, in `SELECT`, `WHERE`, `GROUP BY` and `ORDER BY`, as over joined and derived rows, and in a `WHERE` they are a [condition the indexes cannot answer](#statement-shape) (`substr(sku, 1, 3) = 'ABC'` reads every row the other conditions keep; `sku LIKE 'ABC%'` reads the index). A plan with `substr`, `trim`, `ltrim`, `rtrim`, `replace`, `floor`, `ceil` or `date_diff` needs the plan feature `sql_functions`, which shards of a version without these functions refuse; `concat` and `nullif` are written with `||`, `coalesce` and `CASE`, which every version reads.
### Samples, splits and shuffles: `hash`
```sql
-- about a tenth of the rows, the same tenth every time
SELECT * FROM events WHERE hash(id, 7) % 10 = 0;
-- a train/test split, 80/20: every row in one part
SELECT * FROM events WHERE hash(id, 7) % 10 < 8; -- train
SELECT * FROM events WHERE hash(id, 7) % 10 >= 8; -- test
-- the same thousand rows in the same random order
SELECT * FROM events ORDER BY hash(id, 7) LIMIT 1000;
-- the rows a search finds, in a random order of their own
SELECT * FROM events ORDER BY bm25(body, :q) * 0 + hash(id, 7) DESC LIMIT 10;
```
**`hash(x [, seed])`** is an `INT` from 0 to 263 - 1 that only `x` and `seed` (an `INT`, 0 without one) decide: the same on every machine, in every version of ChloeDB, and on a file and over shards, so a sample or a split made with it is the same rows wherever and whenever it runs. Another seed gives another sample. A `NULL` value or seed gives `NULL`, so a row whose `x` is `NULL` is in no part; hash a column every row holds, such as the key. `x` is one value: text, a number, a `BOOL` or a `TIMESTAMP` (a list is an error). To hash several columns, chain them through the seed: `hash(item, hash(user, 7))`.
It is the 64-bit FNV-1a of the seed's 8 bytes (little-endian) and then the value's, through SplitMix64's finalizer, shifted right by one. A text's bytes are its UTF-8; an `INT`, a `BOOL` (1 or 0) and a `TIMESTAMP` (microseconds since 1970) are their integer's 8 bytes, little-endian; a `FLOAT` is its IEEE 754 bits, little-endian (-0 as 0). So it is the same value elsewhere, in Python for instance:
```python
def chloedb_hash(data: bytes, seed: int = 0) -> int: # data: "u42".encode(), (42).to_bytes(8, "little", signed=True)
m, h = (1 << 64) - 1, 0xcbf29ce484222325
for b in seed.to_bytes(8, "little", signed=True) + data:
h = ((h ^ b) * 0x100000001b3) & m
h = ((h ^ (h >> 30)) * 0xbf58476d1ce4e5b9) & m
h = ((h ^ (h >> 27)) * 0x94d049bb133111eb) & m
return (h ^ (h >> 31)) >> 1
```
In `WHERE`, `hash` is a [condition the indexes cannot answer](#statement-shape): the other conditions narrow the rows by their indexes, and those rows are hashed one by one. `ORDER BY hash(id, 7)` sorts the rows by it, as `ORDER BY lower(name)` or a part of a time sorts them: the rows the table's query finds, in memory. In a [ranking expression](#ranking-expressions) with a score, `hash(field, seed)` of the key or a stored field is the same number, a value of each row the score finds: `bm25(body, :q) * 0 + hash(id, 7)` shows what a search finds in a seeded random order (an arm of an experiment that shuffles its results, or a sample of a search's rows), and a small share of it breaks ties at random. `rrf` does not fuse it. A plan that uses it needs the plan feature `hash`, which shards of a version without the function refuse, and a shard of a version from before it in rankings refuses it there. A [frame](frames.md) samples and splits with it: `frame.sample(fraction=0.1, seed=7)`, `train, test = frame.split(0.8, seed=7)`.
### Places on the Earth: trigonometry, `haversine`, H3 cells and shapes
```sql
-- The 10 fires nearest a point, in kilometres.
SELECT id, haversine(lat, lon, 37.7749, -122.4194) AS km FROM fires ORDER BY km LIMIT 10;
-- A count per H3 cell of resolution 4 (about 1,770 km² each), with each cell's outline to draw.
SELECT h3_cell_to_boundary(h3_latlng_to_cell(lat, lon, 4)) AS cell, COUNT(*) FROM fires GROUP BY cell;
-- The fires inside a shape given as WKT or GeoJSON, and those within 20 km of a point.
SELECT id FROM fires WHERE st_contains(:perimeter, st_point(lon, lat));
SELECT id FROM fires WHERE st_dwithin(st_point(lon, lat), 'POINT(-122.42 37.77)', 20000);
```
ChloeDB has no geometry type: a place is two `FLOAT` columns, or a shape kept as `TEXT`, and these functions compute with them row by row.
- **`sin`, `cos`, `tan`, `cot`, `asin`, `acos`, `atan` and `atan2(y, x)`** are in radians, and **`radians(x)`**, **`degrees(x)`** and **`pi()`** convert, as PostgreSQL's do. `asin` and `acos` of a number beyond -1 to 1 are `NULL` (PostgreSQL's are an error).
- **`haversine(lat1, lon1, lat2, lon2)`** is the great-circle distance between two points given in degrees, latitude first, in kilometres on a sphere of radius 6,371 km, as Snowflake's `HAVERSINE` is to the last digit. Over the Earth's real shape it is within about 0.5% of the truth.
- **The H3 functions** are those of [H3](https://h3geo.org) version 4, the hexagonal grid of the Earth, with Snowflake's names. A cell is an `INT` or its hex text (`'8928308280fffff'`); a resolution is 0 (cells of about 4.4 million km²) to 15 (about 1 m²).
- `h3_latlng_to_cell(lat, lon, resolution)` is the cell holding a point, an `INT`, and `h3_latlng_to_cell_string` the same as text.
- `h3_cell_to_parent(cell, resolution)` is the coarser cell holding it, of the kind its argument is.
- `h3_get_resolution(cell)` is its resolution, and `h3_grid_distance(a, b)` how many steps from cell to cell there are between two cells of one resolution (`NULL` where H3 cannot tell, as across a pentagon).
- `h3_cell_to_point(cell)` is its center and `h3_cell_to_boundary(cell)` its outline, as WKT.
- `h3_int_to_string(cell)` and `h3_string_to_int(cell)` convert, and `h3_is_valid_cell(x)` says whether `x` is a cell.
- **Shapes** are `TEXT` in WKT (`POINT(-122.42 37.77)`, `LINESTRING`, `POLYGON` with holes, the `MULTI` kinds, `GEOMETRYCOLLECTION`, an `SRID=4326;` before it, Z and M values ignored) or GeoJSON (a geometry, a `Feature` or a `FeatureCollection`), with longitude before latitude in degrees (WGS 84), as PostGIS and GeoJSON write them.
- `st_point(lon, lat)` is a point as WKT, and `st_x(p)` and `st_y(p)` its longitude and latitude.
- `st_contains(a, b)` is whether `b` is inside `a` (a point on the outline is not, as in PostGIS), `st_within(a, b)` is `st_contains(b, a)`, and `st_intersects(a, b)` whether they meet at all, outlines included.
- `st_distance(a, b)` is the shortest distance between them in metres, 0 when they meet, and `st_dwithin(a, b, metres)` is `st_distance(a, b) <= metres`.
- `st_area(s)` is a shape's area in square metres.
- `st_astext(s)` and `st_asgeojson(s)` write a shape as WKT or GeoJSON.
Whether shapes contain or meet each other is decided with their edges straight on a flat map of longitude and latitude, as GeoJSON and PostGIS's `geometry` draw them; a shape across longitude 180 is written as two, split there, as GeoJSON asks. Distances and areas are on a sphere of the Earth's mean radius, 6,371,008.8 m, as BigQuery's and Turf's are; PostGIS's `geography` measures on the ellipsoid, within about 0.5%.
Any `NULL` argument gives `NULL`. A text that is not a shape, a cell that is not one and a resolution beyond 0 to 15 are errors that say which. Over one table they are computed row by row, in `SELECT`, `WHERE`, `GROUP BY` and `ORDER BY` (`ORDER BY haversine(…)` is nearest first, and `DESC` farthest), as over joined and derived rows. In a `WHERE` they are a [condition the indexes cannot answer](#statement-shape): give the rows a range of `lat` and `lon` as well (`lat BETWEEN 37 AND 38 AND lon BETWEEN -123 AND -122`) and only the rows in the box are tested. A long shape written out in a query (a perimeter of thousands of vertices) is read once and kept while queries use it, not once per row. A join needs an equality, so to join points to the shapes they fall in, join on a coarse key both have (a region, or an H3 cell the shapes are listed under) and test `st_contains` in the `WHERE`. In a [ranking expression](#ranking-expressions), the trigonometric functions and `haversine` of numeric columns are values of each row the score finds: `bm25(body, :q) / (1 + haversine(lat, lon, :lat, :lon))` ranks a search by its relevance and nearness. A plan that uses any of them but `radians`, `degrees` and `pi` needs the plan feature `geo`, which shards of a version without these functions refuse.
### JSON fields: keys no schema names
A `JSON` field holds an object whose keys are not declared, for attributes that only a few rows have and that nobody knew when the table was made: a product's `voltage`, `certs` or `dims.w`. A row adds keys by holding them, and filters on any key run from the field's index:
```sql
CREATE TABLE products (id KEYWORD PRIMARY KEY, title TEXT, attrs JSON);
INSERT INTO products (id, title, attrs) VALUES
('p1', 'charger', '{"voltage": 5, "certs": ["CE", "UL"], "dims": {"w": 40.5}}'),
('p2', 'lamp', '{"color": "black", "a.b": true}');
SELECT id FROM products WHERE attrs.voltage >= 5 AND attrs.certs = 'UL';
SELECT id, attrs.dims.w FROM products WHERE attrs.color IN ('black', 'red') ORDER BY attrs.dims.w DESC;
SELECT attrs.color, COUNT(*) FROM products GROUP BY attrs.color;
```
- **Paths.** `attrs.dims.w` is the key `w` of the object at `dims`; `attrs['a.b']` names a key that holds a dot, and `json_extract(attrs, 'dims.w')` is the same path as a function, `'$.dims.w'` too, as SQLite and DuckDB write it, in `SELECT`, `ORDER BY` and `GROUP BY` as in `WHERE` (`'$'` is the whole value). **Changed:** 0.3.8 and earlier read a `'$.'` path as `NULL` outside `WHERE`. In a join, qualify the field: `p.attrs.color`. An array holds its elements at its own path, as a multi-valued field does: `attrs.certs = 'UL'` matches `["CE", "UL"]`, and `{"items": [{"sku": "x"}, {"sku": "y"}]}` holds `x` and `y` at `items.sku`. JSON `null` and an empty array are no value.
- **Types.** A comparison sees the values of its literal's type only, as if the path were a column of that type: `attrs.voltage > 5` reads the numbers at `voltage` (integers and doubles alike), `attrs.voltage = 'n/a'` its strings, `attrs.ok` and `attrs.ok = TRUE` its booleans. A row with no value of that type there is `NULL` to the comparison, so `NOT (attrs.voltage > 5)` and `attrs.voltage != 5` leave out rows whose voltage is missing or a string, and `IS NULL` finds rows without the path at all. An `IN` list of several types reads each type for its own values. No row is refused for holding a type other rows do not.
- **Reads.** `SELECT attrs` returns the object as compact JSON text with sorted keys. A path in `SELECT`, `ORDER BY`, `GROUP BY` or an aggregate returns its value, in a column named as the query writes the path (`attrs.dims.w`): a string, an integer, a double or a boolean; a list for an array of values or for several values through an array; an object as its JSON text; `NULL` where the row has none (an empty array included). A list makes a group per value, as a multi-valued column does, and a boolean is a group apart from the number 1.
- **Groups, aggregates and sorts read the index.** `GROUP BY attrs.color`, `AVG(attrs.price)` and `ORDER BY attrs.price` read each row's value from the field's terms, as a declared column's are read, so they take no row's object: a path's counts come from its terms' docID lists, as a facet's do. A row holds one value term per path; where that term is not the whole of the value (an object, an array, a string longer than 256 bytes, a number such as `5.0` or 2^53 + 1 that its term would give as another), the index marks the row, and those rows alone are read from their objects. On a million rows with 1,000 sparse keys (a 4-core cloud VM, [`chloedb/results/json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/json)), `GROUP BY` the most held key takes 2.7 ms, against 2.4 ms for a declared column and 1.9 s when each row's object was read, and `AVG` of a number key held by 82,000 rows 22 ms, against 14 ms and 552 ms. Selecting a path reads it from the objects of the rows returned. A query that mixes paths with what the executor does not run itself (a join, a function of a path, `GROUP BY lower(attrs.color)`) reads them from the rows' objects instead, in memory (up to a million rows), as over [joined rows](#subqueries-with-and-joins); the answer is the same either way.
- **Writes.** A value is a JSON object, given as text (`'{"k": 1}'`), as an object in JSON Lines or the HTTP API, or as a dict from Python; `NULL` is no object. A write is refused, naming the limit, for anything else, for an empty key, and for an object nested more than 16 levels, with a path longer than 256 bytes or with more than 1,000 values and objects. A string longer than 256 bytes is kept and returned, and `IS NOT NULL` sees it, but comparisons do not: its value is not indexed (its words are, with [text](#json-fields-keys-no-schema-names)).
- **Text.** `attrs JSON OPTIONS(text = true)` also indexes the strings of each row's object as text, one a line in path order, long ones included, so `MATCH(attrs, 'charger NOT lamp')` finds rows by the words of any of their strings and `bm25(attrs, 'usb charger')` ranks them as it ranks a `TEXT` field holding the same lines (with a cluster's statistics through a coordinator). Keys, numbers and booleans are not text: a path reads them. The option takes an `analyzer` (`'english'`, the default, or another a `TEXT` field takes), and the text has positions, so a phrase may span two strings that follow each other. A database with such a field needs the feature `json_text` besides `json`.
- **The index** is one sorted dictionary per segment of terms `path \0 type value` (strings as UTF-8, numbers in an order-preserving encoding of doubles), so `=` and `IN` read one term's docID list, a range or `LIKE 'p%'` one run of terms, and `IS NOT NULL` the path's own term. A row pays only for the paths it holds, which is what keeps thousands of sparse keys cheap where as many declared columns would each take a slot in every row. A `JSON` field is stored; it cannot be the primary key, multi-valued, have a default, or be generated or the source of a generated or embedded field. A database with a `JSON` field is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `json`, and plans that read paths carry the plan feature `json`, and `json_columns` when a Search groups, aggregates, orders or selects by them, which a version of ChloeDB from before it refuses by name. A segment written before marks (its section `json..marks` missing) reads every row holding the path from its object, until a merge rewrites it.
#### Which paths a field holds: `json_paths`
Nobody declared the keys, so the table says what they are. `json_paths` lists every path a `JSON` field's objects hold, with how many rows hold each, the types of its values and what they are, read from the field's index (its terms and their docID lists) without reading a row:
```sql
SELECT * FROM json_paths('products', 'attrs');
SELECT * FROM json_paths('products', 'attrs', 'dims'); -- dims and the paths below it
SELECT * FROM json_paths('products', 'attrs', filter => 'MATCH(title, ''charger'')');
```
For the two rows above, the first gives:
| path | rows | share | strings | numbers | bools | min | max | distinct | values |
|---|---|---|---|---|---|---|---|---|---|
| `a\.b` | 1 | 0.5 | 0 | 0 | 1 | | | 1 | `[[true,1]]` |
| `certs` | 1 | 0.5 | 1 | 0 | 0 | | | 2 | `[["CE",1],["UL",1]]` |
| `color` | 1 | 0.5 | 1 | 0 | 0 | | | 1 | `[["black",1]]` |
| `dims` | 1 | 0.5 | 0 | 0 | 0 | | | 0 | `[]` |
| `dims.w` | 1 | 0.5 | 0 | 1 | 0 | 40.5 | 40.5 | 1 | `[[40.5,1]]` |
| `voltage` | 1 | 0.5 | 0 | 1 | 0 | 5.0 | 5.0 | 1 | `[[5,1]]` |
- **A row per path**, in path order, a key's dot escaped (`a\.b`). `rows` counts the rows that hold the path at all (an object there counts), `share` is their share of the rows read, and `strings`, `numbers` and `bools` count the rows holding a value of each type, so a path whose rows disagree on its type says so. `min` and `max` are its numbers' range; `distinct` counts its values, and `values` lists them as JSON with their rows, most first, when there are at most 100 (past that both are `NULL`).
- **The third argument** narrows the listing to a path and the paths below it (`'dims'`, `'$.dims'`, `'a\.b'`). **`filter =>`** counts only the rows a condition keeps, any condition a `WHERE` could hold: `json_paths('products', 'attrs', filter => 'attrs.color IS NOT NULL')` tells which other keys the rows with a color have.
- **The listing is read whole**: `SELECT *` and nothing else, at most 10,000 paths (past that, the first 10,000 in order). A string longer than 256 bytes is not indexed, so it counts at its path in `rows` but in no type. Rows deleted or updated count as they are now.
- **Over HTTP**, `GET /v1/tables/T/paths?field=attrs&path=dims&where=...` gives the same as JSON, each path with its `keys`, and a [coordinator](server.md#sharding-one-coordinator-many-shards) sums its shards' listings, so the counts are the cluster's. The [command center](server.md#the-ui) draws the listing as a tree in **Schema**, completes `attrs.` in the workbench with the keys at each level, and lists the paths in the query builder as fields to filter, group, measure and sort by.
## Some of the conditions: `AT_LEAST`
`AT_LEAST(n, c1, c2, …)` holds where at least `n` of the conditions do. A condition is anything `WHERE` takes: a comparison, `IN`, `IS NULL`, `MATCH`, a graph predicate, a subquery condition, a group in parentheses, another `AT_LEAST`.
```sql
-- two of three signals, ranked by the text
SELECT id, title FROM papers
WHERE AT_LEAST(2, MATCH(title, 'covid'), year >= 2020, venue IN ('nejm', 'lancet'))
ORDER BY bm25(body, :q) DESC LIMIT 20;
-- rows meeting more of the conditions rank higher
SELECT id FROM papers
ORDER BY bm25(body, :q) * (1 + 0.1 * count_true(year >= 2021, venue IN ('nejm', 'lancet', 'jama'))) DESC LIMIT 20;
```
- **`n`** is a count, a percentage of the conditions (`'75%'`, rounded down) or a parameter (`:n`), 1 or more (`0` and `'0%'` are errors: none of the conditions is no condition). Either is clamped to between 1 and the number of conditions, as [`MATCH`'s groups](#full-text-match) are: `AT_LEAST(1, …)` is the `OR` of the conditions, and a count past the end is their `AND`.
- **`NULL`.** A condition that is UNKNOWN (a comparison with a `NULL`) is not met. Under `NOT`, `AT_LEAST` follows SQL's three-valued logic: `NOT AT_LEAST(n, …)` holds where fewer than `n` conditions would be TRUE even if every UNKNOWN one were, so it never returns a row whose answer depends on a `NULL`. With `a = 1` and `c` `NULL`, `AT_LEAST(2, a > 0, c = 'x')` leaves the row out, and so does `NOT AT_LEAST(2, a > 0, c = 'x')`.
- **`count_true(c1, c2, …)`** is how many of the conditions hold, a number for [ranking expressions](#ranking-expressions) and `SELECT`, exactly the sum of `CASE WHEN c THEN 1 ELSE 0 END` over them: a condition on a `NULL` counts 0. In a `SELECT` over rows in memory (a join, a `WITH` result) its conditions cannot use `MATCH` or graph predicates, which only a table's indexes answer.
- **How it runs.** Each condition becomes the set of rows it holds for, as `WHERE` evaluates it, and a counter adds the sets up 64 rows to a machine word, in ⌈log2(y + 1)⌉ words for each 64 rows; sets with few rows are merged instead. A ranking that checks its candidates one at a time tests their conditions in turn, until the count is reached or out of reach. The cost grows with the number of conditions, not with `n`: over 1,000,000 rows where each condition holds for an independent 20% of them, counting the rows took 3.0 ms for 2 of 4 conditions, 4.1 ms for 4 of 8 and 9.3 ms for 8 of 16, against 0.37 ms for one condition. The same conditions written as an `OR` of every `AND` of `n` took 8.2 ms for 2 of 4 (6 `AND`s) and 114 ms for 4 of 8 (70), and 8 of 16 would need 12,870 (`chloedb-at-least-bench` on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/strata/at_least.json`).
- A plan with `AT_LEAST` or `count_true` needs the plan feature `at_least`. From Python, [`at_least(2, match("title", "covid"), col("year") >= 2020)`](python.md#queries-built-in-python) and `count_true(…)` build them.
## As many as fit: `min_rows` and `max_rows`
An "x of y" condition can choose its own x. With `max_rows` or `min_rows`, an `AT_LEAST`, a `MATCH(…, min => n)` or a `bm25(…, min => n)` asks for all y of its items first, and relaxes towards `n` while the rows are too few, stopping before a level that would match more than `max_rows`:
```sql
-- as many of the signals as keep the candidates to 2,000 or fewer
SELECT id, title FROM papers
WHERE year >= 2015 AND AT_LEAST(2, MATCH(title, 'covid'), venue IN ('nejm', 'lancet'), cited > 100, max_rows => 2000)
ORDER BY bm25(body, :q) DESC LIMIT 20;
-- all four words if 50 rows have them, else three, else two
SELECT id, score() FROM docs
ORDER BY bm25(body, 'mrna vaccine trial phase', min => 2, min_rows => 50) DESC LIMIT 10;
```
- **The bounds** are counts of rows, 1 or more, and `min_rows` is at most `max_rows` (else no level could meet both, an error).
- **The level.** From the strictest level, all y items, a guard relaxes one item at a time while the level matches fewer than `min_rows` rows and the next looser one no more than `max_rows`, down to `n`. With `max_rows` alone that is the loosest level that fits, and with `min_rows` alone the strictest with enough rows. If even all y match more than `max_rows`, the query runs at y. The rows counted are those the rest of `WHERE` keeps; `LIMIT` does not cut them.
- **Where.** A guard is an `AT_LEAST` or a `MATCH` joined to the rest of `WHERE` by `AND` (not one under `OR`, `NOT` or another condition), or a `bm25` of the first ranking of `ORDER BY`. `MATCH` and `bm25` need a `min`, the loosest level; `AT_LEAST`'s is its `n`. A query has one guard at most, and a [rerank phase](#rerank-phases) none. A `SELECT` over a `WITH` result that is not a rerank phase counts that result's rows.
- **The plan line** gives each level's rows and the level chosen: `guard: AT_LEAST 3 of 4 (4: 12, 3: 340, 2: 5120, 1: 23000; max_rows 2000)`.
- **Its cost** is counting the rows of every level, over all the rows the rest of `WHERE` keeps, before running at one: a guarded query costs about what counting its matches does, whatever its `LIMIT`. Over 1,000,000 rows where each condition holds for an independent 20% of them, `AT_LEAST(1, …, max_rows => 10000) LIMIT 100` took 2.5 ms over 4 conditions, 6.1 ms over 8 and 11.6 ms over 16, against 0.25, 0.51 and 0.98 ms for the same query written at the level chosen. For four words of different frequencies, over rows of 12 words drawn by Zipf's law from 5,000, `bm25(body, …, min => 1, max_rows => 1000)` took 2.4 ms at the median of 50 queries (`LIMIT 10`), against 1.4 ms at the level chosen and 0.75 ms without `min`, and a `MATCH` guarded alike 2.3 ms against 1.3 ms. A text's words are counted once each, as `AT_LEAST`'s conditions are, unless it has required or excluded words, when each level is counted in turn (`chloedb-guard-bench` on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/strata/guard.json`).
- **What it keeps.** BEIR's queries are sentences, and few rows hold all of a sentence's words. On five BEIR collections the top 100 rows by `bm25(body, :q, min => '100%')` held 0.03 to 0.40 of the relevant rows (recall@100), against 0.13 to 0.97 for any of the words; `min => 1, min_rows => 100`, all the words while 100 rows have them, else as many as 100 rows have, held 0.10 to 0.96, within 0.4 to 7.7 points of any word, with nDCG@10 within 0.013 of it, at a median of 0.15 to 2.05 ms a query, 0.8 to 1.6 times the any-word query's (`chloedb-bm25-eval`, the `_r100` variants, 3 runs each on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/text/bm25_guard.json`).
- **Over shards**, a coordinator first asks every shard for its counts (protocol 8, so a shard of an older server is refused by name), adds them up, chooses the level as one database would, and sends the shards the query at that level: one round more. A shard answering a coordinator runs the level it is sent, never one of its own. With rows like those above split over 4 shards on one machine, the guarded `AT_LEAST` of 4, 8 and 16 conditions took 4.3, 7.4 and 12.6 ms through the coordinator (1.6, 2.6 and 1.8 ms at the level chosen) against 2.3, 3.9 and 7.7 ms on one database, and the guarded `bm25` 4.3 ms against 1.7 ms, medians of 50 queries (`chloedb-guard-shards-bench`, the same VM, `chloedb-server/results/guard/shards-4.json`).
- A plan with a guard needs the plan feature `guard`. From Python, `at_least(2, …, max_rows=2000)`, `match(field, query, min=2, max_rows=500)` and `bm25(field, text, min=2, min_rows=50)`.
## Full text: `MATCH`
`MATCH(field, query)` is a boolean predicate. The query grammar follows SQLite FTS5:
```text
query := and ("OR" and)*
and := unary (["AND"] unary)* juxtaposition is AND
unary := ("NOT" | "-") unary | primary "a NOT b" is "a AND NOT b"
primary := "(" query ")" ["@" n | "@" p "%"] | ("\"phrase\"" | word | word* | word~ | word~N) ["^" weight]
```
| query | matches |
|---|---|
| `vaccine mrna` | both words (juxtaposition is `AND`) |
| `vaccine OR vaccination` | either |
| `vaccine -animal`, `vaccine NOT animal` | the first without the second |
| `"messenger rna"` | the phrase (needs positions on the field) |
| `vacc*` | every indexed term with that prefix |
| `vacine~`, `vacine~1` | the word and the indexed terms an edit or two from it ([typos](#typos-and-synonyms)) |
| `vaccine AND (mrna OR "messenger rna") -animal` | any combination, with parentheses |
| `(mrna vaccine trial phase)@2`, `(…)@50%` | at least 2 of the group's items, or half of them |
Operators are uppercase; lowercase `and`, `or` and `not` are ordinary words (and stopwords). Parentheses and `NOT`s nest at most 100 deep. Words and phrases are analysed like the field's documents, by its [analyzer](#tables): a word that analyses to several terms (`e-mail`) becomes a phrase, and one that analyses to none (a stopword) is dropped. A prefix is lowercased and folded, and matches the indexed terms that start with it and the stems of the words it may be the start of that do not: the stem of the prefix as a word (`battery*` takes `batteri`, the stem of *battery* and *batteries*) and, with `english`, the stems of the prefix completed by a common ending, whole or the rest of one already begun (`runni*` takes `run`, for *running*). Those are looked up as whole terms, not as prefixes, so `cart*` does not take `car`. **Changed:** a prefix matched only the terms that start with it before, so `battery*`, `headphone*` and `running*` found nothing where every letter typed before them found the rows. A weight (`vaccine^2`, `"messenger rna"^0.5`) is read and ignored, since `MATCH` only says whether a row matches: `vaccine^2 mrna` matches what `vaccine mrna` does, so one text can go to both `MATCH` and [`bm25`](#weights-required-and-excluded-words). A weight of 0 is read and ignored too, while `bm25` scores nothing for that word. A `^` before something that starts like a number but is not a weight (`vaccine^1e308`, `vaccine^-1`, `vaccine^2x`), and a `~` with more than 2 typos (`apple~9`), are errors in `MATCH`, where they would otherwise be searched as words; `bm25` reads its text leniently, and there they are words.
**A prefix filters; it does not score.** `bm25` scores a text's whole words and passes over its prefixes (`bm25(name, 'leather sof*')` scores `leather` alone), so a query ranked by `bm25(name, 'sof*')`, which has no whole word, returns no row, even where `MATCH(name, 'sof*')` keeps many, and neither does a ranking expression with it in (`bm25(name, 'sof*') + rating`). For search as you type, filter by what was typed with its last word as a prefix and rank by the words typed whole, or, while the first word is still being typed, by a column:
```sql
-- typed "lether so": the prefix in MATCH, the whole words in bm25 (with the same fuzzy, given again)
SELECT id, name FROM products WHERE MATCH(name, 'lether so*', fuzzy => 'auto') AND in_stock
ORDER BY bm25(name, 'lether', fuzzy => 'auto') * (1 + 0.1 * rating) DESC LIMIT 10;
-- typed "so": no whole word yet
SELECT id, name FROM products WHERE MATCH(name, 'so*') AND in_stock ORDER BY rating DESC, id LIMIT 10;
```
A `bm25` takes its `MATCH`'s `fuzzy` only when its text is the `MATCH`'s ([typos](#typos-and-synonyms)), so here it names its own. A `KEYWORD` field of whole values (a product's name, a past query) completes with [`PREFIX`](#prefixes-and-autocomplete) instead, ordered by a column.
**What a visitor typed: `syntax => 'plain'`.** A search box's text is seldom written in this grammar, and a stray quote, bracket or sign in it (`"soup`, `soup (easy`, `soup)`, `soup -`) is an error that says what is wrong (`MATCH query "soup)" has a ) without its (`). `MATCH(name, :q, syntax => 'plain')` reads the text as words alone: each run of it between spaces a word (several words, `t-shirt`, as a phrase), all of them needed, none of it an operator, so `-easy` is the word *easy* and `OR` the word *or*; a text of no words matches nothing. It takes `fuzzy`, `synonyms` and `min` as the query syntax does, and a [`bm25`](#bm25field-text) of the same text on the same field reads it as plain words too. `syntax => 'query'` is the default. **Changed:** `MATCH` refused `syntax` before, and its errors named the parser's tokens (`unexpected RParen in MATCH query`).
```sql
SELECT id, name FROM recipes WHERE MATCH(name, :q, syntax => 'plain', fuzzy => 'auto') ORDER BY bm25(name, :q) DESC LIMIT 10;
```
A group with `@n` matches a row with at least `n` of its items: its operands, whether juxtaposed, joined by `AND` or by `OR`, each a word, a phrase, a prefix, a typo-tolerant word or a parenthesised query (`vaccine AND (mrna "messenger rna" trial~ (phase OR stage))@2`). A negated item (`-animal`) is not counted: the row must not have it. An item written twice is one item, as in `bm25`'s `min` (`(apple apple cherry)@2` needs both words), and so are words that analyse to the same term. A stopword is not an item, and a word's synonyms and typo neighbours count as it does. `@p%` asks for p percent of the items, rounded down; a count or percentage of 0 is an error, and either is clamped to between 1 and the number of items, as Lucene's `minimum_should_match` is, so `@1` is any of them and a count past the end is all of them. `MATCH(body, 'a b c d', min => 2)` (or `min => '75%'`) treats the whole query as one group. A group nests anywhere a parenthesised query does. A group reads each item's matches once, so it costs about what an `OR` of its items does.
## Prefixes and autocomplete
`kw LIKE 'p%'` and `PREFIX(kw, 'p')` select the rows of a `KEYWORD` field whose value starts with `p`, byte for byte (no case folding). A field's values are sorted in its dictionary, so the values with a prefix are one run of it, found by two binary searches per segment: a short run unions its values' lists, and one of more than 1,024 values of a single-valued field scans the code column, as a range of numbers does. A multi-valued field matches a row when one of its values starts with the prefix, and `NOT` when none does.
A single-valued `KEYWORD` compares by order too, byte for byte as `ORDER BY` sorts it: `id > 't007-006015'`, `id <= :last`, `id BETWEEN 'a' AND 'm'` are one run of the dictionary each, as a prefix is, and a row without a value is `UNKNOWN` to them. So a keyset page of `ORDER BY created_at DESC, id` starts after the last row of the one before with `WHERE created_at < :at OR (created_at = :at AND id > :id)`. A `KEYWORD[]` keeps to `=`, `IN` and prefixes. A plan with such a comparison names the feature `keyword_ranges`, which a server from before it refuses. **Changed:** an order comparison of a `KEYWORD` was refused before.
```sql
-- autocomplete: the ten most asked queries that start with what was typed
SELECT id, n FROM queries WHERE PREFIX(id, :typed) ORDER BY n DESC, id LIMIT 10;
-- a user's own history first: keys of the form '|'
SELECT id, n FROM user_queries WHERE PREFIX(id, 'u42|how to') ORDER BY n DESC LIMIT 3;
-- with typos: 'hwo to ins' still finds 'how to install'
SELECT id, n FROM queries WHERE PREFIX(id, :typed, fuzzy => 'auto') ORDER BY n DESC, id LIMIT 10;
-- the same, exact completions first, then those one edit away, then two
SELECT id, n FROM queries WHERE PREFIX(id, :typed, fuzzy => 2)
ORDER BY CASE WHEN PREFIX(id, :typed) THEN 2 WHEN PREFIX(id, :typed, fuzzy => 1) THEN 1 ELSE 0 END * 1000000 + n DESC LIMIT 10;
SELECT id FROM files WHERE path LIKE 'src/query/%' AND path NOT LIKE 'src/query/ir/%';
```
- `LIKE` on a table's own `KEYWORD` field reads its index for a value (no wildcard: `=`) or text followed by `%`. Another pattern (`_` anywhere, or `%` before the end) and `LIKE` on a `TEXT` field test each row the other conditions keep, as over joined or derived rows. A field with a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) answers every pattern from it.
- `ESCAPE 'c'` makes the character after `c` literal: `LIKE 'snake!_%' ESCAPE '!'` is the prefix `snake_`. `PREFIX` needs no escaping.
- `ILIKE` tests each row the other conditions keep. To find values in any case among many rows by an index, give the field a [substring index](#substrings-like-and-ilike-anywhere-in-a-value), or store the value lowercased (and a display form beside it) and use `LIKE`.
- `PREFIX(x, p)` also works over joined or derived rows, as a test of each value; `PREFIX(kw, '')` and `LIKE '%'` are `IS NOT NULL`.
- **`PREFIX(kw, p, fuzzy => 1 | 2 | 'auto')`** also selects the values that start with a prefix within that many edits of `p` whose first letter is `p`'s own, with the edits `MATCH` counts ([typos](#typos-and-synonyms)); `'auto'` goes by `p`'s length, as it does for a word: none up to 2 letters, 1 up to 5, else 2. The dictionary is walked as a trie, one row of the edit-distance table per letter, jumping past every value whose start is already too far from `p` and past the whole run of a start close enough, so the cost follows the values near what was typed rather than the dictionary's size. The values found are a few runs of the dictionary, read as an exact prefix's one is. A value's edits are the fewest of any of its prefixes, so a completion of `p` itself has none even when a shorter prefix is also close enough. Typo matches rank by the `ORDER BY` like exact ones; to rank completions by their edits, exact ones first and each tier by its count, put the tiers in the ranking expression: `ORDER BY CASE WHEN PREFIX(id, :typed) THEN 2 WHEN PREFIX(id, :typed, fuzzy => 1) THEN 1 ELSE 0 END * 1000000 + n DESC` (the factor larger than any count). `LIKE` takes no typos.
- Counts kept with `UPDATE ... SET n = n + 1` or a write's `add` change in place, so a query log's popularity stays current without rewriting rows.
A plan with a prefix needs the plan feature `prefix`, and one with typos also `prefix_edits`, so a shard of an older version refuses it rather than misreading it. The same run of the dictionary answers [semantic-ID next codes](server.md#semantic-ids).
**Cluster a completion table by its key.** `ORDER BY n DESC LIMIT 10` reads the count column's blocks best first ([ordering by a column](#a-column)), and with `OPTIONS(cluster_by = 'id')` a prefix's rows sit together in each segment, so the ten most asked queries under a prefix read about ten blocks whatever the prefix's length:
```sql
CREATE TABLE queries (id KEYWORD PRIMARY KEY, n INT) OPTIONS(cluster_by = 'id');
```
Over ORCAS's 10.4 million queries, loaded in no particular order and merged by the default policy (11 segments), 2,000 typed queries drawn by clicks, one thread on a 4-core cloud VM (Intel Xeon @ 2.10GHz), p99 in ms:
| characters typed | 1 | 2 | 3 | 4 | 6 | 8 | 12 |
|---|---:|---:|---:|---:|---:|---:|---:|
| rows matching (median) | 560,354 | 64,887 | 9,461 | 2,418 | 415 | 68 | 6 |
| every match read | 46.7 | 25.4 | 18.2 | 17.1 | 9.9 | 9.1 | 2.6 |
| blocks best first | 9.5 | 13.0 | 8.8 | 9.7 | 6.3 | 6.5 | 2.6 |
| blocks, clustered by `id` | 0.27 | 0.53 | 0.48 | 0.38 | 0.35 | 0.33 | 0.28 |
The full runs, with medians and the 105 segments straight after the load, are [`results/text/complete-orcas.json` and `complete-orcas-clustered.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/text) (`chloedb-complete-bench`).
Typos cost the walk of each segment's dictionary, which finds each value's fewest edits. On the same clustered table, the median top 10 with `fuzzy => 'auto'` takes 1.9 ms at 3 letters and 2.7 ms at 4, where it allows one edit, and 8.2 to 11.9 ms from 6 letters, where it allows two (p99 up to 24 ms); with `fuzzy => 1` it takes 3.3 to 4.1 ms from 6 letters (p99 up to 8.5 ms). Up to 2 letters `'auto'` allows none, so it costs what an exact prefix does. Straight after a load, with 105 segments, the same queries take 2.7 to 3.9 times as long. Ranked exact completions first (the `CASE` above), the median is 5.1 to 15 ms from 2 letters and 28 ms at 1 (p99 up to 62 ms), since a ranking expression is not a column whose blocks can be read best first: every completion is ranked. Results: `complete-orcas-clustered-fuzzy.json`, `complete-orcas-clustered-fuzzy1.json` and `complete-orcas-clustered-fuzzy-exact-first.json` (one thread of the 4-core cloud VM, Intel Xeon @ 2.10GHz).
## Substrings: `LIKE` and `ILIKE` anywhere in a value
A `TEXT` or `KEYWORD` column declared with `OPTIONS(substring = true)` gets a substring index, and `LIKE` and `ILIKE` on it are answered from that index, whatever the pattern. It finds what `MATCH` cannot, because it has no tokenizer: part of a word, an IP address, a path, an identifier, punctuation, text in a script the analyzer does not split.
```sql
CREATE TABLE logs (
id INT PRIMARY KEY,
ts TIMESTAMP NOT NULL,
host KEYWORD OPTIONS(substring = true),
body TEXT OPTIONS(substring = true)
);
SELECT ts, body FROM logs WHERE body LIKE '%173.234.31.186%' ORDER BY ts DESC LIMIT 20;
SELECT count(*) FROM logs WHERE body ILIKE '%break-in attempt%' AND ts >= '2026-11-01';
SELECT id FROM logs WHERE body LIKE '%Failed password%from 119.4.203.64%' AND host NOT LIKE '%.internal';
```
- **The answer is the one a test of every row gives.** `%` is any run of characters and `_` one character; `LIKE` compares byte for byte, and `ILIKE` compares both sides lowercased a character at a time, as PostgreSQL does and as it does [over joined or derived rows](#subqueries-with-and-joins): a capital `Σ` matches `σ` and the final `ς` wherever it stands, and a capital `İ` is one `i` . A row without a value matches neither a pattern nor its `NOT`, and a NULL pattern (`LIKE :p` with `:p` NULL) matches no row, nor does its `NOT` . The index only changes how long the answer takes.
- **How it answers.** Each segment holds an FM-index of the field's values: the Burrows-Wheeler transform of their bytes in a wavelet tree, with a sample of the suffix array that says which row a match is in. Counting the places a string occurs takes time by the string's length, not by the table's size, and each row found then costs one to a few microseconds. A pattern with one string (`'%lit%'`, `'lit%'`, `'%lit'`, `'lit'`) is answered from the index alone, under `LIKE` and `ILIKE` : `ILIKE` searches the spellings that exist (`error`, `Error`, `ERROR`), not every combination of cases. A pattern with several strings (`'%a%b%'`) or with `_` takes its candidates from the string that occurs least and tests their stored values, read in the order the table keeps them. A `LIMIT` without an `ORDER BY` on such a column stops at the first rows it needs .
- **A pattern in too many rows reads the values instead.** Where a string occurs in more than about one row for every 2 KiB of a segment's stored rows (4 KiB where each candidate's value is tested), listing its rows from the index would cost more than testing each value, so the query tests the values, as a table without the index does. The rows count whole, since a test reads them whole: a title that is a sixth of its row is listed up to six times as often before the values are read. Beside conditions that leave few rows (`pid = 24200 AND body LIKE '%e%'`), the pattern is tested on those rows' values alone, whichever of the two the index's counts say is cheaper.
- **What the column must be**: one value per row and stored (the stored values answer for rows not yet in a segment's index, and for the candidates above). It need not be searched by `MATCH`: `body TEXT OPTIONS(substring = true, indexed = false)` keeps only the substring index. `ALTER TABLE ... ADD COLUMN` takes the option. In JSON it is `"substring": true`.
- **A `KEYWORD` column's value or prefix** (`LIKE 'abc'`, `LIKE 'abc%'`) still reads its dictionary, which is faster, and takes `ESCAPE`. A pattern the substring index answers does not take `ESCAPE`.
- **Rows just written** are tested by their values until a flush writes their segment; a segment gets its index when it is flushed or merged.
- **What it costs.** On three logs of 0.7 to 4.7 million lines the index took 0.94 to 1.02 of the bytes of the text it indexes, which made the file 1.8 to 2.3 times as large; loading took 1.3 to 2.6 times as long and a merge 2.2 to 3.6 times, since each segment's index is built when it is flushed and again when it is merged. A pattern in few rows took 0.02 to 2 ms where a test of every row took 0.6 to 4 s, and a pattern in very many rows a sixth to an eighth of that test ([`results/substring`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/substring), on a 4-core cloud VM, Intel Xeon @ 2.10GHz).
- It makes the database [file format 3](index.md#wal-memtable-and-snapshots) with the feature `substring:1`, which a version of ChloeDB from before it refuses by name. The format is specified in [`chloedb/notes/substring.md`](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/notes/substring.md).
## Scores
Each function below takes the options its section lists, as `name => value`. An option it does not take, or a value it cannot (`k1 => 'x'`, `b => 2`, `ef => 'x'`), is an error that lists the options it takes: `unknown option bogus for bm25: k1, b, algo, ...`. **Changed:** such an option was ignored before, so a misspelt one (`fuzy => 1`) gave an answer as if it had not been written.
### `bm25(field, text)`
BM25 of the analysed terms of `text`, disjunctively: a row scores if it contains any of them, unless the text [requires or excludes words](#weights-required-and-excluded-words). Ranked queries drop English function words (NLTK's 153-word list), except that its single letters (`d`, `m`, `o`, `s`, `t`, `y`) are kept unless they end a contraction: "vitamin d" and "T cell" keep their letter, "don't" and "it's" drop it. A term written twice weighs twice. Used in `ORDER BY` without a `MATCH`, it is a ranked search; with one, it ranks the matching rows.
| option | default | effect |
|---|---|---|
| `k1`, `b` | 1.2, 0.75 | BM25 parameters (`k1 >= 0`, `0 <= b <= 1`) |
| `algo` | planner's choice (MaxScore) | `'maxscore'`, `'bmw'` (Block-Max WAND) or `'exhaustive'` |
| `stopwords` | 1 (0 on a `simple` field) | `0` keeps English function words in the query, `1` drops them |
| `fuzzy` | 0 | `1`, `2` or `'auto'`: also score the indexed terms that many edits from each word; `'auto'` corrects only the words that look like typos ([typos](#typos-and-synonyms)) |
| `synonyms` | 0 | `1`: also score each word's synonyms |
| `syntax` | `'query'` | `'plain'` reads `+`, `-`, quotes and `^` as punctuation: the text is words alone; `'terms'` reads analysed terms, each weighted by `^w`, as they are written ([query expansion](#query-expansion-expand)) |
| `min` | none | `n` or `'p%'`: rank only the rows with at least that many of the text's optional words and phrases |
| `expand` | 0 | `n`: also rank by the terms the query's top `n` rows hold most ([query expansion](#query-expansion-expand)), with `expand_terms` (20) and `expand_weight` (0.85) |
Keeping function words is better for short questions: on Quora it gains 0.055 nDCG@10, while on TREC-COVID, whose queries are full questions, dropping them gains the same amount.
#### Weights, required and excluded words
The text may weigh a word, require it or exclude it, as a search box does:
| text | ranks |
|---|---|
| `vaccine mrna` | the rows with either word |
| `vaccine^2 mrna` | the same rows, `vaccine` weighing twice: as `vaccine vaccine mrna` |
| `+mrna vaccine` | the rows with `mrna`, by both words |
| `vaccine -animal` | the rows with `vaccine` and without `animal` |
| `+"messenger rna" vaccine^0.5` | the rows with the phrase (with both words, on a field without positions), by its words and half of `vaccine` |
| `+covid^0 treatment` | the rows with `covid`, by `treatment` alone |
| `vacc* trial` | the rows with a word that begins `vacc`, or with `trial` |
| `vacine~ trial`, `vacine~1` | the rows with a word an edit or two from `vacine`, or with `trial` |
- **`^w`** after a word or a closing quote multiplies its terms' BM25 by `w`, a number of at least 0 (`2`, `0.5`, `.5`). Weights add up, as a word written twice does. A word weighing 0 scores nothing, and a text whose words all weigh 0 ranks no row.
- **`+`** before a word or a quoted phrase requires it, **`-`** excludes it: a row must contain every required one and none of the excluded ones, and ranks by the others too. An excluded word does not score, and a word the query drops as a stopword is neither required nor excluded. A sign counts only at the start of a word and before a letter, digit or quote: `covid-19`, a `-` alone, `+-x` and `x^` are words. Quotes alone change nothing: `"messenger rna"` scores what `messenger rna` does.
- **`word*`** ranks by the words of the field that begin with `word`, as `MATCH`'s prefix matches them (lowercased and folded, with the stems of the words it may begin), scored as one word whose document frequency is the largest of theirs, as a typo's neighbours are. When more than 128 words begin so, the 128 in the most rows score, and the plan says so: `bm25 vacc*: the 128 terms in the most rows, of the 412 it begins`. **`word~`** and **`word~1`**, **`word~2`** rank by the word and the words within that many edits, as `fuzzy` does for one word (`~` alone goes by its length, as `'auto'` does). Both take signs and weights (`+vacc*^2`), and with `syntax => 'plain'` both are words as written. So `ORDER BY bm25(title, :typed) DESC` with `:typed` = `'sof*'` ranks the rows `MATCH(title, 'sof*')` keeps, for search as you type. **Changed:** `bm25` read `vacc*` and `vacine~` as the words `vacc` and `vacine` before, which ranked no row where `MATCH` found some.
- With `fuzzy` or `synonyms`, a word's typo neighbours and synonyms take the highest weight the word is written with (writing it twice weighs the word twice, not them), and a required or excluded word counts as present when one of them is, as in `MATCH`.
- A required or excluded word is a filter on the ranked rows: the top-k loop (all three `algo`s), a [rank-safe boost](#rank-safe-boosts), a [rerank phase](#rerank-phases) (where a row the filter drops scores 0, as one without the words does) and shards all apply it, so the rows and scores are those of the rows the text allows.
- Weights and signs cost little. With each query's first word weighed 2 (`word^2`) or required (`+word`), or its last word excluded (`-word`), the median query took 0.27, 0.28 and 0.23 ms on Quora's 10,000 queries against 0.25 ms for the plain text, and 0.24, 0.18 and 0.22 ms on FiQA against 0.22 ms; a required word can make a query faster, as the filter drops rows before they are scored. Text written without operators ranks and times as the plain text does on all five collections measured (`chloedb/results/text/bm25_term_operators.json`, one core of a 4-core cloud VM while another job held the other three). The operators were put on words mechanically to time them, so these queries rank worse than the plain text: an operator helps when it says what the person searching means.
- **`min => n`** (or `'p%'`) ranks only the rows with at least `n` of the text's optional words and phrases: those without a sign, each counted once however often it is written, whatever its weight (`^0` counts too). Required and excluded words are not counted; a text without optional words ignores `min`. Counts are clamped to between 1 and the number of optional words, and a percentage rounds down, as in `MATCH`'s groups: `bm25(body, 'vaccine mrna trial phase', min => 2)` ranks the rows with two of the four words, by all of them. With `syntax => 'plain'`, each word is an optional word.
- `min` filters the ranked rows, as a required word does, so its cost depends on how many rows hold one of the words. With `min => 2` the median query took 0.24 ms on Quora's 10,000 queries (0.25 ms plain) and 0.41 ms on FiQA (0.23 ms plain). On TREC-COVID, whose query words appear in most of its documents, it took 1.6 ms (0.5 ms plain), because the filter counts every row that holds one of the words (`chloedb/results/text/bm25_min_match.json`, one core of a 4-core cloud VM while another job held the other three). `min` is for leaving rows out, not for ranking better. Asking every BEIR query for two of its words, or half of them, left nDCG@10 unchanged on TREC-COVID and lowered it elsewhere, by as much as 0.077 (SciFact, half the words).
- **`syntax => 'plain'`** reads the text as words alone, as `bm25` did before: for text not written for a search box, such as a user's message passed through, or a benchmark's recorded queries. BEIR's hold `+1`, `-word` or `x^2` here and there, so the evaluations and benchmarks in this repository pass `syntax => 'plain'`, and so does ChloeCtx.
- A plan that ranks with weights, signs, prefixes or typos (`word*`, `word~`; a shard from before them, which takes `text_operators`, reads them as words, so finish an upgrade before relying on them), or a `MATCH` with weights, needs the plan feature `text_operators`, and one with `min` or a `MATCH` group `(…)@n` needs `min_match`. From Python, `bm25("body", "+mrna vaccine^2")` reads them, `bm25("body", text, syntax="plain")` does not, and `bm25("body", text, min=2)` and `match("body", text, min="75%")` ask for some of the words.
**Changed:** `bm25` read `+`, `-`, `"` and `^` as punctuation before; text with them now ranks as above, and `syntax => 'plain'` keeps the old reading. In `MATCH`, `^` separated words: `vaccine^2` matched `vaccine` and `2`, and now matches `vaccine`; and `)@2` closes a group a row needs 2 of, where `@2` was a word before.
### `similarity(field, vector)` and `distance(field, vector)`
The dot product (cosine for unit vectors) and the Euclidean (L2) distance between a row's vector and the query vector, which is a bound parameter or a JSON array of the field's dimension.
**Text instead of a vector.** On a field a model embeds (`OPTIONS(embed = 'body', model = '...')`), the second argument may be text, a literal or a parameter that holds text: `ORDER BY similarity(emb, 'how do I reset my password') DESC`, or `similarity(emb, :q)` with `:q` bound to a string. The text is embedded as a query by the field's own model when the query is planned, once however often the query repeats it, and the query runs as if its vector had been given (`distance` and `maxsim` take text the same way; on a multi-vector field the text is its tokens' vectors). `similarity(emb, embed(:q))` says the same. In a [rank profile](#rank-profiles-a-ranking-kept-with-its-table) too, on chloedb-server: one text parameter feeds both `bm25(title, :q)` and `similarity(emb, :q)` (the profile written out, its texts embedded, the plan still naming the profile). A string that is a JSON array of numbers is still a vector, and a `SPARSE` field's terms are still text.
**`embed('model', text)`** is the query vector of a text by the model named, wherever a vector goes: against a field of no model, `similarity(raw, embed('potion-base-8M', :q))`, or in a projection, `SELECT id, embed('potion-base-8M', 'tents') AS v FROM docs`. The model is one an embedded field uses, `hash:N`, or a directory directly under the models directory, named as `llm()` names one (letters, digits, `_`, `-` and `.`, never a path; `chloedb-server fetch-model` fetches the known ones). A model behind an API (`openai/...`, an `endpoint.json`) is taken only when a field uses it, so that a query spends no key a table was not given. The text is a value or a parameter, not a column: the model runs once a query, not once a row, and a column is embedded when rows are written, by declaring its vector field `OPTIONS(embed = 'column', model = '...')`.
The text is embedded where the query is planned: by the database from Rust, Python and JavaScript, and by the server (a coordinator for its shards) on the cores it embeds writes with, as a parameter's `{"embed": "text"}` is. With a static model (Model2Vec, such as `potion-retrieval-32M`) that takes tens of microseconds; the median query on SciFact, its text embedded and every row measured, took 0.45 ms ([results](../../chloedb/results/static-int8/README.md)).
`similarity` is the raw dot product of the vectors as written: ChloeDB does not normalise the vectors a write supplies (the models it runs itself write unit vectors), so on vectors of other lengths long vectors rank first. For cosine similarity, write unit vectors. `ORDER BY distance(emb, :v) ASC` ranks by $\lVert v - q \rVert$, nearest first, and `score()` is minus the distance (ranking is always best first). On a field a model embeds the vectors are unit length, where distance orders rows as the dot product does, so the index searches them (`strategy => 'flat'` measures every row); on any other field every row `WHERE` keeps is measured exactly, a scan of the field's float32 vectors, since its index ranks by the dot product. **Changed:** `distance()` ranked like `similarity(...) DESC` before, which is the nearest row only for unit vectors, and its `score()` was the similarity; a shard from before this change still ranks it so. In an expression, `distance()` stays refused: use `similarity()`.
| option | effect |
|---|---|
| `strategy` | `'auto'` (default: the planner decides, by its cost model, which sizes the work by the vectors' dimensions: an unfiltered search scans every vector exactly where that costs no more than the index, as in a segment of 20,000 vectors of 64 dimensions), `'prefilter'` (evaluate the filter, scan its members exactly), `'index'` (search HNSW or IVF with the filter inside), `'postfilter'` (search with a larger *k* and drop non-matching rows), `'flat'` (exact scan), `'partition'` (walk the graphs of the [partitions](#vector-partitions) the filter can match) |
| `ef` | HNSW search breadth (default 200; 64 before). On random unit vectors of 64 dimensions, the hard case for a graph (real embeddings cluster, and need less), the index found 0.73 of the true top 10 at ef 64 and 0.96 at 200 over 20,000 rows (0.13 and 0.24 ms at the median), and 0.40 and 0.71 over 200,000 (0.24 and 0.35 ms); the default search of the 20,000, now an exact scan, finds all of them in 0.15 ms (200 queries, `cargo test --test vector_defaults -- --ignored`, one run on a 4-core Intel Xeon @ 2.10GHz shared with other builds) |
| `nprobe` | IVF clusters probed |
| `rerank` | how many candidates are re-scored in float32 |
#### Vector partitions
A filter that keeps a fifth of the rows makes an HNSW search either walk its graph testing every row it reaches, or fetch five times the candidates and drop the rest. A field partitioned by the column the filter names does neither: each segment keeps, besides the field's graph of every row, a graph per partition of the rows, and a search whose `WHERE` limits that column walks only the graphs of the partitions that can match.
```sql
CREATE TABLE docs (id KEYWORD PRIMARY KEY, rating FLOAT, category KEYWORD,
emb VECTOR(768) OPTIONS(partition_by = 'rating', partition_bounds = '1, 2, 3, 4'));
SELECT id FROM docs WHERE rating >= 4 ORDER BY similarity(emb, :v) DESC LIMIT 10;
```
- `partition_bounds` splits an `INT` or `FLOAT` column into ranges: here below 1, 1 to 2, 2 to 3, 3 to 4, and 4 and up (1 to 63 increasing numbers). A `KEYWORD` column is partitioned by value and takes no bounds (`partition_by = 'category'`): each segment builds a graph for each of its 64 most frequent values. The column must be stored, indexed and single-valued, and the field an HNSW field of one vector a row. Rows without a value in the column are only in the field's graph.
- The planner reads the first condition on the column among the filter's top-level `AND`s: a range (`>=`, `<`, `BETWEEN`), `=` or `IN`. A partition whose rows all pass it is walked with no test at all, so `rating >= 4` costs what an unfiltered search of a fifth of the rows costs; a partition that only partly matches, or a filter with other conditions, tests the rest on each row the walk reaches. The planner uses partitions when its cost model predicts them faster than its other plans, and `strategy => 'partition'` uses them wherever they apply. A search without a condition on the column uses the field's graph, as before.
- On 1M MS MARCO passages (768-dimension vectors, one segment, the 4-core cloud container), the engine comparison's `rating >= 4` (20% of rows) took 176–184 µs with partitions against 364–438 µs, at recall@10 0.963 against 0.961; `rating >= 4.5` (10%) 383 µs against 674–777 µs. At 2% (`rating >= 4.9`) the partitions took 1.1 ms where the planner's exact scan of the matching rows takes 1.6–2.2 ms, finding 0.995 of the exact answers instead of 0.999 (`chloedb/results/vector/partitions-msmarco-1000000x768.json`).
- The partitions' graphs take as much space as the field's graph again (128 bytes a row at `m = 16`, 3% of that table's file) but share its vectors and codes. Building that table took 320 s instead of 179 s, and merges build the partitions again from scratch.
- A database with partitions is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `vector_partition`, which versions of ChloeDB from before them refuse by name.
A `VECTOR` field keeps, besides its float32 rows, a compact code per row that the search scans: 8 bits per dimension by default, or 1 bit per dimension with `"codes": "binary"` in the field's schema (or the build option `vector.codes = 'binary'`). Binary codes are 32 times smaller than the vectors and 8 times smaller than 8-bit codes; to make up for the coarser scores, the search re-scores 8 times as many candidates in float32. On synthetic 768-dimensional data that kept recall@10 at 0.985–0.994 with flat, IVF and HNSW search, at an eighth of the memory ([results](results.md#compressed-vectors)); check recall on your own embeddings before choosing them, since some models lose more to one-bit codes than others.
RaBitQ codes (`"codes": "rabitq1"`, `"rabitq2"` or `"rabitq4"`, or `codes = 'rabitq4'` in `OPTIONS`) keep 1, 2 or 4 bits per dimension of the vector after a fixed random rotation, and two numbers per row that give each estimated score an error bound. The search keeps 8, 4 or 2 times as many candidates, and skips the float32 row of any candidate whose bound shows it cannot reach the top results found so far. On FiQA's Cohere embeddings, at recall@10 1.000 with a flat scan, 1-bit RaBitQ codes read 91 float32 rows a query where binary codes read 320, 2-bit codes 28 and 4-bit codes 13, against SQ8's 40 ([results](results.md#compressed-vectors)). Their scan is slower per row than binary or SQ8 codes of the same field: 4-bit codes take half the memory of SQ8 and scan about 1.5 times slower. They pay off when reading the float32 rows is the cost, as with a table larger than memory. A database with RaBitQ codes is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `rabitq`, which versions of ChloeDB from before them refuse by name.
### `similarity(field, weights)` on a `SPARSE` field
The dot product of a row's term weights with the query's, `Σ q_t · w_t` over the terms both have. The query is a JSON object of term weights, bound as a parameter or written as a string:
```sql
SELECT id, score() FROM docs
ORDER BY similarity(splade, '{"vaccine": 1.4, "mrna": 2.1, "efficacy": 0.6}') DESC LIMIT 10;
```
It runs on the same machinery as `bm25` (MaxScore, Block-Max WAND, the filter strategies), so `algo => 'maxscore' | 'bmw' | 'exhaustive'` applies, and it fuses with other scores in `rrf`, weighted sums and products. `distance` is not defined on a `SPARSE` field.
A `SPARSE` field [embedded by a learned sparse model](server.md#term-weights-of-a-learned-sparse-model) (`sp SPARSE OPTIONS(embed = 'body', model = '...')`) gets its rows' weights from the model; the query's are the parameter `{"embed": "some words", "field": "sp"}` (from Rust, `Db::embed_query_in`), weighed by the same model.
### `maxsim(field, vectors)`: several query vectors
The best similarity of a row's vector with any of several query vectors, $\max_i q_i \cdot v$: a row near any one of a user's recent items, or of a query's several phrasings. The vectors are a bound list of vectors, a tuple of vector parameters, a JSON array of arrays, or a subquery that returns one column of vectors, which runs first:
```sql
-- items like any of the user's last 20, by similarity
SELECT id, score() FROM items
ORDER BY maxsim(emb, (SELECT emb FROM history WHERE usr = :u ORDER BY ts DESC LIMIT 20)) DESC LIMIT 10;
-- and fused with text and a row's rating
SELECT id FROM items
ORDER BY rrf(bm25(title, :t), maxsim(emb, :recent)) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10;
```
It runs one search per query vector, with the filter and the options of `similarity` (`strategy`, `ef`, `nprobe`, `rerank`), and scores the union of their top *k* exactly against every query vector. The union holds the exact top *k*: a row among them is among the top *k* of the query vector it is closest to. Each added query vector costs one more search ([what that costs](results.md#maxsim)). A row without a vector scores `NULL`, a subquery with no rows ranks nothing, and more than 64 vectors is an error unless `max_vectors => n` raises the limit. It is a score wherever `similarity` is one: in `rrf`, `minmax()` sums and ranking expressions, on one database or over shards.
On a **multi-vector field** (`VECTOR(d)[]`), `maxsim` is late interaction as ColBERT and ColPali score it: the sum over the query vectors of each one's best match among the row's vectors, $\sum_i \max_j q_i \cdot v_j$. Each query vector's search returns its best `depth` vectors (64), which name candidate rows; the `candidates` rows (200, at least the `LIMIT`) with the largest sum of the matches found are scored over all their vectors, with their 8-bit codes, or float32 when the field keeps them. A row without vectors ranks nowhere. `depth => n` and `candidates => n` trade time for recall; with both at least the number of vectors, the answer is exact. `similarity` refuses a multi-vector field, and so do graph functions.
```sql
-- pages by their patches' best matches with the query's token vectors
SELECT id, score() FROM pages ORDER BY maxsim(patches, :tokens) DESC LIMIT 5;
```
A multi-vector field can also be the vectors of a text's tokens, which a model of late interaction (ColBERT) computes when rows are written: `tok VECTOR(96)[] OPTIONS(embed = 'body', model = 'answerai-colbert-small-v1')` ([a vector a token](server.md#a-vector-a-token)). A query gives the vectors of its own tokens as the parameter (`{"embed": "the text", "field": "tok"}` on the server, `Db::embed_query_in` from Rust). Its usual place is a rerank phase over BM25's best rows, which scores each of them over all its vectors:
```sql
WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 100)
SELECT id, score() FROM top ORDER BY maxsim(tok, :tokens) DESC LIMIT 10;
```
On BEIR's SciFact and NFCorpus, `answerai-colbert-small-v1` over BM25's top 20 scores nDCG@10 0.738 and 0.354 (BM25 alone 0.691 and 0.329) in 80–90 ms a query on four cores, most of it encoding the query; that ranks better than the cross-encoder below, in a fifth of its time. The cost is at write: 0.1–0.16 s a document to embed, and a database about 29 times BM25's (half that with `pool_factor = 2`, which scores the same). The [results](results.md#colbert-reranking) have the details.
`dot(a, b)` is the dot product of two vectors as a value, for rows in memory: `SELECT id, dot(emb, :q) FROM h` over a `WITH` result, a join, or a table's own rows. It equals `similarity` to the bit, and in a ranking expression over a table (`ORDER BY bm25(title, :q) + 2 * coalesce(dot(emb, :q), 0) DESC`) it is `similarity(emb, :q)`: `NULL` for a row without a vector.
### `rrf(s1, s2, …)`: reciprocal rank fusion
Each input ranks the rows that pass `WHERE`, to a depth of 100 by default, and a row's fused score is
$$
\mathrm{rrf}(d) = \sum_{i} \frac{1}{k + \mathrm{rank}_i(d)}, \qquad k = 60
$$
Options: `k => 60`, `depth => 100`, and `weights => [w1, w2, …]`, one number of at least 0 per input, which multiplies that input's terms (weighted RRF):
$$
\mathrm{rrf}(d) = \sum_{i} \frac{w_i}{k + \mathrm{rank}_i(d)}
$$
`rrf(bm25(body, :q), similarity(emb, :v), weights => [0.3, 0.7])` leans on the vectors; the weights are a list (`[0.3, 0.7]`, `ARRAY[0.3, 0.7]`) or a parameter holding one, and all of them 1 is plain `rrf`. A list of another length, or of weights all 0, is an error. The depth is raised to the page's `LIMIT` when it asks for more rows, as in weighted sums and products, but not by its `OFFSET`: pages of one size (`LIMIT 20 OFFSET 0, 20, 40 ...`) rank the same candidates, so they are the pages of one ranking, with no row on two pages and none skipped. A page past the candidates comes back short, with `truncated: true` and a plan line that says so; to page deeper, give the ranking a larger `depth =>`, the same on every page. **Changed:** the depth was raised to `LIMIT + OFFSET` before, so each page ranked other candidates, and paging repeated and skipped rows.
### `ranked(keys)`: a ranking from elsewhere
`ranked(:keys)` is a ranking computed outside ChloeDB, given as primary keys, best first: a recommender's candidates, a reranker's order, or the rows a [semantic-ID](server.md#semantic-ids) decoder generated. It is a score like any other, so it fuses with ChloeDB's own rankings:
```sql
SELECT id FROM items WHERE in_stock ORDER BY rrf(bm25(title, :q), ranked(:keys)) DESC LIMIT 20;
```
A listed row scores `-(its position)`, from `-1` for the first key; a key listed twice ranks where it is first. A row the list leaves out has `NULL`, so in an expression it ranks last unless `coalesce` gives it a value, and in a weighted sum it takes the input's worst value, as a missing column does. Times another score (`ranked(:keys) * rating`) it multiplies as arithmetic, not as a product of scores, which would count its negative values as 0. A key no live row has is skipped. On its own, `ORDER BY ranked(:keys) DESC` answers the listed rows that `WHERE` keeps, in list order. The keys are a parameter holding a list (an array of keys in the HTTP API), a tuple (`ranked(('a', 'b'))`) or an array (`ranked(ARRAY['a', 'b'])`). Over shards, each shard scores its own rows from the list and the coordinator merges them, so no extra round is needed. A plan that uses it needs the plan feature `ranked`.
### Weighted sums: `tmm()`, `minmax()` and `zscore()`
A weighted sum of normalised scores is weighted (convex) fusion: `0.2 * tmm(bm25(body, :t)) + 0.8 * tmm(similarity(emb, :q))`. Weights are numeric constants; `+` and `-` combine any number of terms. Candidates are the union of each input's top 100, re-scored exactly by every input and normalised over that union ($C$). Three normalisers put a score on one scale:
| normaliser | a row's value | a row without a value |
|---|---|---|
| `tmm(x)`, theoretical min-max | $\dfrac{x - lo}{\max_C x - lo}$, `lo` the least value `x` can take | 0 |
| `minmax(x)` | $\dfrac{x - \min_C x}{\max_C x - \min_C x}$, 1 where all are equal | 0 |
| `zscore(x)` | $\dfrac{x - \mathrm{mean}_C x}{\mathrm{sd}_C x}$, 0 where all are equal | the least of the candidates' |
Use `tmm` unless your own judged queries say otherwise. Its lower end is fixed by what the score is, not by the candidates: a row's value depends only on the best candidate, which is the same at any depth, while `minmax` moves every row whenever the weakest candidate changes, which it does with `depth` and with what each input happens to return. Bruch, Gai and Ingber ([TOIS 2023](https://arxiv.org/abs/2210.11934)) find this convex combination beats RRF in and out of domain once its one weight is tuned, and that a few dozen judged queries tune it; the [relevance lab](server.md) tunes it on yours ([what it gives on BEIR](results.md#score-fusion)).
`lo` is the score's own: 0 for `bm25`, a `SPARSE` similarity (weights at least 0, as learned models give them), `rrf`, `ppr` and `decay`; -1 for `similarity` and a one-vector `maxsim`, the least cosine of unit vectors (the vectors of an embedded field, and of most models; for vectors of other lengths, give `lo`); -n for `maxsim` of n vectors on a multi-vector field. Anything else, a column or an expression, needs it written: `tmm(rating, lo => 0)`. With `hi` too, `tmm(x, lo => a, hi => b)` is $(x - a) / (b - a)$, each row's own value (0 without one), fixed bounds that read nothing of the other candidates.
Options, given on any input: `depth => 100` (candidates per input), `exact => 1` (score every row that passes `WHERE` instead of the top-100 union). The top-100 shortcut recovers 89–95% of the exact fused top 10 ([results](results.md#hybrid-ranking)).
A row without a value of a column input (`0.7 * minmax(bm25(body, :t)) + 0.3 * minmax(rating)` for a row whose `rating` is `NULL`) takes that input's worst value among the candidates: its lowest when the weight is positive and its highest when the weight is negative (0 and 1 after min-max), so a missing value never lifts a row. Under `tmm` and `zscore` it takes the value in the table above. A plan with `tmm` or `zscore` needs the plan feature `score_norms`, which a version of ChloeDB from before them refuses by name.
**Changed:** a sum of bare scores, `0.2 * bm25(body, :t) + 0.8 * similarity(emb, :q)`, was this fusion before ranking expressions; `+` now adds raw values, as in any expression below. Write `minmax()` around each term for the fusion. For one release, `EXPLAIN` and a query's plan lines add a note when an expression adds raw relevance scores. `norm => 'none'`, which kept raw scores in a sum, is accepted and changes nothing.
### Ranking expressions
`ORDER BY` takes any expression of scores, numeric columns and numbers, ranked best first (`DESC`; negate it to rank the smallest first):
```sql
-- relevance boosted by a rating, which may be missing
SELECT id FROM products ORDER BY ln(1 + bm25(body, :t)) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10;
-- a business rule on top of similarity
SELECT id FROM products
ORDER BY similarity(emb, :q) + CASE WHEN in_stock THEN 0.1 WHEN category = 'outlet' THEN -0.2 ELSE 0 END DESC LIMIT 10;
-- Borda-style fusion of two rankings
SELECT id FROM papers ORDER BY -rank(bm25(body, :t)) - rank(similarity(emb, :q)) DESC LIMIT 10;
```
| part | meaning |
|---|---|
| `+ - * / %`, unary `-` | arithmetic on raw values |
| `bm25`, `similarity`, `ppr`, `decay`, `rrf`, `ranked`, a numeric column, `hops()`, `seq_no()`, `hash(field, seed)` | the leaves: a row's value of each |
| `ln(x)`, `log(x)` (base 10), `log(b, x)`, `exp(x)`, `sqrt(x)`, `pow(x, y)`, `abs(x)`, `round(x[, digits])`, `sigmoid(x)`, `clamp(x, lo, hi)` | numeric functions |
| `least(…)`, `greatest(…)`, `coalesce(…)` | over their arguments that are not `NULL` |
| `tmm(x[, lo => a][, hi => b])` | `x` from its least possible value to the best row's, put on [0, 1]: 0 where `x` is `NULL` ([above](#weighted-sums-tmm-minmax-and-zscore)) |
| `minmax(x)` | `x` over the rows ranked, put on [0, 1]: 1 where all are equal, 0 where `x` is `NULL` |
| `zscore(x)` | `x` less the rows' mean, over their deviation; `NULL` takes the least of the rows' |
| `rank(x)` | 1 plus the number of rows ranked with a greater `x`; `NULL` places after every other |
| `CASE WHEN c THEN x … ELSE y END` | the first branch whose condition holds (any `WHERE` condition), else `y`, else `NULL` |
| `count_true(c, …)` | how many of the conditions hold ([`AT_LEAST`](#some-of-the-conditions-at_least)) |
`NULL` is a missing value (a `NULL` column, a row without a vector, one a traversal does not reach) or a result that is not a finite number (`ln(0)`, a division by 0, an overflow). Arithmetic and functions of `NULL` are `NULL`, except `coalesce`, `least` and `greatest`, which skip it. A row whose score is `NULL` ranks after every other, and its `score()` is `NULL`.
Candidates are the top `depth` (100) rows of each relevance leaf (`bm25`, `similarity`, a graph's, `ranked`), and of every input of `rrf`; an expression with no such leaf (`rating * 2 + year / 1000`), or `exact => 1` on any leaf, ranks every row that passes `WHERE`. A [rank-safe boost](#rank-safe-boosts) ranks every row its text score matches. Each leaf scores every candidate exactly, and `tmm()`, `minmax()`, `zscore()` and `rank()` are taken over the candidates. Over shards, each shard returns its candidates' leaf values and the coordinator runs the expression, so a split collection ranks like the whole one.
#### Rank-safe boosts
An expression with one text score (`bm25`, or `similarity` on a `SPARSE` field) whose other parts are numeric columns, `decay`, `CASE` conditions, numbers, `seq_no()` and `hash()` finds its exact top rows: the rows that scoring every row the text matches would rank first, not only the best of the text's top 100. Set functions (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` and `exact => 1` take the candidates above instead.
```sql
-- the 10 best by BM25 boosted by importance, even a row 5,000th by BM25 alone
SELECT id FROM docs ORDER BY bm25(body, :t) * (1 + 0.2 * importance) DESC LIMIT 10;
```
The text score's top-k loop (MaxScore, Block-Max WAND or exhaustive, as `algo` says) ranks by the whole expression. From the k-th best value so far and each column's smallest and largest value, it works out the lowest text score a row needs, and skips the rows below it. A row the text does not match is not a candidate. When the expression does not rise with the text score (`rating - bm25(body, :t)`), no text score can be ruled out: the loop scores every matching row, and the plan line says `every match scored`. Over shards, each shard returns its own exact top rows: its top `LIMIT + OFFSET` over all its segments, and the rows tied with the last of them. The cluster's top rows are each in their own shard's, so a split collection ranks like the whole one. A shard also returns the text score's top `depth` rows, which a coordinator from before rank-safe boosts fused from, only to a coordinator older than shard protocol 10 ([gRPC](server.md#grpc)).
A plan that ranks by an expression needs the plan feature `rank_expressions`; a version of ChloeDB from before it refuses the plan by that name. Weighted sums of `minmax()`, products of scores and `rrf` are written as before, so older shards still run them.
#### Rerank phases
A ranking can go on in phases, as a search engine's rank profile does: a cheap first phase over every candidate, then a costlier one over its top rows. SQL writes a phase as a `WITH` that ranks a table and cuts it, ranked again by the next `WITH` or the query itself:
```sql
-- BM25's top 100, ranked again by a mix of title and body relevance and rating
WITH top AS (SELECT * FROM docs WHERE year >= 2020 ORDER BY bm25(body, :t) DESC LIMIT 100)
SELECT id, title, score() FROM top
ORDER BY bm25(title, :t) + 0.5 * bm25(body, :t) + 0.1 * coalesce(rating, 0) DESC LIMIT 10;
-- three phases: similarity's top 500, its best 50 by a rating, then a fusion of the 50
WITH a AS (SELECT * FROM products ORDER BY similarity(emb, :q) DESC LIMIT 500),
b AS (SELECT * FROM a ORDER BY coalesce(rating, 0) DESC LIMIT 50)
SELECT id, score() FROM b ORDER BY minmax(bm25(body, :t)) + minmax(similarity(emb, :q)) DESC LIMIT 10;
```
The planner makes one search of them, with phases. Each phase ranks the rows of the one before by an expression, best first, and may read any of the table's columns, since the rows are the table's. Every row a phase reads goes on: one the expression gives no value ranks last with a `NULL` score (and a row a `bm25` phase's terms miss scores 0), and rows tied keep the order the phase before gave them. `LIMIT` and `OFFSET` on the query cut the last phase, and `score()` is the last phase's score. The first `WITH` may filter (`WHERE`) and rank as any query does; each later step reads the step before alone, with no `WHERE` or grouping, ranks by one expression `DESC` (which may hold [correlated subqueries](#correlated-subqueries-a-ranking-that-reads-other-rows)), and each `WITH` keeps the table's columns (`*`) and has a `LIMIT`. `WITH` results before the first phase, a user's history say, are computed first, for the phases' subqueries to read. Other `WITH` queries plan as before: the table restricted to the rows of the `WITH`.
A phase whose expression is row-local is a second phase: over shards, each shard scores it on its own top rows by the first phase. A phase with a set function (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` or a weighted sum reads every row it reranks, so it is a global phase: it runs once over the merged rows (on the coordinator over shards), and so does every phase after it. The coordinator keeps the top rows of the whole collection by the first phase before it ranks them by the next, so a split collection answers exactly as the whole one does. `EXPLAIN` shows each phase and which kind it is, and a query's plan lines say how many rows each reranked. The first phase's `LIMIT` counts against the rows a query may reach (`max_rows`), and the phases against its deadline.
From Python, `rerank(expr, count)` adds a phase: `t.select("id", score()).order_by(bm25("body", q)).rerank(col("rating"), 100).limit(10)`. A plan with phases needs the plan feature `rank_phases`.
#### Correlated subqueries: a ranking that reads other rows
A scalar subquery in a ranking may name a column of the row it ranks (`first.cat`). It is then correlated, and gives a number for each row: how often the user met the row's category, how long ago, how close the row is to what they bought.
```sql
-- the user's last 50 events with their items' categories and embeddings, then
-- BM25's top 1,000 reranked by what the user did with each one's category
WITH h AS (SELECT e.item AS item, i.cat AS cat, i.emb AS emb, e.action AS action, e.ts AS ts
FROM events e JOIN items i ON e.item = i.id WHERE e.usr = :u ORDER BY e.ts DESC LIMIT 50),
first AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 1000)
SELECT id, title, score() FROM first
ORDER BY bm25(title, :q)
+ 0.5 * (SELECT COUNT(*) FROM h WHERE h.cat = first.cat)
- 0.0001 * coalesce((SELECT MIN(:now - h.ts) FROM h WHERE h.cat = first.cat), 100000)
+ coalesce((SELECT MAX(dot(h.emb, first.emb)) FROM h WHERE h.action = 'buy'), 0) DESC
LIMIT 20;
-- a table read through its indexes: the user's events in the row's category that cost less
SELECT id FROM items WHERE MATCH(title, :q)
ORDER BY bm25(title, :q) + 0.1 * (SELECT COUNT(*) FROM events e WHERE e.usr = :u AND e.cat = items.cat AND e.price < items.price) DESC
LIMIT 20;
-- as a column of the rows ranked
WITH first AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 100)
SELECT id, (SELECT COUNT(*) FROM events e WHERE e.usr = :u AND e.item = first.id) AS seen FROM first
ORDER BY bm25(title, :q) DESC LIMIT 20;
```
- **Where.** The rows ranked must be a bounded set: a [rerank phase](#rerank-phases), whose rows are the phase before's top rows; an `ORDER BY` over a table, or over a `WITH` result, of at most 10,000 rows (more is an error that suggests a phase); or the columns of a ranked query, alone or in an expression (`coalesce(price, 0) + (SELECT ...)`). A subquery naming the outer row in `WHERE`, `IN` or `EXISTS` is an error, but for an [`EXISTS` that names it by one equality](#subqueries-with-and-joins), a semi join.
- **What it names.** `name.column`, where `name` is the outer query's table or `WITH` result (or its alias) and the column one of its columns. The subquery reads a `WITH` result in memory, compared any way an expression over rows in memory can be, or a table through its indexes, whose conditions compare one of its columns with the outer row's (`e.cat = items.cat`, `e.price < items.price`) as they would a value.
- **Its value** is a number, a `FLOAT` (`COUNT`, `SUM`, `MIN`, `MAX`, `AVG` of numbers, or a boolean as 0 or 1), so a correlated `COUNT` reads `10.0` where PostgreSQL gives the integer `10`. One of no rows is `NULL` (`COUNT` gives 0), which ranks last unless `coalesce`d. A `NULL` of the outer row is compared as SQL compares it: `e.price < first.price` holds for no event when the row has no price.
- **How it runs.** First the rows ranked (the phases before, or the rows a bounded `ORDER BY` reads), with the columns the subqueries name. The parts of a subquery that do not read the outer row run once (`h` above, and its rows where `h.action = 'buy'`). A subquery whose outer columns meet only equalities ANDed into its `WHERE` (`h.cat = first.cat`) then runs once, grouped by them over the values the rows hold (`h.cat IN (...)`), and a value no group has takes the subquery's value over no rows; any other runs once for each distinct value of the columns it names. Then the ranking sorts the rows, with each row's values, and the plan lines say how much ran: `correlated: 3 subqueries over 1000 rows, 597 values, 3 runs`.
- **Over shards** a coordinator runs the steps before, and the subqueries over the shards' rows, and sends each row's values to the shards inside the plan, by key, so that every shard ranks with the same ones. A plan with them needs the plan feature `correlated`.
- **Cost** at 1,000 candidates, measured with `chloedb-correlated-bench` on a cloud VM (4-core Intel Xeon @ 2.10GHz, 16.9 GB, Linux 6.18): 100,000 items in 200 categories, 400,000 events of 2,000 users, a history of 50 events, one thread, 300 requests of each shape. BM25's top 1,000 reranked to 20 took 1.29 ms (mean) without subqueries, and reading the history added 1.67 ms. A subquery added, over the rerank alone (with the history's read):
| subquery | values | runs | added, mean |
|---|---|---|---|
| by category, over `h` | 199 | 2 | 4.90 ms |
| three by category, over `h` | 596 | 6 | 8.14 ms |
| by category, over the events table | 199 | 2 | 4.09 ms |
| by item, over the events table | 992 | 2 | 21.6 ms |
| by embedding (`dot(h.emb, first.emb)`), over `h` | 992 | 992 | 10.5 ms |
A grouped run costs about what reading the candidates' values does. A subquery that runs once per value costs about 10 µs a run over rows in memory, and one grouped by a key reads an `IN` list as long as the candidates (`e.item IN (...)`), which is most of its cost. A second run gave the same numbers within 0.4 ms (`chloedb/results/correlated/`).
#### Features: the values a ranking read
A ranking expression that scores each row by itself is a column, with the value the ranking computes for the row, and `features()` lists the inputs of the query's ranking, to log beside what users chose and train a model on (Vespa's match-features):
```sql
SELECT id, score(), features() FROM docs
ORDER BY bm25(body, :t) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10;
-- columns: id, score(), bm25(body, :t), rating, bm25(body, :t) * (1 + 0.2 * coalesce(rating, 0))
SELECT id, bm25(title, :t) AS title_bm25, ln(1 + rating) AS r, year / 1000 FROM docs
ORDER BY similarity(emb, :q) DESC LIMIT 10;
```
- **`features()`** stands for one column per input, each once, named by its SQL text: every leaf of the ranking (a score such as `bm25(body, :t)` or `similarity(emb, :q)`, a column, `decay(..)`, `hops()`), the first phase's first, then each phase's expression that scores a row by itself and is not a leaf. With [rerank phases](#rerank-phases) it lists every phase's. An expression with a set function (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` or a weighted sum ranks rows against each other, so it is not a column: its inputs are, and `score()` is its value. A ranking by `distance(..)` lists the `similarity(..)` it ranks by. `features()` takes no alias and needs an `ORDER BY`. **Changed:** `features()` refused a ranking with `tmm()` or `zscore()` before (`minmax()` it took), and so did the rank log and Explain's hits for one.
- **A selected expression** may use anything a ranking expression does but the set functions: `bm25`, `similarity`, `decay`, columns, numbers, arithmetic, `ln` and the other functions, `CASE`. Its value is the ranking's, bit for bit: a row a `bm25`'s terms miss scores 0, and one without a value is `NULL`. `ORDER BY 2` ranks by the second column when it is one.
- **Over shards** a feature is one database's value: a coordinator sums the shards' BM25 statistics of the terms any column scores, and its fetch round computes the columns for the page alone, with those statistics.
- A plan with such a column needs the plan feature `rank_features`. From Python, `features()` goes in `select`, and so does any expression of scores (`select("id", bm25("title", q).alias("t"))`); Python names a feature as it writes the expression.
#### Rank profiles: a ranking kept with its table
A ranking used by many queries can be kept with its table under a name, as a search engine keeps a rank profile, and queries rank by the name:
```sql
CREATE RANK PROFILE recall ON memories AS
WITH top AS (SELECT * FROM memories ORDER BY bm25(body, :q) DESC LIMIT 100)
SELECT * FROM top ORDER BY bm25(body, :q) * (1 + :imp * importance) DESC
WITH (imp => 0.2);
SELECT id, score() FROM memories WHERE kind = 'fact'
ORDER BY rank_profile('recall', q => :q) LIMIT 10;
CREATE OR REPLACE RANK PROFILE recall ON memories AS ...; -- replaces it
DROP RANK PROFILE IF EXISTS recall ON memories; -- ON may go when one table has it
```
- **The ranking** is a query of the table that ranks every row: `SELECT * FROM table ORDER BY expression` (any [ranking expression](#ranking-expressions), or a numeric column with `ASC` or `DESC`; `CREATE` checks that every column it names is the table's), or [rerank phases](#rerank-phases) over it. It has no `WHERE`, and no `LIMIT` after its last ranking: the query that ranks by it filters and cuts. `WITH (name => value, ...)` after it gives its parameters defaults: numbers, strings, `TRUE` and `FALSE`. Names are letters, digits and `_`, in any case; `CREATE` refuses a name the table has already, and `CREATE OR REPLACE` replaces it.
- **`ORDER BY rank_profile('name', parameter => value, ...)`** is the whole `ORDER BY` of a query of the profile's table, without `ASC`, a `WITH`, a join or `GROUP BY`. The query ranks as if it were written out: its `WHERE` filters the rows the first ranking reads, and its columns, `LIMIT` and `OFFSET` are the last ranking's, so `score()` and [`features()`](#features-the-values-a-ranking-read) work as with the ranking written out. Each parameter of the ranking is the call's argument (a value, or a parameter of the query: `q => :q`), else the profile's default, else the query's parameter of the same name.
- **Kept and replicated as writes are**: a profile is logged in its own transaction (numbered where writes are, shipped to replicas), and dropped with its table. A database with a profile needs the format 3 feature `rank_profiles`, which a version of ChloeDB from before profiles refuses by name; once the last profile is dropped and flushed, the database no longer needs it.
- **A plan names its profile** and a hash of its definition (`EXPLAIN` shows `rank profile: recall (hash ...)`) and needs the plan feature `rank_profiles`. A database whose profile of that name is another (replaced since, or a shard that missed the change) refuses the plan rather than rank otherwise. Through a coordinator, `CREATE` and `DROP RANK PROFILE` run on every shard, and the coordinator serves the profiles every replica holds alike.
#### Ranking models: `gbdt('model', features…)`
A gradient-boosted tree model, trained by LightGBM or XGBoost on the [features](#features-the-values-a-ranking-read) a query logged, ranks rows as a ranking expression of them:
```sql
SELECT id, score() FROM docs
ORDER BY gbdt('docs_ltr', bm25(title, :t), bm25(body, :t), coalesce(rating, 0), year % 6) DESC LIMIT 10;
-- as a second phase over BM25's top 200, and a binary model's probability
WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :t) DESC LIMIT 200)
SELECT id, score() FROM top ORDER BY sigmoid(gbdt('clicks', bm25(title, :t), bm25(body, :t), rating)) DESC LIMIT 10;
```
- **The model** is the file `//gbdt.json` in the models directory, the one embedded fields' models come from (`--models` on a server, `models=` in Python, else `~/.local/share/chloedb/models` (or `~/.local/share/strata/models`, on a machine that has that folder from before the rename; before 0.3.2, always)): LightGBM's `booster.dump_model()` written with `json.dump` (numerical and categorical splits, any missing-value handling, a random forest too), or XGBoost's `booster.save_model("gbdt.json")` (a `gbtree`; categorical splits, multiclass and `dart` are refused). A name is letters, digits, `_`, `-` and `.`. A model is read when a query first uses it and again when its file changes.
- **Its arguments are its features**, in the order it was trained on, each any ranking expression of the row (a score, a column, arithmetic); as many as the model reads. A `NULL` feature is a missing value, which goes where the model sends missing values (LightGBM: `NaN`; or 0 under `zero_as_missing`).
- **The score is the model's raw one**, the sum of its trees, bit for bit what LightGBM's `predict(raw_score=True)` and XGBoost's `predict(output_margin=True)` give (XGBoost's in `f32`, from its base score): `sigmoid(gbdt(…))` is a binary model's probability. A random forest's score is the sum of its trees, as LightGBM's raw score is.
- **Rank it over the top rows of a cheaper ranking.** In a [rerank phase](#rerank-phases) a model is a second phase, which each shard scores on its own rows, one tree at a time over them: a LambdaMART model of 300 trees over BM25's top 100 takes 0.7 to 1.0 ms a query at the median on SciFact, NFCorpus and FiQA, against 0.02 to 0.2 ms for BM25 alone (`chloedb/results/text/bm25_gbdt.json`, a 4-core cloud VM). `ORDER BY gbdt(bm25(…), columns…)` alone is exact, a [rank-safe boost](#rank-safe-boosts) bounded by the leaves each tree can reach from the text score's bound and each column's range; but summed over hundreds of trees such a bound sits well above what rows score, so the top-k loop skips few matches and scores the rest with every tree: 5.5 to 70 ms on the same collections.
- **A plan names the model and the hash of its file** (`EXPLAIN` shows `ranking model: docs_ltr (hash …)`) and needs the plan feature `rank_models`. A database or shard whose file of that name is another refuses the plan rather than rank with another model; a plan without a hash runs with the file there. A coordinator scores the shards' rows with the model too, so it needs the same file in its own models directory.
- `features()` lists a model's inputs' leaves and then the model's score, and from Python `gbdt("docs_ltr", bm25("title", t), col("rating"))` builds the same ranking.
#### Cross-encoders: `cross_encoder('model', fields…, query)`
A cross-encoder reads the query and a row's text together and scores how well the text answers it. It costs thousands of times what BM25 does per row, so it reranks the top rows of a cheaper ranking, in a rerank phase of its own:
```sql
WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 20)
SELECT id, title, score() FROM top
ORDER BY cross_encoder('ms-marco-MiniLM-L-6-v2', title, body, :q) DESC LIMIT 10;
-- mixed with other scores of the row, and a phase after it
WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 20),
ce AS (SELECT * FROM top ORDER BY cross_encoder('bge-reranker-base', body, :q) + 0.1 * coalesce(rating, 0) DESC LIMIT 10)
SELECT id, score() FROM ce ORDER BY bm25(title, :q) + decay(published, now(), 2592000) DESC LIMIT 5;
```
A server reranks at most 20 rows a query by default: start it with `--max-rerank 100` to rerank the top 100, as the measurements below do.
- **The model** is a Hugging Face directory `/` holding `config.json`, `tokenizer.json` and its weights. A `model.onnx`, any sequence classifier with one label exported to ONNX (int8 ones too, as Hugging Face repositories ship them under `onnx/`, such as `model_qint8_avx512_vnni.onnx`), runs through ONNX Runtime in a server or Python package built with `--features onnx`, which downloads ONNX Runtime's library when it builds and links it in; its rows are sorted by length into batches of 16, so that little of a batch is padding. A `model.safetensors`, a `BertForSequenceClassification` (such as `cross-encoder/ms-marco-MiniLM-L-6-v2`) or an `XLMRobertaForSequenceClassification` (such as `BAAI/bge-reranker-base`) with one label, runs through candle in `f32` in one built with `--features bert` (`accelerate` on a Mac), as BERT embedding models do. A directory with both runs its `model.onnx`; without the feature its weights need, a query by it is refused. `chloedb-server fetch-model ms-marco-MiniLM-L-6-v2-int8` (or `gte-reranker-modernbert-base-int8`, a ModernBERT model) downloads an int8 export ready to run. A model is read when a query first uses it and again when one of its files changes. `builtin:overlap` needs no files: the share of the query's distinct words the text holds, for tests and demos.
- **A model served elsewhere** is called over HTTP, a batch of rows a request (feature `hosted`, on by default), for models too large or slow for the server's CPU: a provider's by name, `cohere/rerank-v3.5`, `voyage/rerank-2.5` or `jina/jina-reranker-v2-base-multilingual`, with the key in `COHERE_API_KEY` (or `CO_API_KEY`), `VOYAGE_API_KEY` or `JINA_API_KEY`; or a server of one's own that a directory `/` names in an `endpoint.json`, such as Hugging Face TEI on a GPU (`{"api": "tei", "url": "http://gpu:8080/rerank"}`), or vLLM, Infinity or LiteLLM (`"api": "vllm"`, `"infinity"` or `"litellm"`, with a `base_url`; they answer at `/rerank` in Cohere's shape). `endpoint.json` takes the keys an [embedding model's](server.md#embedded-vector-fields) does that apply (`url` or `base_url`, `model`, `key_env`, `key_header`, `headers`, `batch`, `max_chars`, `concurrency`, `retries`, `timeout_s`), and `COHERE_BASE_URL`, `VOYAGE_BASE_URL` or `JINA_BASE_URL` sends a provider's requests to a server of its API. A request carries 1,000 rows at most (TEI's default batch, 32, for a server of one's own), four are sent at once, a rate limit or a server's error is tried twice more (pauses of at most 5 s; a request times out after 10 s), and a refused key, a server that keeps failing or an answer that misses a row fails the query. A provider's score is its `relevance_score`, between 0 and 1; TEI's is the logit (`raw_scores`), as a model run here gives it. A row with no text is not sent, and gets no score. The plan's hash is of the endpoint (its API, URL and model, not its key), so a plan made with one server is refused by another.
- **The text** is the values of the fields named, stored TEXT or KEYWORD fields, joined by a space (`NULL`s left out, each value of a list), and the query is the last argument, a string or a parameter. Query and text together are cut to 256 tokens (or the model's length, if shorter), the longer of the two first, as Hugging Face's tokenizers cut a pair; a `cross_encoder.json` in the model's directory, `{"max_tokens": 512}`, sets another length.
- **A language model** grades each row instead: `anthropic/` (a Claude model, such as `anthropic/claude-haiku-5-5`, its key in `ANTHROPIC_API_KEY`), `openai/`, or a chat server of one's own that an `endpoint.json` names with `"api": "chat"` (OpenAI's `/chat/completions`, as vLLM, Ollama, LM Studio and LiteLLM serve it; `base_url` is its `/v1`) or `"api": "anthropic"`. Each row is its own request, eight at once (`concurrency`), with UMBRELA's prompt (the one [`/v1/judge`](server.md#relevance-judgments) asks): the model reads the query and the row's text and answers a grade from 0 (nothing to do with the query) to 3 (the exact answer), which is the row's score. A model costs a request a row and about a second each, so it reranks a few dozen rows at most, and gives many rows the same grade: add the first phase's score to break ties (`cross_encoder('anthropic/claude-haiku-5-5', body, :q) + 0.01 * bm25(body, :q)`). An answer without a grade leaves the row without a score, and it ranks last; a request times out after 30 s.
- **The score is the label's logit**, what sentence-transformers' `CrossEncoder.predict` gives with an identity activation (`sigmoid()` of it is the probability for a model trained with one), equal to PyTorch's within 1e-5. A phase may mix it with other scores of the row (`cross_encoder(…) + 0.1 * rating`), and phases after it rerank the rows it kept.
- **It runs once per query, in a global phase**: on a database over the rows the phase before it kept, and through a coordinator once on the coordinator, which reads the text of the rows its shards ranked best in the fetch round of query then fetch and scores them; shards need no model. A cross-encoder is refused as the first ranking (rerank a cheaper ranking's top rows), as a column, and among `features()`.
- **Its cost is per row and per token**: on four cores `ms-marco-MiniLM-L-6-v2` takes about 50 ms a row of 256 tokens in `f32` through candle, and its int8 export through ONNX Runtime about 20 ms. BM25's top 20 takes 0.9 to 1.0 s at the median on SciFact, NFCorpus and ArguAna in `f32` and 0.37 to 0.43 s in int8, and the top 100 4.4 to 4.8 s and 1.8 to 2.0 s, where BM25 alone takes 0.1 to 1 ms; cut at 512 tokens, as before, the top 20 took 1.3 to 1.6 s ([results](results.md#cross-encoder-reranking), a 4-core cloud VM). `--max-rerank` on a server (default 20, a quarter of the default deadline at p99 in `f32`) refuses a phase that would score more rows, and the query's deadline (`--timeout-ms`, 5 s) is checked between batches of 16 rows. Its layers run on the threads the queries share (one per core), so reranks running at once take turns on the cores rather than each starting a thread per core, and queries that ask for a model not yet open wait for one of them to open it.
- **Whether it helps depends on the collection**: reranking BM25's top 100 by `ms-marco-MiniLM-L-6-v2`, a model trained on web questions, raises NFCorpus's nDCG@10 from 0.329 to 0.352, leaves SciFact's where it was (0.687 against 0.691) and lowers ArguAna's from 0.362 to 0.312; see [the results](results.md#cross-encoder-reranking). Measure it on your own queries before paying for it.
- **A plan names the model and the hash of its files** (FNV-1a of the three, or of a served model's endpoint; `EXPLAIN` shows `ranking model: … (hash …)`), with the plan feature `rank_models`, as for [`gbdt`](#ranking-models-gbdtmodel-features). From Python, `.order_by(bm25("body", q)).rerank(cross_encoder("ms-marco-MiniLM-L-6-v2", ["title", "body"], q), 100)` builds the same query.
#### The rank log: what each query served
A ranking is trained on what it served. A query run with a log writes one row per row it answered to a log table, with the values its ranking read as it computed them, so a model trained later sees what serving saw, however the tables change in between: new rows that move BM25's statistics, counters that grow, rows deleted.
```sql
-- what the first query logged to it makes (rank_log unless the log names another)
CREATE TABLE IF NOT EXISTS rank_log (
id KEYWORD PRIMARY KEY, -- '#'
request KEYWORD NOT NULL, ts TIMESTAMP NOT NULL, context KEYWORD,
row_key KEYWORD NOT NULL, position INT NOT NULL, shown BOOL NOT NULL,
score FLOAT, features KEYWORD OPTIONS(indexed = false),
variant KEYWORD, label FLOAT,
query KEYWORD OPTIONS(indexed = false), -- on a request's first row: {"sql": ..., "params": ...}
propensity FLOAT, prefix_propensity FLOAT, -- the chance the row was shown where it was
policy KEYWORD OPTIONS(indexed = false), took_ms FLOAT -- on a request's first row
) OPTIONS(cluster_by = 'context');
-- a label written later: a judge's grade, an agent citing the row
UPDATE rank_log SET label = 3 WHERE request = :r AND row_key = :k;
```
```sh
curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10",
"params": {"t": "mrna vaccine"}, "log": {"context": "u42", "variant": "b", "candidates": 50}}'
# {"columns": ["id", "title"], "rows": [...], ..., "request": "9f0c...", "logged": {"rows": 50, "seq_no": 812}}
```
- **A logged query** is one `SELECT` ranked by an `ORDER BY` ([rerank phases](#rerank-phases) and [rank profiles](#rank-profiles-a-ranking-kept-with-its-table) included) of a table with a primary key: `"log"` in the body of `POST /v1/query` or `/v1/sql` (`true`, or an object of options), `db.query_logged(sql, params, context=...)` in [Python](python.md#the-rank-log), `Db::query_logged` in Rust. It runs with `score()` and [`features()`](#features-the-values-a-ranking-read) added to its columns, answers with the columns it asked for and the request's id (`request`), and writes its rows to the log in one transaction once it has answered: a logged query costs a write.
- **Options**: `context`, whom the request served (a user, a session, a query class), which the export reads events by; `request`, the request's id (a random one when left out; logging a request's id again overwrites its rows at the same positions); `variant`, the client's name for the ranking that served (an A/B arm); `candidates`, a number of rows from the query's `OFFSET` to log, more than its `LIMIT` returns, those past the `LIMIT` logged as not shown (unshown negatives); `ts`, when it was served (ISO 8601 text or microseconds; now when left out), for replaying past traffic; `table`, another log table; `interleave`, a second ranking to show in the same list ([interleaving](#interleaving-two-rankings)); `explore`, a policy that shows the top rows in a randomized order and logs each row's chance ([exploring](#exploring-a-log-that-evaluates-rankings-it-never-served)).
- **A row** holds its request, time and context, the key of the row served (`row_key`, as text), its `position` from 0 (the `OFFSET` included), whether it was `shown`, its `score()`, and `features`: a JSON object of each `features()` column, named by its SQL text, whose numbers read back to the bits the ranking computed. The request's first row also keeps its `query`: the SQL as the client sent it and its parameters as they were bound (a vector as `{"$vector": [...]}`, a time as `{"$ts": microseconds}`), which the [relevance autopilot](#the-relevance-autopilot) replays. A table made by hand serves as a log if it has these columns, of these types (with `retain = '90 days'`, say); it may leave out `query`, and then keeps no query (a log made before the column was added: `ALTER TABLE rank_log ADD COLUMN query KEYWORD OPTIONS(indexed = false)`). Each row shown also keeps its `propensity`, the chance the [logging policy](#exploring-a-log-that-evaluates-rankings-it-never-served) put it where it was shown (1 for a query that does not explore), and the request's first row its `policy` (as JSON, `{"policy": "none"}` when it does not explore) and `took_ms`, how long the query took before its rows were written. A log made before these columns logs as it did and refuses `explore`, naming the statement that adds them: `ALTER TABLE rank_log ADD COLUMN IF NOT EXISTS propensity FLOAT, ADD COLUMN IF NOT EXISTS prefix_propensity FLOAT, ADD COLUMN IF NOT EXISTS policy KEYWORD OPTIONS(indexed = false), ADD COLUMN IF NOT EXISTS took_ms FLOAT`.
- **Through a coordinator** the query is the coordinator's, so the values are one database's ([features over shards](#features-the-values-a-ranking-read)), and the rows go to the shards their keys place them on; the first logged query makes the table on every shard. A replica refuses a logged query, the log being a write; a primary ships the table it makes to its copies, as it ships the rows. A shard's query (`"shard": true`) is not logged.
- **Cost.** Computing the values is nearly free, since the ranking computes them anyway; the write is the cost. On a 4-core cloud VM over HTTP, with 100,000 documents and one client, a query took 1.87 ms at the median plain, 1.85 ms with its values added and 4.33 ms logged (7.81 ms logging 100 candidates); writing the same ten rows alone through `/v1/write` took 1.97 ms. Without the disk's flush (`--no-sync`) the logged query took 3.50 ms: the sync is a third of the log's cost here, and the rest is the write itself. Four clients got 1,620 plain and 670 logged queries a second. A row took 152 bytes in the segments (an Intel Xeon @ 2.10GHz, 16.9 GB, Linux 6.18; `chloedb-server/results/rank_log/vm.json` and `vm-no-sync.json`, from `chloedb-rank-log-bench`). The export read 70,000 records a second, each with a history of 20 events and a label.
#### Exporting the log for training
The export reads a log table back from one snapshot, one record per logged row, with what happened around it as of its time, from a table of events (a user's views, clicks, purchases): the context's last events before the row (its history, for a sequence model), and a label from the events on the row's key after it, within a window.
```sh
curl -s localhost:7700/v1/rank_log/export -H 'content-type: application/json' -d '{"events": {"table": "events", "user": "usr", "item": "item", "time": "ts", "action": "action"},
"history": 20, "window": "30 minutes", "grades": {"click": 1, "buy": 3}, "since": "2026-10-01"}'
# {"id": "9f0c...#0", "request": "9f0c...", "ts": 1793338200000000, "context": "u42", "row_key": "d17", "position": 0, "shown": true,
# "score": 7.31, "variant": "b", "label": 3.0,
# "features": {"bm25(body, :t)": 6.09, "bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0))": 7.31, "rating": 2.0},
# "history_items": ["d3", "d9", ...], "history_times": [...], "history_actions": ["view", "click", ...]}
```
- **Records** come as NDJSON from `POST /v1/rank_log/export`, as a list of dicts from `db.export_rank_log(...)` in Python, and from `Db::export_rank_log` in Rust, context by context, each context's rows in the order they were served. Times are microseconds since the epoch. `since` and `until` keep the rows served in `[since, until)`, and `table` names another log.
- **`events`** names a table, its column of contexts (`user`, `KEYWORD` or `INT`), of the rows the events were about (`item`), of when they happened (`time`, a `TIMESTAMP` or an `INT` of microseconds), and optionally of what they were (`action`). `OPTIONS(shard_by = 'usr', cluster_by = 'usr')` keeps each user's events together, on one shard and in few pages.
- **History**: with `history` set to n, the context's last n events before the row's time, oldest first. **Label**: with `window`, a period (`'30 minutes'`) or seconds, the best grade among the context's events on the row's key in the window after the row's time, `grades` giving each action's (an event whose action has none is not a label; without `grades` every event grades 1), and 0 when there is none. A label written on the row wins. A row without a context has no history and no label but its own.
- **As of the row's time**, by the events' own times: an event timed before a row is in its history even when it arrived after the row was served, which a query at the time could not have seen. The features are the values served, never recomputed.
- **Through a coordinator** the export and the interleaving credit run their queries over every shard, each read whole by a scroll, rather than from one snapshot ([cluster limits](cluster-limits.md)). Logs placed by context (a hand-made log with `context KEYWORD NOT NULL` and `shard_by = 'context'`) and events placed by user then give each shard every row and event of its contexts.
#### Interleaving two rankings
An A/B test shows each user one ranking and compares the users; interleaving shows each user both, in one list, and asks which ranking's rows the user acted on. Each request sets the two side by side for the same user and the same query, so it tells two rankings apart with ten to a hundred times fewer requests than an A/B test of the same two (Chapelle et al., "Large-scale validation and analysis of interleaved search evaluation", TOIS 2012).
```sh
curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) DESC LIMIT 10", "params": {"t": "mrna vaccine"},
"log": {"context": "u42", "interleave": {"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10", "variants": ["bm25", "rated"]}}}'
# {"columns": ["id", "title"], "rows": [...], "request": "9f0c...", "teams": ["rated", "bm25", "bm25", "rated", ...], "logged": {"rows": 10, ...}}
curl -s localhost:7700/v1/rank_log/interleaving -H 'content-type: application/json' -d '{"events": {"table": "events", "user": "usr", "item": "item", "time": "ts", "action": "action"}, "window": "30 minutes"}'
# {"pairs": [{"variants": ["bm25", "rated"], "requests": 4120, "acted": 1630, "wins": [690, 820], "ties": 120, "delta": -0.040, "p": 0.00089}], "took_ms": 61.3}
```
- **The list** is team draft (Radlinski, Kurup and Joachims, CIKM 2008): both queries run, on one snapshot, and in each round the ranking with fewer rows in the list, or a coin's choice when they have as many, adds its best row not yet in it, up to the logged query's `LIMIT`. A row both rankings hold goes to the one that took it. The coin is seeded by the request's id, so the same request draws the same list. When one ranking runs out, the other's rows fill the list for neither team. `teams` in the answer names each row's ranking; show the rows, not the teams.
- **The second ranking** is a `SELECT` of the same table answering the same columns, with the same parameters. Both need a `LIMIT` and no `OFFSET` (a draft is of a first page), and `candidates` and `variant` are left out: each row shown is logged with its own ranking's score and features and its team's name as its `variant` (`variants`, `["a", "b"]` unless named).
- **The credit**: `POST /v1/rank_log/interleaving` takes the export's body and reads the log as the export does, labels included. A request is interleaved when its shown rows carry two variants, and it goes to the team whose rows its user acted on more (a label above 0), or is a tie; a request nobody acted on counts for neither. `delta` is Chapelle et al.'s Δ, (wins of the first + ties / 2) / requests acted on − 0.5, above 0 when the first ranking (by name) is preferred; `p` is the two-sided sign test of the wins, ties left out. `Db::interleaving_credit` gives the same in Rust, and the command center's Recsys eval draws it.
#### Exploring: a log that evaluates rankings it never served
A log of what one ranking served says little about another: a row it never showed was never clicked, and a row it always put first was clicked partly for being first. Off-policy evaluation asks what another ranking would have earned from the clicks the log holds, by weighting each by how likely the serving policy was to show it there (inverse propensity scoring and the estimators built on it: Li et al., "Offline evaluation of ranking policies with click models", KDD 2018; Joachims et al., "Unbiased learning-to-rank with biased feedback", WSDM 2017). Those estimates are only as good as the chances logged, and a ranking that always serves the same list in the same order has a chance of 1 or 0 for every row, which weights nothing. With `explore`, a logged query shows its top rows in a randomized order drawn by a policy, and logs each row's chance exactly.
```sh
curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) DESC LIMIT 10", "params": {"t": "mrna vaccine"},
"log": {"context": "u42", "explore": {"policy": "softmax", "tau": 0.5, "top": 20}}}'
# {"columns": ["id", "title"], "rows": [...], "request": "9f0c...", "propensities": [0.61, 0.28, 0.33, ...], "logged": {"rows": 20, ...}}
```
| policy | options | what it shows | propensity |
|---|---|---|---|
| `none` | | the ranking as it is | 1 |
| `epsilon` | `epsilon`, `top` (10) | with chance ε the top `top` in a uniform random order, otherwise the ranking | (1 − ε)·[the row's own place] + ε / `top` |
| `shuffle` | `top` (10) | the top `top` in a uniform random order | 1 / `top` |
| `swap` | `top` (10) | the first row swapped with a uniform place up to `top`, itself included | exact, per place |
| `softmax` | `tau`, `top` (20), `by` (`score`) | the top `top` drawn one place at a time by Plackett–Luce, row i with weight exp(sᵢ / τ) | exact: per place by a one-dimensional integral, the list's prefix in closed form |
- **The draw** takes the ranking's first `top` rows (the query's `LIMIT` is raised to `top` when it is smaller, and `candidates` adds rows past them), orders them by the policy and answers the query's `LIMIT` of them: those are shown, the rest are logged as not shown. A query explores its first page only: it needs a `LIMIT` and no `OFFSET`, and is not also interleaved. `softmax` reads each row's `score()` (`by: "score"`, so τ is in the score's units; a row without a score is refused) or its rank (`by: "rank"`, sᵢ = −ln(i + 1), a weight of (i + 1)^(−1/τ) whatever the scores' scale). `swap` is Joachims et al.'s intervention, which measures position bias at little cost to users; `softmax` is the stochastic policy that evaluating any other ranking needs, since every row of its top has a chance at every place.
- **The chances**: `propensities` in the answer are the shown rows', in order, and each row's `propensity` in the log is the chance the policy put that row at that place. A row's `prefix_propensity` is the chance of the list down to it: of that row at that place and every row above it where it was, which a cascade estimator weights by. `softmax`'s per-place chance is the integral of its Gumbel form, ∫₀¹ P(k of the other rows' Gumbels beat this row's | v) dv, computed by tanh-sinh quadrature to within 1e-6 (1e-9 for weights less than a million times apart) and kept for the last 16 lists a thread drew; the other policies' are closed forms. The request's first row keeps the policy with its options (`policy`).
- **The same request draws the same list**: the draw is seeded by the request's id, as interleaving's coin is, so replaying a logged request checks itself, and a client that names its requests by user and query shows one user the same list until the ranking's rows change. Through a coordinator the draw is the coordinator's, over the merged ranking: three shards draw what one database draws.
- **Cost**: the rows past the `LIMIT` and up to `top` are logged too, as `candidates` are, so a wider `top` is a bigger write; the draw itself reads only the scores the ranking computed.
#### The relevance autopilot
The autopilot reads the queries the rank log kept, proposes new numbers for the [rank profile](#rank-profiles-a-ranking-kept-with-its-table) they rank by, and shows the measured before and after on the database's own data before anything changes.
```sh
curl -s localhost:7700/v1/relevance/autopilot -H 'content-type: application/json' -d '{"profile": "recall", "since": "2026-11-01", "judge": true}'
# {"report": {"verdict": "propose", "reason": "held-out nDCG@10 0.412 to 0.447 (+0.035, 95% interval +0.019 to +0.052): 61 queries better, 12 worse (sign test p = 0.000)",
# "statement": "CREATE OR REPLACE RANK PROFILE recall ON docs AS SELECT * FROM docs ORDER BY bm25(body, :q) + 0.4 * bm25(title, :q) DESC",
# "changes": [{"knob": "0.05 * bm25(title, :q)", "from": 0.05, "to": 0.4}], "snapshot": 81231,
# "held_out": {"queries": 140, "before": 0.412, "after": 0.447, "better": 61, "worse": 12, "p": 0.0, "ci": [0.019, 0.052]},
# "latency_ms": {"before": {"p50": 1.9, "p95": 4.1}, "after": {"p50": 1.9, "p95": 4.3}}, "holes": [...], ...},
# "proposal": "6932a1f0-9e1b...", "judged": {"rows": 184, "model": "...", "errors": []}}
curl -s -X POST localhost:7700/v1/relevance/proposals/6932a1f0-9e1b.../apply
```
(The numbers above show the shape of an answer; they were not measured.)
- **The workload** is each distinct query (its SQL and parameters, named by a `qid`) that a logged request asked with `ORDER BY rank_profile(...)`, the most recent first (`max_queries`, 500), logged since `since`. The profile is the one most of them rank by unless `table` and `profile` name one. The autopilot tunes a profile because a profile is what a proposal can change; a query that ranks by an expression of its own is left out.
- **Grades** are the rank log's labels (a row's mean over the query's requests) and the judgments table's, `relevance_judgments` unless `judgments` names another, which win for the same row: `{id: '#', qid, query, row_key, grade, source, ts}`, grades 0 to 3 (UMBRELA's scale and the relevance lab's). A query needs a row graded above 0 to count, and the autopilot says nothing with fewer than `min_queries` (20) such queries.
- **The search** is coordinate ascent (Metzler and Croft, 2007) over the profile's numbers: the defaults of its parameters (`WITH (w => 0.2)`) and the numeric literals of its rankings' `ORDER BY` expressions, 0 and 1 left out as structure. Each number is tried at 2, 0.5, 1.25, 0.8, 4 and 0.25 times its value, and a step is taken when the training queries' mean nDCG@k (`k`, 10) rises, until no step helps or `budget` (60) candidates have been replayed. A proposal is the profile with some numbers moved, nothing else.
- **The proof**: every query reads one snapshot (`snapshot` is its sequence number), so both rankings see the same rows and the same statistics. The share `held_out` (0.3) of the graded queries, picked by a seeded hash of their `qid`, is kept out of the search, and the verdict is drawn from those alone: `propose` when their mean nDCG@k rose by more than `min_gain` (0.005), more of them were made better than worse and the sign test of the two says so at `alpha` (0.05) (a few queries up by much and more down by a little is `not_significant`, though its mean rose), and the 95th percentile of the queries' time did not grow by more than `max_slowdown` (1.5 times, beyond 2 ms). Otherwise `no_change`, `no_gain`, `not_significant`, `slower`, `too_few_judged` or `no_workload`, each with a `reason`. The report has the training, held-out and overall measures, a bootstrap interval of the held-out change, each query's nDCG both ways, and the share of the top k that was graded. With the same data and `seed` a report is made again the same.
- **Rows no one graded** gain nothing, which favours the ranking now (its rows are the ones people saw and graded). The report lists them (`holes`, `max_holes`, 200); with `"judge": true` the server has Claude grade them first (UMBRELA's prompt, as `POST /v1/judge` does; the server's `ANTHROPIC_API_KEY` or `api_key`), writes the grades to the judgments table with source `claude`, and measures again.
- **Proposals** are kept in `relevance_proposals` with the report (`keep`, true): `GET /v1/relevance/proposals` lists them, `GET /v1/relevance/proposals/:id` gives one with its proof, `POST .../:id/apply` runs its `CREATE OR REPLACE RANK PROFILE` and `POST .../:id/dismiss` closes it. Applying is refused once the profile has changed since the measure (the proof is of another profile: run the autopilot again), and for a verdict other than `propose` unless `{"force": true}`. A proposal's row is not taken at its word: its statement is applied only when it is the profile now with some of its numbers moved (never another ranking, even with `force`), and its proof is made again first, on the log and the grades as they are, with the options it was measured with (kept in the proof as `options`); a proof made again that does not propose it is refused unless `{"force": true}`. Running, applying and dismissing need an admin key, and so does any write to `relevance_proposals` and `relevance_judgments` (a write key's answers 403 `scope_refused`). The command center's Labs have it as Relevance autopilot.
- **In Rust**: `Db::autopilot(&Options)` gives the report and reads only; `Db::keep_proposal`, `Db::apply_proposal` and `Db::add_judgments` write. A coordinator does not run it, since its shards hold a snapshot each: run it on a single server or on each shard's server.
#### Sequence models: `encode('model', history)`
A sequence model reads what a user did, newest first, and gives a vector in the space of an item field, so that the items it ranks first are the ones the user is likely to want next:
```sql
-- the next item for a user, from their last 200 events
SELECT id, score() FROM items
WHERE NOT id IN (SELECT item FROM events WHERE usr = :u)
ORDER BY similarity(emb, encode('next', (SELECT item, action, ts FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 200), now => :now)) DESC
LIMIT 10;
-- as a feature of a ranking, next to the text's
WITH top AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 200)
SELECT id, score() FROM top
ORDER BY bm25(title, :q) + 2 * coalesce(dot(emb, encode('next', (SELECT item, ts FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 200))), 0) DESC
LIMIT 10;
```
- **The history** is a subquery of the user's events, newest first: its first column is an item's primary key in the model's table, then optionally what the event was (a text column: `view`, `buy`, a rating) and when (a `TIMESTAMP`, or a number of microseconds since the epoch, as the [rank log's export](#exporting-the-log-for-training) writes them). With two columns the second is the time when it is a `TIMESTAMP` and the action when it is text; a number there is refused, since it could be either, so give microseconds as the third column (`SELECT item, NULL, micros`). Order it by time, descending: a row newer than one above it is an error rather than a history read backwards. Of its rows whose item has a vector, the model reads the newest, up to the length it was trained on, as training reads a history. `now =>` is the time of the request (a `TIMESTAMP`, microseconds or ISO 8601 text; the clock's by default): the time since the newest event is part of what the model reads.
- **Where it goes**: `similarity(field, encode(…))` ranks the field's nearest items (the dot product with the model's vector: a search of the field's index, its best scored exactly, as [`maxsim`](#maxsimfield-vectors-several-query-vectors) runs one), `maxsim(field, encode(…))` the same as one query vector, and `dot(field, encode(…))` is a number in any ranking expression. A user with no events has no vector: `similarity` and `maxsim` then return no rows, and `dot` is `NULL`. The history runs once a query, however often `encode` appears in it.
- **The model** is a small causal transformer (SASRec's): each event is its item's vector, projected, plus a learned vector for its action, for the time until the next event (in powers of two of seconds) and for its position; two layers of attention over the events, each seeing only the ones before it, then the last event's output, projected into the item field's space and normalized. It is the directory `//` (`config.json`, `model.safetensors` and `items.safetensors`), in the models directory [`gbdt`](#ranking-models-gbdtmodel-features)'s files come from. The config names the table and the vector field the model was trained on and their dimension: a database without that field, or with one of another dimension, refuses the model, and so do `similarity` and `maxsim` over another field. `items.safetensors` holds the item vectors it was trained with, and is part of the model's version (its hash): a history whose items have other vectors in the field is refused, naming one, since the model's vector would be in a space it never saw. An item the file does not list (one added since) is read with the field's vector.
- **Training** is `chloedb.train.sequence` in Python, with PyTorch (`pip install torch`), from a table of events, the rank log's export, or lists of `(item, action, time)`:
```python
import chloedb, chloedb.train
db = chloedb.Database.open("shop.chloedb")
out = chloedb.train.sequence(db, "next", table="items", field="emb",
events={"table": "events", "user": "usr", "item": "item", "action": "action", "time": "ts"},
learn_items=True)
chloedb.train.write_vectors(db, "next") # with learn_items, the items' learned vectors into items.emb
```
It trains next-item prediction over each user's events, with every item in the field (`negatives="all"`) or the other targets of a batch (`"in_batch"`, for many items; with `logq=True` and `uniform_negatives=n` it no longer learns to rank popular items low) as the negatives, and writes the model where `models=` says (the models directory by default), with the item vectors it was trained with. With `learn_items=True` the item vectors are trained too, starting from the field's: `chloedb.train.write_vectors` writes them into the field, changing nothing else of each row, and until then `encode` refuses the model. Otherwise the field's vectors are kept as they are and only the model learns.
- **Equal to PyTorch's**: ChloeDB's vector is the one the PyTorch module gives for the same history, within 2·10⁻⁵ (`chloedb/tests/sequence.rs`), and the items a query ranks are the ones PyTorch's vector ranks.
- **How well it ranks**: on MovieLens-1M and Amazon Beauty, leave-one-out over every item as SASRec is measured, a model of two layers that reads items only has Recall@10 0.278 and 0.066 (NDCG@10 0.159 and 0.041). That is above the original SASRec's published 0.250 and 0.061, but below SASRec trained the same way as this model, with cross-entropy over every item (SASRec+, 0.315 on MovieLens), and on Beauty below counted transitions from the same events ([`chloedb.next_items`](next-items.md), 0.069): good, not the best published. Reading times too, it has 0.319 and 0.077. Both MovieLens runs stopped at a time limit while still improving. ChloeDB's answers equal PyTorch's on every user ([`results/sequence`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence), with the protocol and the published numbers), and CI checks ranking quality on MovieLens-1M against popularity and item-kNN baselines and ChloeDB's other sources (`chloedb/results/sequence/gate.py`): there a model trained for an hour has Recall@10 0.306, `ppr` over what came after what 0.242, counted transitions 0.211 and item-kNN 0.069.
- **What it costs**: the model alone, on one thread of a cloud VM's Xeon at 2.80 GHz, takes 0.09 ms for 10 events, 0.28 ms for 50 and 1.5 ms for 200 (p50); the whole query, reading the history and searching the field, 0.6 to 0.7 ms on Beauty's 50 events and 2 to 3 ms on MovieLens's 200. Keep `max_len` as short as the ranking allows.
- **A plan names the model and the hash of its files** and needs the plan feature `encode`; a database or shard whose files of that name are others refuses it. A coordinator runs `encode` itself, from the history its shards return, so it needs the model; the shards don't.
### `decay(field, origin, scale, …)`: closeness to a value
A numeric column's closeness to `origin`, as in Elasticsearch's decay functions. With `d = max(0, |x − origin| − offset)`, the score is 1 at `d = 0` and `decay` at `d = scale`:
| `shape` | score |
|---|---|
| `'exp'` (default) | `decay^(d / scale)` |
| `'gauss'` | `decay^((d / scale)²)` |
| `'linear'` | `max(0, 1 − (1 − decay) · d / scale)`, reaching 0 at `scale / (1 − decay)` |
Options: `offset => 0`, `decay => 0.5`, `shape => 'exp'`. Rows without a value score 0. `now()` as the origin is the current Unix time in seconds, so `decay(published, now(), 86400)` halves a row's score for each day of age. `decay` ranks on its own, inside `rrf` and weighted sums, and in products.
### Products: boosting relevance by a row's values
Multiplying scores boosts relevance by what a row holds:
```sql
-- fresh news first: BM25 halved at 30 days old
SELECT id FROM news ORDER BY bm25(body, :t) * decay(published, now(), 2592000) DESC LIMIT 10;
-- similar products, weighted by their rating
SELECT id FROM products ORDER BY similarity(emb, :q) * rating DESC LIMIT 10;
```
A product's factors are scores (`bm25`, `similarity`, `ppr`, `decay`) and numeric columns, one of them a relevance score (`bm25`, `similarity`, a graph's); a product of a row's own values alone (`rating * clicks`, `decay(..) * rating`) is arithmetic, and ranks as the numbers multiply. Candidates are the top `depth` (100) rows of each relevance factor, scored exactly by every factor; a product of one text score and row values (`bm25(..) * decay(..)`, `bm25(..) * rating`) is a [rank-safe boost](#rank-safe-boosts) and ranks every row the text matches. A factor below 0 (a negative similarity) or missing (a `NULL` column) counts as 0, so the product of two negatives cannot rank high. Over shards, each shard returns its factors' raw scores and the coordinator multiplies them, so a split collection ranks like the whole one.
### A column
`ORDER BY year DESC` orders by a numeric column. Rows without a value come last in either direction (as in Elasticsearch); `ORDER BY year DESC NULLS FIRST` puts them first. Their `score()` is `NULL`. With no `ORDER BY`, rows come in storage order.
With a `LIMIT`, the rows can come from the column's blocks of 128 rows, best block first by its zone map (its largest value for `DESC`, smallest for `ASC`), stopping at the first block whose best value is worse than the k-th row found. A row's filter is checked only when its value can still make the cut, and blocks the filter's own zone maps rule out are never read. So the ten most clicked of the 560,000 ORCAS queries starting with `a` read about 150 of 81,000 blocks, and about 10 when the table is clustered by query (`OPTIONS(cluster_by = 'id')`), where each prefix's rows sit together. The planner keeps the plain scan of the matches when they are a few thousand rows, or under 1 in 64 of the rows the zone maps admit (a rare prefix of an unclustered table, whose k-th best value is low enough that most blocks could hold a better one), and switches to it when the blocks have cost half of what it would (a filter that rejects the best values, `WHERE n < 3 ORDER BY n DESC`); `NULLS FIRST` always scans. Values written in place are read first, so counters kept with `UPDATE ... SET n = n + 1` rank by their current value.
## Typos and synonyms
`MATCH` and `bm25` take two options that widen a search beyond the words written:
```sql
SELECT id FROM papers WHERE MATCH(body, 'nueral netwrok', fuzzy => 'auto') LIMIT 10;
SELECT id, score() FROM papers ORDER BY bm25(body, 'nueral netwrok', fuzzy => 1) DESC LIMIT 10;
SELECT id FROM papers WHERE MATCH(body, 'gnn', synonyms => 1) LIMIT 10;
```
- **`fuzzy => 1` or `2`** also matches the indexed terms within that many edits of each word, counting an insertion, deletion, substitution or swap of two neighbouring letters as one edit (optimal string alignment). With an analyzer that stems, the edits are counted on the word as typed: a term matches when it is the stem of a word within that many edits of the typed word, so `choclate` finds `chocol` (*chocolate*, one edit), though its own stem, `choclat`, is three edits from it. **Changed:** the edits were counted between stems before, so a typo that the stemmer cut differently (`choclate`, `vegtable`) found nothing with `fuzzy => 'auto'` or `~`. **`fuzzy => 'auto'`** allows no edits for words of 1 or 2 letters, 1 for 3 to 5 letters and 2 for longer ones. In the `MATCH` grammar, `word~` is `'auto'` for one word and `word~1`, `word~2` choose. A ranked query adds the 50 nearest terms of each word, each weighted `1 − edits / length` (at least 0.1), as Lucene's fuzzy queries do. A word and its typo neighbours share one document frequency, the largest among them, so a rare misspelling scores below the word rather than above it; the expansion is found once per query over every segment's dictionary, so all segments, and the plan line `bm25 expanded with N terms`, agree. Each dictionary is walked as a trie, skipping every run of terms whose start is already too many edits away, rather than tested term by term. A skip inside a block of the front-coded dictionary passes terms by their lengths alone, and each letter's row of edits is worked out for up to 63 letters of the word at once in a machine word (Wu and Manber's bit-parallel matching, with Hyyrö's swap of two letters). For a word of a typed query looked up in the 797,472 analysed terms of ORCAS's 10.4 million queries, the median lookup takes 1.4 ms with one edit and 7.8 ms with two (2.1 and 16.5 ms before the in-block skip and the bit-parallel rows, run just before on the same machine), against 77 and 106 ms testing every term (one thread of a 4-core cloud VM, Intel Xeon @ 2.10GHz; [`results/text/fuzzy-orcas.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/text), `chloedb-fuzzy-bench`). A query walks a copy of each segment's terms laid out flat in memory rather than the dictionary itself: each term whole, where it ends and how many bytes it shares with the one before, so a step decodes nothing and a jump past a run of terms reads only those shared counts. The copy is made at the segment's first typo query (12 ms for 530,000 terms) and kept while the segment lives, at the terms' bytes plus 5 bytes a term (6.5 MB for 2 million MS MARCO passages, against the dictionary's 4.7 MB). On a shard of 5 million MS MARCO passages in three segments, with the engine comparison's typed queries, a word's walks over the three segments take 9.4 ms against 22.6 ms over the dictionaries, the median typed query 17.0 ms against 29.1 ms, and four clients, one thread each, get 215 typed queries a second against 124 (a 4-core cloud VM, Intel Xeon @ 2.80GHz).
- **A ranked query with `fuzzy => 'auto'` and no `MATCH` of its text corrects typos** rather than widening every word, by how many documents hold the word and its neighbours, as a spelling corrector does. A word in at least 1 in 10,000 of the documents, and in 2 or more, is taken as spelled right and gets no neighbours: typos are rare words. Another word gets only its neighbours in more documents than it, each weighted, besides `1 − edits / length`, by the chance it was meant: `x / (x + df)` with `x = df′ × 0.01^edits`, where `df` counts the word's documents and `df′` the neighbour's (a noisy channel that takes each term as likely as its documents and each edit as a 1 in 100 slip). A word in no document is a typo of each of its neighbours (chance 1), and a word nearly as common as its neighbour almost surely means itself. A shard chooses the neighbours by its own counts, the same in a coordinator's statistics round as in its query, and takes the chances from the collection's counts the coordinator sends. `MATCH`, and `bm25` with `fuzzy => 1` or `2`, still widen every word.
- **A `bm25` of the text a `MATCH` filters by takes the `MATCH`'s `fuzzy`** (and its `syntax => 'plain'`) when it names none, **and ranks every row the `MATCH` keeps**: `WHERE MATCH(title, 'wireles hedphones', fuzzy => 'auto') ORDER BY bm25(title, 'wireles hedphones') DESC` ranks the rows the filter found, rather than scoring the words as written and dropping them all. The text must be the same (case and outer spaces aside), on the same field, with the same `fuzzy`, taken or given again. Beside such a `MATCH`, `bm25` widens each word as the `MATCH` does, to every indexed term within its edits, rather than correcting it: a word the index has gets its neighbours too, each weighted `1 − edits / length` and, with `'auto'`, by the chance it was meant, so `colour` ranks the names spelt *colour* first and those spelt *color* after them. **Changed:** with `'auto'`, `bm25` left a word the index has as written, so the rows the `MATCH` found by a neighbour scored nothing and dropped out: on 2 names with *colour* and 5 with *color*, `colour` returned 2 of the 7 rows its `WHERE` matched while the misspelling `colur` returned all 7, and on 3,970 recipes `lasagne` returned 2 of 27.
- **A typo is looked up as typed too**: under a stemming analyzer such as `english`, a word the index does not hold looks for neighbours of the word as written as well as of its stem, so `wireles` (stem `wirel`, three edits from `wireless`) finds `wireless` one edit away.
On 500,477 passages, half of MS MARCO's first million, with the first 300 dev queries, each given a typo as the engine comparison does (two letters of its longest word swapped; 271 queries take one), the typed query's top 10 holds 0.685 of the top 10 that plain `bm25` gives the query as written, against 0.346 widening every word and 0.383 without typo tolerance. On the queries as written, `'auto'` keeps 0.946 of plain `bm25`'s top 10, against 0.340 widening every word. The median typed query takes 10.0 ms, against 48.5 ms before this change and 20.6 ms widening every word on its faster walk and scoring, and the median query as written 0.35 ms (19 ms widening every word), since it walks no dictionary. Through a coordinator over two shards of the million passages (both halves, on the same machine), the median typed query takes 15.8 ms against 112 ms before (p99 30 against 287 ms), and four clients get 137 typed queries a second against 17.7: a shard also walks once per query rather than twice, its statistics round and its query sharing the walk. On BEIR's SciFact and NFCorpus, whose queries are spelled right, nDCG@10 with `'auto'` went from 0.673 and 0.294 widening every word to 0.693 and 0.331, level with plain `bm25` (0.691 and 0.329). The thresholds were chosen on MS MARCO's dev queries, not BEIR's test queries. One segment on a 4-core cloud VM, Intel Xeon @ 2.10GHz; `cargo run --release --example typo_queries`.
- **`synonyms => 1`** also matches what the server's synonym list says a word or phrase means. The list is in Solr's format: `laptop, notebook, portable computer` makes each find the others, and `tv => television` makes `tv` find `television` but not the reverse. Both sides are analysed like documents, so `laptops` finds `notebook`. A one-word synonym of a word shares that word's document frequency, as Lucene's synonym queries do; the words of a longer synonym score on their own. [chloedb-server](server.md) loads it from `--synonyms FILE` and edits it at `/v1/synonyms`; from Rust, set `ExecOptions::synonyms`. Without a list, `synonyms => 1` is an error that says so.
- **A table's own list** (experimental). `CREATE SYNONYMS ON products AS 'sofa, couch\ntv => television'` gives a table rules of its own, which `synonyms => 1` on that table's searches uses after the server's list. It is kept as the stored function `synonyms_products()`, so it has versions (`CREATE OR REPLACE SYNONYMS` makes the next, `CREATE OR REPLACE FUNCTION synonyms_products FROM VERSION 1` goes back) and a coordinator writes it on every shard; `DROP SYNONYMS [IF EXISTS] ON products` removes it. The rules are checked when the list is made. `GET /v1/synonyms` lists each table's.
- **Mined synonyms** (experimental) are proposals for that list, never applied by themselves: `Db::mine_synonyms` or `POST /v1/synonyms/mine` reads the words of a stored text field and embeds the 3,000 most frequent with the model of one of the table's vector fields, proposing pairs whose vectors are close (cosine 0.6 or more) and whose spellings are not alike (a model of word pieces puts `adel` by `adela`; numbers such as `b10` and `b11` still pass); or reads a table of searches (`context`, `ts` in seconds, `text`) and proposes `a => b` where people of two or more contexts rewrote one word of a search into another within a minute. On Wayfair's WANDS (`chloedb-synonyms-eval`, `chloedb/results/text/synonyms_wands.json`, an Intel Xeon at 2.10 GHz, 4 cores), the words of 42,994 product names embedded by potion-retrieval-32M gave pairs such as `kids, children`, `bike, bicycle` and `picture, photo` beside related words that are not synonyms (`animal, dog`, `hawaii, honolulu`), and none of the lists made a measurable difference to nDCG@10 (0.4327 without; 0.4343 with the 33 rules at cosine 0.6, p = 0.31), while the 462 rules at 0.4 lowered it to 0.4231 (p = 0.007). Read the proposals before keeping them. A mining keeps to bounds whoever asks: 200,000 rows read, 5,000 words compared, a cosine of 0.3 or more and 10 proposals a word at most; on a server it takes an admin key.
## Query expansion: `expand`
> **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release.
`bm25(body, :q, expand => 10)` ranks by the query's words and by the words its first ranking's top 10 rows hold most: pseudo-relevance feedback (RM3). It finds rows that use other words for what the query asks, such as `antibodies` for `vaccines`.
```sql
SELECT id, title FROM papers ORDER BY bm25(body, :q, expand => 10) DESC LIMIT 10;
SELECT id, title FROM papers WHERE year >= 2023
ORDER BY bm25(body, :q, expand => :n, expand_terms => 10, expand_weight => 0.7) DESC LIMIT 10;
```
- **How.** The query runs in two steps. The first ranks the rows as the call would without `expand`, through the query's `WHERE`, and reads the field's text of the top `n` (`SELECT body, score() FROM papers WHERE year >= 2023 ORDER BY bm25(body, :q) DESC LIMIT 10`). Each of those rows weighs its terms by its share of the scores and each term's share of the row; the `expand_terms` best terms over all of them share `1 − expand_weight` of the weight, and the query's own terms share `expand_weight`. The second step is the query with the call rewritten to those analysed, weighted terms (`bm25(body, 'vaccin^0.85 antibodi^0.03 immun^0.03 ...', syntax => 'terms')`), and the answer's plan lines start with what was added: `bm25(body) expanded from 10 rows of papers with 20 terms: antibodi 0.031, immun 0.029, ...`.
- **Options.** `expand` is the rows read, from 0 (no expansion, the call as written) to 100; `expand_terms` the terms added, up to 100; `expand_weight` the query's own share, from 0 to 1. Each may be a parameter (`expand => :n`). A call that expands takes no `min`, `min_rows` or `max_rows`.
- **Where.** In a `SELECT` of one table, in its columns, `WHERE` or `ORDER BY`, and in a `WITH` or a subquery of one table. A join is refused, and so is `expand` in a rank profile or a stored function. On a coordinator over shards the first step is an ordinary query of the shards, merged, and the coordinator rewrites the query, so every shard ranks by the same terms.
- **Cost.** A second query and the analysis of `n` rows' text: on BEIR's SciFact, NFCorpus and ArguAna the median query took 1.8, 1.7 and 2.9 ms against 0.09, 0.03 and 0.77 ms for plain `bm25` (one core of a 4-core cloud VM, Intel Xeon @ 2.10GHz).
- **Quality.** The defaults (10 rows, 20 terms, 0.85) were chosen on SciFact's train and NFCorpus's dev judgements (`chloedb/results/text/bm25_rm3_tuning_*.json`). On the test judgements, nDCG@10 went from 0.691 to 0.693 on SciFact (p = 0.55), 0.329 to 0.346 on NFCorpus (p = 0.0001) and 0.362 to 0.369 on ArguAna (p = 0.0006) (`chloedb/results/text/bm25_rm3.json`, `chloedb-bm25-eval --variants plain,rm3`). Expansion helps most where queries are short and documents use a field's own vocabulary; a setting that keeps less of the query (0.5) lowered SciFact to 0.646, so measure before lowering `expand_weight`.
## Understanding a query's words: `understand`
> **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release.
`bm25(field, :q, understand => 'boost')` reads the words of a search for the values of the table's `KEYWORD` fields they name (`white`, a colour; `coffee table`, a class) and for ranges of numbers (`under $300`), and ranks by the text and by them:
```sql
SELECT id, name FROM products
ORDER BY bm25(body, :q, understand => 'boost', understand_fields => 'class, color, price') DESC LIMIT 10;
-- :q = 'white coffee table under $300' ranks as
-- bm25(body, 'white coffee table') * (1 + 0.25 * (CASE WHEN color = 'white' THEN 1 ELSE 0 END
-- + CASE WHEN class IN ('Coffee Tables', 'Coffee & Cocktail Tables') THEN 1 ELSE 0 END
-- + CASE WHEN price < 300 THEN 1 ELSE 0 END))
```
- **What names a value.** A field's values are read with a query (`SELECT color, COUNT(*) ... GROUP BY color`, once per version of the table but at most once a second for a table that takes writes, one query at a time reading it while the others use the one before; on a coordinator once a minute) and analysed as the text field is. Words name a value when they are a run of its words, in its order, that ends with its last word, its head: `coffee table` names `Coffee Tables` and `Coffee & Cocktail Tables`, and `chair` every value that ends in chairs, but `table` does not name `Table Lamps`. A run inside a longer one of another field is that one's (`coffee` of `coffee table` is not the colour coffee). Values of several fields named by the same words are one condition, any of them.
- **A check against the rows.** A run counts only when, of the rows whose text holds its words, at least `understand_share` (0.05) hold one of its values: `up` is not the brand Up when almost no row that says up is of it. That is one query a run, counting both (`SELECT COUNT(*), SUM(CASE WHEN .. THEN 1 ELSE 0 END) ... WHERE MATCH(..)`), and runs of the same words and values share one. A text is understood in its first 32 words, and a call uses its first 16 runs, so that a pasted page costs what a query does.
- **Ranges.** `under`, `below`, `less than`, `up to`, `over`, `above`, `more than`, `at least`, `between .. and ..`, `since`, `after` and `before` followed by a number (`$1,500`, `2.5`, `10k`) are a range of a numeric field named in `understand_fields`: the one named next to them (`over 10 citations`), a field named for years for a year (`since 2020`), or the only one. Their words leave the ranked text, and a `MATCH` of the same text on the same field too (`WHERE MATCH(body, :q) ORDER BY bm25(body, :q, understand => 'filter')`, every word needed), which would otherwise need `under 100` in a row's text and keep no row. **Changed:** such a `MATCH` kept the words of a range before, so a search that needed every word found nothing when its text named a range.
- **Modes.** `'boost'` multiplies the text score by `1 + understand_weight` (0.25) for each condition a row meets, a [rank-safe boost](#rank-safe-boosts). Inside a fusion (`rrf(bm25(.., understand => 'boost'), similarity(..))`, `tmm(..)`, `minmax(..)`), which fuses scores rather than a score times a boost, the boost multiplies the whole fusion instead. `'filter'` also puts each run that names a value in full, and each range, in the `WHERE` (a row without a value of the field is kept). `'off'` is the call as written. Each option may be a parameter (`understand => :mode`).
- **Fields.** Without `understand_fields`, every `KEYWORD` field of the table but its key, and a field of more than 20,000 values is left out as a name rather than a facet (its read stops at 20,001); a listed field reads up to 200,000. A call that understands ranks the rows of one table, without a join, and goes with `expand` (it understands first).
- `Db::understand(table, field, text, options)` (chloedb-server's [`POST /v1/understand`](server.md)) returns what a text says without ranking: its runs, the values each names, their shares, the ranges and the conditions.
- **Measured.** On Wayfair's WANDS (42,994 products, 480 queries; name and description as the text, class, category, colour, style, material, shape and product type as keyword fields) `'boost'` moved nDCG@10 from 0.707 to 0.731 on the odd-numbered queries (p = 0.002), and the classes its words named held the class the query asks for in 262 of 343 queries; `'filter'` lowered it to 0.631, since a product judged relevant often lacks the value or holds another. On Amazon's ESCI (its 8,956 US test queries of the small version and the 164,900 products judged for them; brand and colour listed) `'boost'` moved it from 0.394 to 0.396 (p = 0.007): its titles already hold their brands. Without the check against the rows, ESCI's ranking fell to 0.391. The weight and share were chosen on the even-numbered queries of both. A query took 0.9 to 1.0 ms at the median, against 0.07 to 0.12 ms for `bm25` alone (`chloedb-understand-eval`, `chloedb/results/text/understand_wands.json` and `understand_esci.json`, Intel Xeon @ 2.10GHz, 4 cores).
## Did you mean: correcting a query's words
> **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release.
`Db::correct(table, field, text)` (chloedb-server's [`POST /v1/correct`](server.md)) returns the text with the words that look like typos of a TEXT field's terms replaced, for a search box to offer as "did you mean":
```json
{"text": "mRNA vaccines for neural networks", "changed": true,
"words": [{"word": "vacines", "term": "vacin", "to": "vaccin", "to_word": "vaccines", "edits": 1, "chance": 0.86}, ...]}
```
- A word is corrected only when no row holds it: a word some document uses is a word of the collection. Words with digits or capitals inside (`p150n`, `dLNs`) are names and codes, and stay.
- Its neighbours are the field's terms one edit away (up to 5 letters) or two (longer), as `fuzzy => 'auto'` finds them, and it takes the one most likely meant if that chance is at least 0.5: the noisy channel of [typos](#typos-and-synonyms), with an unseen word counted as in 0.05 documents, so that a neighbour one edit away must be in 5 or more documents. The edits are counted from the word as typed to the word shown, which is the word nearest it that the analyzer reads as the corrected term (`ifnlammation` gives `inflammation`, `choclate` gives `chocolate` and `wireles` gives `wireless`, not `wirees`). **Changed:** the edits were counted between stems before, so a typo whose stem drifted from the right one's (`choclate`, `vegtable`) had no neighbour, and the word shown was the term with the typed word's ending, which could be no word.
- On BEIR's queries with a typo typed in (two letters of the longest word swapped), it corrected 0.75, 0.69 and 0.88 of them back to the words as written on SciFact, NFCorpus and ArguAna (0.73, 0.66 and 0.85 when the edits were counted between stems); of the queries it changed, 0.92, 0.91 and 0.99 were corrected back; and it changed 4.0%, 2.8% and 0% of the queries as written (`chloedb/results/text/bm25_did_you_mean.json`, variant `typed_corrected`). For ranking, `fuzzy => 'auto'` stays better than ranking the corrected text: nDCG@10 0.691 against 0.674 on SciFact, as it widens each word with its likely neighbours rather than choosing one.
- A coordinator corrects as one server does, by its shards' document counts summed: the words' own, then, for a word in none, those of its neighbours (each shard's nearest 50 within the edits allowed).
### Times later and earlier: `INTERVAL`
```sql
SELECT host, COUNT(*) FROM syslog WHERE ts > now() - INTERVAL '15 minutes' GROUP BY host;
SELECT id FROM events WHERE at >= date_trunc('day', now()) - INTERVAL '7 days';
SELECT id, due + INTERVAL '2 days' AS reminder FROM tasks;
SELECT TIMESTAMP '2026-01-31' + INTERVAL '1 month'; -- 2026-02-28T00:00:00Z
```
- **`INTERVAL 'text'`** is a length of time: numbers each with a unit, `'15 minutes'`, `'1 day 12 hours'`, `'-2 weeks'`, `'90s'`, or `INTERVAL '15' MINUTE`. The units are `microseconds`, `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months` and `years`, singular or plural, and `us`, `ms`, `s`, `sec`, `min`, `m` (a minute), `h`, `hr`, `d`, `w`, `mon` and `y`. It is added to a time or subtracted from one; alone it is an error.
- **A time written as a value** (`now()`, `CURRENT_TIMESTAMP`, `TIMESTAMP '2026-10-01'`, `CAST('...' AS TIMESTAMP)`, `date_trunc('day', now())`) moved by an interval is one value, computed once for the statement: `ts > now() - INTERVAL '2 hours'` is a range of `ts`, which the index answers, in `WHERE`, `ON` and a join's side alike. Months and years move it on the calendar, a day past the new month's end becoming its last day (January 31 plus a month is February 28 or 29), as in PostgreSQL.
- **A column moved by an interval** (`due + INTERVAL '2 days'`) is computed row by row, in microseconds; a month or a year has no fixed number of them, so an interval with months moves only values. A `NULL` time gives `NULL`.
- **A number added to a time** written as a value is an error that points to `INTERVAL` (`now() - 3600` could mean seconds or microseconds). Over the rows, a number added to a `TIMESTAMP` column counts microseconds: `at + 3600000000` is an hour later.
## Aggregates
```sql
SELECT category, COUNT(*) FROM docs
WHERE MATCH(body, 'india') AND year >= 2000
GROUP BY category ORDER BY 2 DESC LIMIT 5;
SELECT category, topic, COUNT(*) AS n, AVG(rating), MIN(year), MAX(year), COUNT(DISTINCT source)
FROM docs WHERE year >= 2000
GROUP BY category, topic HAVING n > 20 ORDER BY AVG(rating) DESC LIMIT 10;
SELECT COUNT(*), SUM(clicks), AVG(rating) FROM docs WHERE MATCH(body, 'india');
SELECT item, MEDIAN(price), PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY price) AS p90
FROM snapshots GROUP BY item HAVING MEDIAN(price) > 100 ORDER BY p90 DESC;
SELECT host, COUNT(*) FILTER (WHERE severity = 'error') AS errors, COUNT(*) AS total
FROM syslog GROUP BY host ORDER BY errors DESC LIMIT 10;
SELECT brand, AVG(price), STDDEV(price), CORR(rating, price) FROM products GROUP BY brand;
SELECT customer, STRING_AGG(sku, ', ' ORDER BY sku) AS skus FROM orders GROUP BY customer;
```
- **`GROUP BY`** takes one or more indexed `KEYWORD`, `INT` or `FLOAT` columns, or [parts of times](#parts-of-times-date_trunc-extract-and-strftime) of a `TIMESTAMP` column (`date_trunc('day', at)`), by name, position or alias, which the index groups. A stored `TEXT` column, or a column kept without an index, groups too (`GROUP BY billing_country`, `SELECT DISTINCT billing_country`): its stored values are read with the rows and grouped in memory, as over derived rows, each distinct text its own group (case and spaces count). A multi-valued column puts a row in one group per value, over one table, joined rows or derived rows alike, and so does `SELECT DISTINCT`, which is `GROUP BY` its columns. The rows without a value form the group `NULL`, as in SQL, and `SELECT DISTINCT` lists `NULL` once.
- **Aggregates** are `COUNT(*)`, `COUNT(f)`, `COUNT(DISTINCT f)`, `SUM(f)` and `AVG(f)` over numeric columns, `MIN(f)` and `MAX(f)` over numeric or keyword columns, the [percentiles](#percentiles) of numeric columns, and the statistical aggregates below. `COUNT(f)`, `COUNT(DISTINCT f)`, `MIN(f)` and `MAX(f)` of a stored `TEXT` column (or a column kept without an index) count and compare its stored values, read with the rows. Every selected column is a group column or inside an aggregate. Without `GROUP BY` they summarize every row that passes `WHERE`, in one row (`COUNT(*)` 0 and the others `NULL` when none does).
- **`FILTER (WHERE condition)`** after an aggregate aggregates only the rows the condition holds for: `COUNT(*) FILTER (WHERE severity = 'error')` counts the errors of each group, beside `COUNT(*)` of all its rows. It is the aggregate of a `CASE` (`COUNT(CASE WHEN severity = 'error' THEN 1 END)`), and any aggregate takes it, in `SELECT`, `HAVING` and `ORDER BY`; a column without an alias is named as written. `FILTER` on a function that is not an aggregate, or on a [window](#window-functions) aggregate, is an error.
- **`STRING_AGG(x, separator [ORDER BY …])`** is the values of `x` that are not `NULL`, as text, with the separator (a constant text) between them, in the order of its `ORDER BY` (the rows' order without one), and `NULL` when there are none, as in PostgreSQL. `x` may be any value, a number written as `||` writes it, where PostgreSQL takes text only. The aggregates of one `SELECT` order their values one way: two `STRING_AGG`s with different `ORDER BY`s are refused (compute one in a subquery). It is computed over rows in memory, as over joined rows (over shards, on the coordinator), and takes `FILTER`, but not `DISTINCT` (`STRING_AGG(x, ', ')` over `SELECT DISTINCT x` in a subquery) or `OVER`. A plan with it needs the plan feature `sql_functions`.
- **Statistical aggregates**: `STDDEV(x)` and `STDDEV_SAMP(x)`, the sample standard deviation; `STDDEV_POP(x)`; `VARIANCE(x)` and `VAR_SAMP(x)`, the sample variance; `VAR_POP(x)`; `COVAR_SAMP(y, x)` and `COVAR_POP(y, x)`; and `CORR(y, x)`, the Pearson correlation. As in PostgreSQL, `NULL`s are left out (the two-variable ones take the rows with both values), the sample forms are `NULL` for fewer than two values and the population forms for none, and `CORR` is `NULL` when either variable does not vary. They are computed from sums and counts in one pass (the sum of squares less the square of the sum over n), so they merge over shards as `SUM` and `COUNT` do, and with values far larger than their spread (times in microseconds) lose digits to rounding.
- **`HAVING`** filters groups by their aggregates, written out or by alias, with comparisons, `BETWEEN`, `AND`, `OR` and `NOT`, in three-valued logic: an aggregate of no values (`AVG(rating)` of a group without ratings) is `NULL`, so neither `AVG(rating) < 3` nor `NOT (AVG(rating) < 3)` keeps that group.
- **`ORDER BY`** a group column, an aggregate or a position, each by name or by its alias in the `SELECT` list (`SELECT zone AS z, COUNT(*) AS n ... GROUP BY zone ORDER BY n DESC, z`), with a tie-break; without one, the largest groups come first. The group of rows without a value comes last in either direction, and first with `NULLS FIRST` (`ORDER BY passenger_count DESC NULLS FIRST`). `LIMIT` and `OFFSET` apply to groups. **Changed:** 0.3.8 and earlier refused `ORDER BY` a group column's alias, and `NULLS FIRST` after `GROUP BY` or `DISTINCT`.
A `SUM` or `AVG` of `FLOAT` values is exact: the values are added without rounding and the total is rounded once, so it does not depend on the order rows are read in, nor on the [engine](#subqueries-with-and-joins) that runs it: ChloeDB's operators and DataFusion add the same way, so a total, and a `RANK` or an order over it, stay the same when a table grows past the rows at which DataFusion takes a plan over (two totals of 43.62 tie on both, where adding in order gives one of them as 43.620000000000005). **Changed:** 0.3.8 and earlier added in order on DataFusion, so such a tie broke once a query read more than 4,096 rows. A database groups its segments on several threads and merges them, and the answer is the same bits as on one thread. A coordinator over shards merges partial aggregates (sums and counts for `AVG`, the distinct values for `COUNT(DISTINCT)`), so the answers are the same as on one server, except that each shard sends its `FLOAT` sum rounded once, so a sum over shards can differ from one server's in its last bit.
### Percentiles
`PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY f)` is the value a fraction `p` (0 to 1) of the way from the group's least value of `f` to its greatest, interpolated between the two values around that position, a `FLOAT`; `MEDIAN(f)` is `PERCENTILE_CONT(0.5)`. `PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY f)` is the least value that at least a fraction `p` of the values are at most: one of the values, of `f`'s type (a `TIMESTAMP`'s times too). The answers are PostgreSQL's: of `n` values in order, `PERCENTILE_DISC(p)` is the one at position ⌈p·n⌉ (counting from 1, the first for `p` = 0), and `PERCENTILE_CONT(p)` the one at position p·(n − 1) counting from 0, interpolated in doubles. `NULL`s are left out, and a group without values gives `NULL`. A column without an alias is named as the call reads, `PERCENTILE_CONT(price, 0.9)`.
- **Of columns and expressions.** Over one table they take indexed `INT` and `FLOAT` columns, read from the columns as the other aggregates are; over joined or derived rows, any numeric expression (`MEDIAN(s.price * 1.2)`). `p` is a constant or a parameter (`:p`); the order is ascending (`ORDER BY f DESC` is an error: write `1 - p`). They are aggregates of groups, not window functions.
- **Exact, so they hold the values.** A group keeps each of its values (8 bytes each, counted against the [query's memory budget](server.md#limits)) and orders them once when it is read: a median over 5 million rows holds 40 MB. A shard sends a group's values to the coordinator as runs of equal values, so prices that repeat travel once with their count, and the coordinator's answer is one server's. Plans with a percentile carry the plan feature `percentiles`, which a version of ChloeDB from before them refuses by name.
### Approximate percentiles
```sql
SELECT date_bin('5 minutes', ts) AS b, service, approx_percentile(latency, 0.99) AS p99
FROM logs WHERE ts >= '2026-11-12' GROUP BY b, service;
```
`approx_percentile(f, p)` is `PERCENTILE_DISC(p)` of the group's values (the one at position ⌈p·n⌉ in order) within 1% of it, a `FLOAT`, from a [DDSketch](https://arxiv.org/abs/1908.10693) of the group's values rather than the values themselves. `p` = 0 and 1 give the least and greatest values exactly. It takes what the exact percentiles take, `INT` and `FLOAT` columns over one table and numeric expressions over joined or derived rows, except `TIMESTAMP`s.
- **A few KB a group, however many rows.** A sketch counts each value in a bucket of values within 1% of each other, and keeps at most 1,024 buckets of each sign (4 KB): the bound holds for values up to about 10⁸ times apart, as latencies are, and past that the least ones are folded together, so the low percentiles of such a spread lose it first. A p99 over 100 million rows holds a few KB rather than 800 MB.
- **Exact merges.** Sketches of segments, threads and shards add up to the sketch of all the values, so the answer does not depend on how rows were split: a coordinator's answer is one server's. A shard sends a group's sketch as versioned bytes (base64 text), which a coordinator reads only in the version it knows. Plans with one carry the plan feature `approx_percentiles`, which a version of ChloeDB from before it refuses by name.
### Rollups: `CREATE ROLLUP`, a materialized view of counts over time
> **Experimental.** Rollups are new in 0.3.1, and their options, columns and refresh may change in a later release.
A rollup is a table of counts, sums, least and greatest values per bucket of time and per group, kept up to date from another table as rows arrive: ChloeDB's materialized view (a continuous aggregate) of a `GROUP BY` of time. Precomputed daily or hourly counts, kept up to date without a job of your own, are one: a time-bucket query over weeks of logs reads a few thousand rows of the rollup instead of millions of the table.
```sql
-- Orders per day and status, kept up to date as orders arrive.
CREATE ROLLUP orders_daily ON orders AS SELECT date_trunc('day', created_at), status, COUNT(*);
SELECT bucket, status, count FROM orders_daily ORDER BY bucket DESC;
```
It needs an admin key that is not limited to tables, and `check_sql` checks one without making it.
```sql
CREATE ROLLUP logs_5m ON logs OPTIONS(lateness = '10 minutes', retain = '400 days') AS
SELECT date_bin('5 minutes', ts), service, severity, COUNT(*), SUM(latency), COUNT(latency), MAX(latency) AS worst
WHERE severity <> 'DEBUG';
SELECT date_trunc('hour', bucket) AS h, service, SUM(count), SUM(sum_latency) / SUM(count_latency) AS mean, MAX(worst)
FROM logs_5m WHERE bucket >= '2026-11-01' GROUP BY h, service;
REFRESH ROLLUP logs_5m; -- now, without waiting for the background job
REFRESH ROLLUP logs_5m FULL; -- every bucket, for rows later than the lateness
REFRESH ROLLUP logs_5m REBUILD; -- fold every bucket again, after an UPDATE
DROP ROLLUP IF EXISTS logs_5m;
```
- **The bucket** is `date_bin('', field)`, any whole number of seconds, minutes, hours, days or weeks counted from 1970-01-01, or `date_trunc('second' | 'minute' | 'hour' | 'day', field)`, of a `TIMESTAMP` column. The groups are `KEYWORD`, `INT`, `BOOL` or `TIMESTAMP` columns, and the aggregates `COUNT(*)`, `COUNT(f)` (the rows whose `f` is not NULL), and `SUM(f)`, `MIN(f)`, `MAX(f)` and `AVG(f)` of numeric columns (`MIN` and `MAX` of a `TIMESTAMP` too). A `WHERE` keeps some rows only; `FROM`, when written, names the table after `ON`.
- **The rollup is an ordinary table**, named by the statement, with a row per bucket and group: `rollup_key` (its primary key, a number made of the bucket and the group's place in it), the bucket (`bucket`, or the name `AS` gives it), the group columns, typed as in the table, and a column per aggregate, `count`, `count_`, `sum_`, `min_` and `max_` unless `AS` names it. `AVG(f)` keeps `sum_f` and `count_f`, so the mean is `SUM(sum_f) / SUM(count_f)`, which skips NULLs as `AVG(f)` does (a rollup made before 0.3.4 keeps `sum_f` and `count` only, whose quotient counts the rows without a value too; make it again for the other). A `count` column (`COUNT(*)`) is always kept. A rollup that counts a field's values is marked `needs_chloedb_0_3_4` in its definition, which 0.3.3 refuses by name rather than refresh it wrong. Its columns are kept in the columns only, not again as whole rows (`stored = false`), which a rollup's queries never need: about 40 bytes a row. Query it by name, and add its rows up into larger buckets or fewer groups (`SUM(count)`, `MIN(min_latency)`); a query of the table is not rewritten onto it. `OPTIONS(retain = ...)` is the rollup's own [retention](#tables), kept by its bucket: a rollup outlives the rows it counts.
- **How it is kept.** `CREATE ROLLUP` folds the table's rows at once, a day of buckets to a query: 20 million lines in about 8 seconds. On a server it answers what it made: the rollup, whether it is `filled`, the buckets folded and the rows written; it leaves the first fold of a table of over a million rows to its refresher, a few seconds on, and until then the rollup has fewer rows (`REFRESH ROLLUP` fills it at once). From then on a refresh compares, bucket by bucket, how many rows of the table the bucket holds with the rollup's count for it (one count by bucket for a day of buckets at a time: every bucket of 20 million lines over 30 days in a quarter of a second), and folds again the buckets that differ, each in one transaction. A plain refresh compares the buckets from the clock less the `lateness` (10 minutes by default; from the newest row, when that is older) to the newest row, and any the rollup has not folded up to now: a row dated in the future is folded, but does not take the window away from the present. `FULL` compares them all, and `REBUILD` folds them all again whatever their counts. Only buckets that hold rows, in the table or in the rollup, are compared, so a row dated in 1970 or 2099 costs a query, not a walk over every bucket between. One refresh of a rollup runs at a time; another waits for it. A server refreshes every rollup every few seconds, and all their buckets every few minutes, each rollup on its own: one whose refresh fails is logged by name, and the others go on. `GET /v1/tables` gives a rollup's table a `rollup` entry with the table it reads, its last good refresh and its last error. An embedding program calls `Db::spawn_rollups` (or runs `REFRESH ROLLUP`; `Db::rollup_health` says how each went). Buckets older than the table's `retain` are not compared again, so they keep what they counted. A bucket of a time so far from 1970 that its key would not fit in 64 bits (a time in nanoseconds stored as microseconds, say) is not folded, and the refresh says so in the log.
- **For tables rows are added to**, such as logs: a change that leaves a bucket's count as it was (an `UPDATE`, or a delete and an insert into one bucket between two refreshes) is never seen by a plain or a `FULL` refresh, only by `REFRESH ROLLUP name REBUILD`.
- **Its table and the one it reads stay as the rollup needs them.** `DROP TABLE` of a table a rollup reads is refused while the rollup is there (`DROP ROLLUP` first, or drop both in one `DROP TABLE logs, logs_5m`); `DROP TABLE` of a rollup's own table drops its definition too. `ALTER TABLE` that drops or renames a column a rollup reads, or that changes a rollup's own table, is refused. The definition is kept as a [stored function](#stored-functions), `rollup__()`, whose body is the statement, so it needs nothing new on disk and travels with the database. On a server with shards, each shard keeps a rollup of its own rows; rollups through a coordinator come later.
## Subqueries, WITH and joins
```sql
-- IN (SELECT ...): rows of the categories that 2001's surveys are in
SELECT id FROM papers WHERE category IN (SELECT category FROM papers WHERE year = 2001 AND kind = 'survey');
-- a scalar subquery
SELECT id, year FROM papers WHERE year > (SELECT AVG(year) FROM papers) ORDER BY year DESC LIMIT 10;
-- WITH: name a query and read it like the table
WITH top AS (SELECT id FROM papers ORDER BY bm25(body, 'graph neural network') DESC LIMIT 50)
SELECT category, COUNT(*) FROM top GROUP BY category;
-- a WITH result as graph seeds
WITH top AS (SELECT id FROM papers ORDER BY bm25(body, 'graph neural network') DESC LIMIT 20)
SELECT id FROM papers WHERE REACHABLE(cites, (SELECT id FROM top), dir => 'in') LIMIT 100;
-- FROM (SELECT ...) and DISTINCT
SELECT category, n FROM (SELECT category, COUNT(*) AS n FROM papers GROUP BY category) AS t WHERE n > 50 ORDER BY n DESC;
SELECT DISTINCT category FROM papers WHERE MATCH(body, 'graph');
-- joins of two tables: on a key, a multi-valued column (each of its values), or three tables
SELECT p.id, v.name FROM papers p JOIN venues v ON p.venue = v.id WHERE v.rank >= 4 AND MATCH(p.body, 'graph');
SELECT a.name, COUNT(*) AS n FROM papers p JOIN authors a ON p.authors = a.id GROUP BY a.name ORDER BY n DESC LIMIT 10;
SELECT p.id, a.name, v.name FROM papers p JOIN authors a ON p.authors = a.id LEFT JOIN venues v ON p.venue = v.id WHERE p.year = 2024;
SELECT id FROM papers WHERE venue IN (SELECT id FROM venues WHERE field = 'ir');
-- joins of the table with itself: along an EDGES field, or on a shared value
SELECT a.id, b.id AS cited FROM papers a JOIN papers b ON a.cites = b.id WHERE a.year >= 2020;
SELECT a.id, b.id AS cited_by FROM papers a LEFT JOIN papers b ON b.cites = a.id WHERE a.id IN ('p1', 'p2');
SELECT b.id, COUNT(*) AS n FROM papers a JOIN papers b ON a.cites = b.id GROUP BY b.id ORDER BY n DESC LIMIT 10;
SELECT a.id, b.id FROM papers a JOIN papers b ON a.category = b.category AND b.id != a.id WHERE a.id = 'p1';
```
Each plans into operators over the single-table queries above ([`EXPLAIN`](#explain) shows them), all run on one snapshot, so every single-table query uses the indexes. Each is bound as it is built, never printed as SQL and parsed again:
- **`IN (SELECT ...)`** and **`NOT IN`** run the subquery first and filter with its values (a multi-valued column contributes each value). **`EXISTS`** is true or false, and a **scalar subquery** must return one column and at most one row. An `EXISTS` or `NOT EXISTS` in `WHERE` whose subquery names the outer row by one equality, `WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer = c.id AND o.total > 100)`, is a semi join (an anti join for `NOT EXISTS`): it runs as `c.id IN (SELECT o.customer FROM orders o WHERE o.total > 100)`, the subquery once, with `NULL`s as `EXISTS` has them (`NOT EXISTS` keeps an outer row whose `c.id` is `NULL`). The subquery may have a `LIMIT`, not groups, aggregates or an `OFFSET`; one that names the outer row anywhere else is an error. A subquery's values reach the outer query's filter as values, so its indexes serve it: `year > (SELECT AVG(year) ...)` is a range of `year`. A scalar subquery that names a column of the outer row is [correlated](#correlated-subqueries-a-ranking-that-reads-other-rows): it ranks, and is not a condition.
- **`WITH`** results and **`FROM (SELECT ...)`** are read like a table. A `WITH` whose rows are rows of the table (no aggregates) keeps their keys, so an outer query over it reads the table restricted to those rows, in the `WITH`'s order unless it orders them itself, and `(SELECT id FROM top)` can seed a graph. The outer query may name any of the table's columns (`SELECT id, category FROM top`), while `*` is the `WITH`'s own columns, as in any SQL. A `score()` or `hops()` the `WITH` selects (`score() AS s`) is read from its rows, by name or by `*`. A column a `WITH` or a `FROM (SELECT ...)` selects as `s.item`, without an alias, is its column `item`, as SQL names it, so the query reading it says `ls.item`; two columns of one name keep their tables' (`s.id`, `p.id`). `WITH RECURSIVE` is not supported: `REACHABLE` and `PATH` walk links.
- **Joins** are `JOIN` (inner), `LEFT JOIN`, `FULL [OUTER] JOIN`, and `RIGHT JOIN` as the first join of a `FROM` (`a RIGHT JOIN b ON ...` runs as `b LEFT JOIN a ON ...`, and `*` keeps `a`'s columns first), of a table with another, with itself or with a `WITH` result; name each side (`papers a JOIN papers b`). `ON` needs an equality between the sides, of two columns of one kind: `KEYWORD`, or `INT` and `FLOAT` compared as numbers (`p.venue = a.id`, an `INT` with a `KEYWORD`, is an error). A multi-valued column joins each of its values. Comparing an `EDGES` field with the key follows its links (`a.cites = b.id`: *b* is a row *a* links to; `b.cites = a.id`: *b* links to *a*); links name keys of their own table, so they join a table with itself. Each `WHERE` or `ON` condition on one side filters that side's scan, and the second side reads only the rows whose join values the first side holds (`b.id IN (...)`, or for links the rows linking to them), before a hash join in memory. Groups of the second side's rows, a `GROUP BY` of its key (and of other columns of its rows) that aggregates only fields of the first side and is ordered by that key among others, are made in the first side's scan, by its join key, before the join (`SELECT p.id, p.title, COUNT(*) AS n FROM reviews r JOIN products p ON r.product_id = p.id GROUP BY p.id, p.title ORDER BY n DESC, p.id`): the join reads a row per group rather than per row. Text, vector and graph functions name one side (`MATCH(a.body, ...)`); `ORDER BY` a score ranks by that side's scan, and when the order is the first side's, scans of a growing number of its rows stop once `LIMIT` rows join. Joined columns of the answer are named by their expression (`b.title`) unless aliased, where PostgreSQL names them by the column alone (`title`): pandas and `chloedb.dbapi`'s `cursor.description` see `b.title`, so alias a column whose name a program reads (`b.title AS title`).
- **`FULL JOIN`** gives the rows of a `LEFT JOIN`, then each row of the right side that matched no row of the left, with `NULL`s for the left's columns, in the right's order (`ORDER BY` orders them as any rows): `SELECT coalesce(o.sku, s.sku) AS sku, o.qty, s.qty FROM orders o FULL JOIN stock s ON o.sku = s.sku`. A `NULL` key matches nothing, so its row comes once, from its own side. Since both sides keep their unmatched rows, no condition filters either side's scan: `ON`'s other conditions decide which pairs join (a row they part from every match keeps its `NULL`s), and `WHERE` filters the joined rows, so `WHERE o.sku IS NULL` keeps the stock no order names. Both sides are read whole, without the restriction to the first side's join values or the growing scan of a `LIMIT`. Joins after it join its rows as they join any. It runs on the operators (DataFusion leaves it to them), and through a coordinator, which joins the rows its shards answer; a plan with one needs the plan feature `full_join`.
- Over joined or derived rows, `WHERE`, `GROUP BY`, aggregates, `HAVING`, `ORDER BY`, `DISTINCT` and `LIMIT` also take arithmetic, `||`, `LIKE`, `ILIKE`, `CASE`, `COALESCE`, `LOWER`, `UPPER`, `LENGTH`, `ABS`, `ROUND`, `DOT`, `HASH` and the numeric functions of ranking expressions (`ln`, `pow`, `least`, ...). So does the `SELECT` list over one table (`SELECT id, rating * 2, lower(category), dot(emb, :q) FROM papers WHERE ...`): the table's query finds the rows and the columns are computed in memory, typed as over derived rows. A `SELECT` that also selects a ranking's value (`bm25(..) * 2`, `hops()`) computes its columns as ranking expressions do, as `FLOAT`s. Their conditions follow the same three-valued logic as a single table's, multi-valued columns included (`NOT (b.tags = 'red')` keeps rows without tags). Integer arithmetic is exact, and a result too big for an integer is a `FLOAT`; `/` gives a `FLOAT`, and dividing by zero gives `NULL`. `||` with a `NULL` gives `NULL`, as in PostgreSQL (`coalesce(note, '')` keeps the rest), and `LIKE` with a `NULL` side is `NULL`. `ROUND(x)` gives an `INT`: of a `FLOAT` it rounds half to even, as PostgreSQL rounds a `double precision` (`ROUND(price)` of 2.5 is 2 and of 3.5 is 4), and of a number written in the statement, or of a value made of such numbers alone (`ROUND(CASE WHEN qty > 0 THEN 2.5 END)`), half away from zero, as PostgreSQL rounds a `numeric` (`ROUND(2.5)` is 3); `ROUND(x, digits)`, `ROUND(x, 0)` included, rounds half away from zero, as PostgreSQL's `round(numeric, int)` does. A ranking expression's `round` rounds half away from zero, as it always has. `ORDER BY` puts rows without a value last in either direction unless `NULLS FIRST`, as over a single table.
- **Engines.** ChloeDB's own operators run these in memory, a row at a time. With the feature `datafusion`, which chloedb-server and the Python package turn on and ChloeCtx leaves off, [DataFusion](https://datafusion.apache.org) runs them on column batches once their single-table queries read more than 4,096 rows; below that the operators answer, faster on so few, reusing the rows DataFusion's attempt already read. Both give the same rows in the same order, and the same sums of floats, which both add exactly ([aggregates](#aggregates)). On two tables of 100,000 rows, a join with a group took 285 ms on the operators and 60 ms on DataFusion. On two tables of 100 rows it took 0.6 ms on the operators and 2.9 ms on DataFusion; the default engine (`auto`) answered in 1.2 ms. Measured with `chloedb/examples/df_join.rs` on a 4-core cloud Xeon at 2.10 GHz, 2026-11-01. `CHLOEDB_ENGINE` sets the engine:
- `auto`: the default;
- `operators`;
- `datafusion`: DataFusion, whatever the size;
- `datafusion-only`: a query DataFusion does not run fails, to find what it lacks.
The operators run what DataFusion does not run yet, and the plan's first line says why. Today that is joins along links, multi-valued columns as sort keys, correlated subqueries, and `maxsim` or `encode` over a subquery.
chloedb-server runs them on its engine over its own tables and as a [coordinator](server.md#sharding-one-coordinator-many-shards), which runs them above the rows its shards answer for each single-table query: on DataFusion, as Arrow columns from shards of [protocol 10](server.md#grpc).
- On the operators, each single-table query, `WITH` result and side of a join holds at most 1,000,000 rows. On DataFusion they hold as many rows as the query's memory budget allows, and past it sorts and groups spill to disk. `CROSS` joins, and a `RIGHT JOIN` after another join, are not supported.
The executor's plan lines (`--plan`, `/v1/explain`'s `plan`) list each single-table query that ran, with its rows and its own plan.
## Window functions
A window function gives each row a value computed over other rows, its *partition*, without folding them into one as `GROUP BY` does: a row's rank among its category's, the value of the row before, a running total, a moving average.
```sql
-- each paper's rank in its category by citations, and its category's average
SELECT id, category, cites,
RANK() OVER (PARTITION BY category ORDER BY cites DESC) AS r,
AVG(cites) OVER (PARTITION BY category) AS avg_cites
FROM papers WHERE year >= 2020;
-- the three most cited of each category: QUALIFY filters by a window
SELECT id, category, cites FROM papers
QUALIFY ROW_NUMBER() OVER (PARTITION BY category ORDER BY cites DESC, id) <= 3;
-- a running total and a moving average of the day before, the day and the day after
SELECT day, clicks,
SUM(clicks) OVER (ORDER BY day) AS total,
AVG(clicks) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS smooth,
clicks - LAG(clicks) OVER (ORDER BY day) AS change
FROM daily ORDER BY day;
-- over groups: categories ranked by size, and each one's share
SELECT category, COUNT(*) AS n, RANK() OVER (ORDER BY COUNT(*) DESC), COUNT(*) / SUM(COUNT(*)) OVER () AS share
FROM papers GROUP BY category;
-- one window, named once
SELECT id, ROW_NUMBER() OVER w, LAG(year) OVER w, SUM(cites) OVER (w ROWS 2 PRECEDING)
FROM papers WINDOW w AS (PARTITION BY category ORDER BY year);
```
- **Functions.** `ROW_NUMBER()`; `RANK()` and `DENSE_RANK()`; `PERCENT_RANK()` and `CUME_DIST()`, `FLOAT`s; `NTILE(n)`, buckets 1 to n as even as they can be, the first ones a row larger (as SQL says, and PostgreSQL and SQLite do); `LAG(x [, offset [, default]])` and `LEAD(..)`, `x` of the row `offset` rows before or after (1 by default), or `default` (`NULL` without one) past the partition's ends; `FIRST_VALUE(x)`, `LAST_VALUE(x)` and `NTH_VALUE(x, n)` of the row's frame; and the aggregates `COUNT(*)`, `COUNT(x)`, `SUM`, `AVG`, `MIN` and `MAX` of the frame. `NTILE`'s, `NTH_VALUE`'s and `LAG`'s numbers are constants. `COUNT(DISTINCT ..)`, `FILTER (WHERE ..)` and `IGNORE NULLS` are errors.
- **`OVER (PARTITION BY .. ORDER BY ..)`.** The partition is the rows with equal values of its expressions (`NULL` equal to `NULL`); without `PARTITION BY` it is every row. The window's `ORDER BY` orders the partition, its `NULL`s last unless `NULLS FIRST` as elsewhere; rows whose order keys are all equal are *peers*, and rows that tie keep the order they came in. Both take expressions of the rows (`PARTITION BY year % 10`, `ORDER BY lower(title)`), or over groups of the groups' values and aggregates.
- **Frames.** `FIRST_VALUE`, `LAST_VALUE`, `NTH_VALUE` and the aggregates read the rows of the row's frame: `ROWS BETWEEN start AND end` counts rows from the row, and `RANGE BETWEEN start AND end` takes the rows whose value of the window's one `ORDER BY` key is within the offsets of the row's (a row without a value has its peers, the other rows without one). The ends are `UNBOUNDED PRECEDING`, `n PRECEDING`, `CURRENT ROW` (in `RANGE`, the row's first or last peer), `n FOLLOWING` and `UNBOUNDED FOLLOWING`, in that order; `ROWS 2 PRECEDING` is `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW`. Without a frame, a window with an `ORDER BY` reads from the partition's first row to the row's last peer, so `SUM(x) OVER (ORDER BY day)` is a running total that counts a day's rows together, and a window without one reads the whole partition. The other functions read the partition whatever the frame says. `GROUPS` frames are errors.
- **Where they go.** A window function is a column of `SELECT`, a key of `ORDER BY`, or part of a condition of **`QUALIFY`**, which filters the rows after the windows are computed and may name a selected window by its alias (`QUALIFY r <= 3`). It is not part of `WHERE`, `GROUP BY` or `HAVING`, which come before, and a window function's argument, partition or order holds no other: compute that one in a subquery in `FROM`. In a grouped query the windows are computed over the groups `HAVING` keeps; `SELECT DISTINCT`, `ORDER BY` and `LIMIT` come after them, so `COUNT(*) OVER () ... LIMIT 5` counts every row.
- **`WINDOW w AS (..)`** names a window that `OVER w` uses as it is, and that `OVER (w ORDER BY ..)` or `OVER (w ROWS ..)` extends with an order or a frame it lacks; a window may name one before it (`WINDOW w AS (PARTITION BY a), v AS (w ORDER BY b)`).
- **Engines.** The operators sort each partition in memory; DataFusion runs windows on column batches, sorting and spilling within the query's memory budget, and both answer alike. The operators run a window DataFusion does not lower yet: a `LAG` or `LEAD` whose default is not a constant of the value's type, `FIRST_VALUE` and `LAST_VALUE` over a `RANGE` frame with an offset, `NTH_VALUE` over a `RANGE` frame that starts after the partition's first row, a `RANGE` offset of another type than its key (`0.5` over an `INT`), and windows over multi-valued columns.
The plan's node is `Window` (`Window: RANK() OVER (PARTITION BY category ORDER BY cites DESC)` in `EXPLAIN`, the functions computed after the rows' own columns), and its JSON needs the plan feature `window`; a version of ChloeDB from before it refuses the plan by that name.
## UNION, INTERSECT and EXCEPT
A set operation takes the rows of two queries together: `UNION` the rows of either, `INTERSECT` those of both, `EXCEPT` those of the first that the second lacks.
```sql
-- the categories of 2024's papers and of the reviews' papers, each once
SELECT category FROM papers WHERE year = 2024 UNION SELECT category FROM reviews;
-- every row of both, repeats kept, ranked together
SELECT id, cites AS n FROM papers WHERE cites > 100
UNION ALL
SELECT id, downloads FROM preprints WHERE downloads > 1000
ORDER BY n DESC LIMIT 10;
-- the venues 2023 had and 2024 lost
SELECT venue FROM papers WHERE year = 2023 EXCEPT SELECT venue FROM papers WHERE year = 2024;
-- a side ordered and cut on its own, in parentheses
(SELECT id FROM papers ORDER BY cites DESC LIMIT 5) UNION ALL (SELECT id FROM preprints ORDER BY downloads DESC LIMIT 5);
```
- **Columns.** Both sides select as many columns, matched by place, and the answer's columns are named as the first side's. A column of `INT`s on one side and `FLOAT`s on the other is `FLOAT`, the wider type, as in PostgreSQL and DuckDB: `SELECT 1 UNION ALL SELECT 2.5` is 1.0 and 2.5. Rows are equal when each of their values is, `NULL` equal to `NULL` and an `INT` equal to the `FLOAT` of its value.
- **`ALL`.** Without it each row comes once. With it, `UNION ALL` keeps every row of both sides; `INTERSECT ALL` keeps a row as many times as both sides have it, the fewer of the two counts; `EXCEPT ALL` as many times as the first side has it more than the second.
- **Order.** `INTERSECT` comes before `UNION` and `EXCEPT`, which go left to right, and parentheses group sides: `a UNION b INTERSECT c` is `a UNION (b INTERSECT c)`. `ORDER BY`, `LIMIT` and `OFFSET` at the end apply to the whole and name its columns; a side in parentheses takes its own. Without an `ORDER BY` the rows come in the sides' order: `UNION ALL` the first side's rows, then the second's; `UNION` those rows each where it first comes; `INTERSECT` and `EXCEPT` rows of the first side in its order, the first ones of rows equal to one another.
- **Anywhere a query goes**: a `WITH` result, a derived table `FROM (SELECT .. UNION ..) d`, or a subquery `x IN (SELECT .. UNION ..)`, and each side may group, join, rank, or compute windows. `UNION BY NAME` is an error.
- **Engines.** Both answer alike. The operators run a set operation DataFusion does not lower: one whose sides give a column types other than an `INT` and a `FLOAT` (text and a number), and `INTERSECT`, `EXCEPT` or `UNION` without `ALL` of a multi-valued column.
The plan's node is `SetOp` (`Union`, `Intersect all` and so on in `EXPLAIN`, the sides below it), and its JSON needs the plan feature `set_ops`; a version of ChloeDB from before it refuses the plan by that name.
## The first row of each group: DISTINCT ON
`SELECT DISTINCT ON (keys) ...` keeps, of the rows with equal keys, the first in the query's order, as PostgreSQL does: a row per group, the groups in the order of their first rows, and `LIMIT` and `OFFSET` count groups. With rows of a long video or document in a table of segments, it answers each video once, by its best segment:
```sql
-- each video's best clip, the 10 best videos
SELECT DISTINCT ON (video) video, id, start_ms, score() FROM clips
WHERE MATCH(transcript, 'penalty kick') ORDER BY bm25(transcript, 'penalty kick') DESC LIMIT 10;
-- each user's latest event
SELECT DISTINCT ON (usr) usr, item, ts FROM events ORDER BY ts DESC, id;
-- the best page of each PDF, by an image query's similarity
SELECT DISTINCT ON (doc) doc, page FROM pages ORDER BY similarity(emb, :q) DESC LIMIT 5;
-- over groups: each country's top seller
SELECT DISTINCT ON (country) country, seller, SUM(price) AS total FROM sales GROUP BY country, seller ORDER BY country, total DESC;
```
- **Keys** are expressions of the rows (`video`, `lower(lang)`, `year % 10`), or columns of the answer by name or number (`DISTINCT ON (2)`), and need not be selected. Keys are equal when their values are: `NULL` with `NULL`, and a multi-valued column's list with the same list.
- **The order.** PostgreSQL requires `ORDER BY` to start with the keys; ChloeDB does not, so `ORDER BY` a score gives the best row of each group, the best groups first. When `ORDER BY` does start with the keys, the answer is PostgreSQL's. Without `ORDER BY`, which row of a group is kept is not defined.
- **Reads.** When the query's order is the scan's (a score, or one numeric column), a `LIMIT` reads the scan in growing slices: four times the rows asked for (at least 32), then four times as many, until that many groups have a row or the scan runs out. A group with many rows near the top costs more reads, never a wrong answer. `DISTINCT ON` one keyword or `INT` field of a table ranked by `bm25` reads less: each segment keeps each group's first row as it scores ([`MAX k PER`](#at-most-k-rows-of-a-value-max-k-per) does the same with k rows), so the scan returns the rows asked for. Ordered by several columns, the rows are sorted in memory, and the scan holds at most 1,000,000 rows.
- **Shards.** A coordinator keeps the first rows over its shards' merged rows, so three shards give what one database does, whether or not the table is placed by the keys (`shard_by`).
The plan's node is `DistinctOn` (`Distinct on: video` in `EXPLAIN`), and its JSON needs the plan features `operators` and `distinct_on`; a version of ChloeDB from before it refuses the plan by that name.
## At most k rows of a value: `MAX k PER`
`ORDER BY ... MAX k PER field` keeps, of the rows with equal values of `field` (a `KEYWORD` or a number of one value: a `TEXT` field is an error, as rows rarely share a whole text), the first `k` in the query's order, and the rows kept stay in that order: a ranking with at most two clips of a video, three products of a brand or two arguments of a debate. `LIMIT` and `OFFSET` count the rows kept.
```sql
-- the 20 best clips, at most two of a video
SELECT id, video, score() FROM clips ORDER BY bm25(transcript, :q) DESC MAX 2 PER video LIMIT 20;
-- the newest products in stock, at most three of a brand
SELECT id, brand, title FROM products WHERE in_stock ORDER BY added DESC, id MAX 3 PER brand LIMIT 30;
-- in a subquery: of each video's two most viewed clips, those about a dog
SELECT id FROM clips WHERE MATCH(transcript, 'dog')
AND id IN (SELECT id FROM clips ORDER BY views DESC, id MAX 2 PER video LIMIT 1000);
```
- **It ends `ORDER BY`**, and needs one: the rows a value keeps are its first in that order. `k` is a whole number, 1 or more, and `MAX 1 PER x` is `DISTINCT ON (x)`, with the same plan.
- **A field of one value.** `field` is a field of the rows (`video`, `t.brand` in a join), and `NULL` is one value of its own. A multi-valued field is refused, since a row with several values would be in several groups.
- **Not with `DISTINCT`** or `DISTINCT ON`, which already keep one row of each.
- **Reads.** A table's own rows ranked by `bm25` and capped by a keyword or `INT` field keep the cap as they are scored: each segment keeps each value's best k rows (and the rows tied with its k-th) and skips the rows that can no longer reach the `LIMIT`, so the query reads its rows once. Other rankings, and caps over joined or derived rows or by other fields, read growing slices of the ranking until `LIMIT` rows are kept or it runs out, as [`DISTINCT ON`](#the-first-row-of-each-group-distinct-on) does. A field whose values cannot fill the `LIMIT`, such as one row of each of 15 topics for a `LIMIT` of 20, reads every row that matches either way, and returns 15.
- **Shards.** A coordinator keeps each value's first rows over its shards' merged rows, so three shards give what one database does.
The plan's node is `DistinctOn` with `per` (`At most 2 per: video` in `EXPLAIN`). With `k` above 1 its JSON needs the plan feature `per_cap`, so a version of ChloeDB from before it refuses the plan rather than keeping one row of each value. Python's builder writes it `.max_per(2, "video")`.
On ArguAna (BEIR's 8,674 arguments from 592 debates on 15 topics; a document's debate and topic are in its id), every one of the 1,406 queries ranked by `bm25(body, :q)`, its own argument left out as BEIR scores it, top 20. Times are the median over queries of each query's median of 3 runs, one thread on a 4-core cloud VM (Intel Xeon @ 2.10GHz):
| top 20 | nDCG@10 | debates | topics | p50 ms | p99 ms |
|---|---:|---:|---:|---:|---:|
| uncapped | 0.489 | 7.5 | 3.8 | 1.6 | 4.1 |
| `MAX 1 PER debate` | 0.307 | 20.0 | 7.2 | 2.4 | 5.4 |
| `MAX 2 PER debate` | 0.379 | 14.5 | 5.9 | 2.3 | 5.0 |
| `MAX 3 PER debate` | 0.419 | 12.6 | 5.4 | 2.3 | 5.5 |
| `MAX 1 PER topic` | 0.301 | 14.9 | 15.0 | 2.8 | 5.7 |
| `MAX 2 PER topic` | 0.376 | 16.3 | 11.4 | 2.6 | 5.4 |
| `MAX 3 PER topic` | 0.416 | 14.2 | 9.1 | 2.4 | 5.4 |
Debates and topics are the mean number of each in a query's answer. Each segment keeps the cap as it scores, so a cap costs about 1.5 times the uncapped query whatever the field: BM25 can skip fewer rows, since the 20th row kept scores lower than the 20th of all. One row of each of the 15 topics cannot fill 20 rows, so that query scores every argument that matches, once, and returns 15. Before the scan kept the cap, the same queries read growing slices of the ranking: 6.0 to 6.1 ms by debate, 7.1 and 18.8 ms for three and two per topic, and 549 ms for one per topic, which read every row again at each slice (with the uncapped query at 3.3 ms in that run).
Caps trade relevance for spread. ArguAna's answer to a query is the argument against it, in the query's own debate, so a cap on debates also caps how many of the right debate's arguments the ranking can show: nDCG@10 falls from 0.489 to 0.307 with one per debate, and to 0.419 with three. The run is `chloedb-per-cap-bench` ([`results/text/per_cap.json`](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/text/per_cap.json)).
## As much as fits: `PACK n TOKENS`
**Experimental:** what `PACK` reads and how it chooses may change between releases. Against the top rows of a ranking cut in the client ([measured](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/pack/README.md) on SciFact and NFCorpus), it reaches more of the relevant documents when the budget holds one to three (SciFact 0.74 against 0.65 at 500 tokens) and spends less of the budget on them, and the two are the same once it holds five or more.
A query's answer is often the context a language model is given, and the model has a budget of tokens, not of rows. `PACK n TOKENS` at the end of a SELECT fills that budget: it reads the query's rows in its order and decides each once, so that a long row, a row that repeats one already taken and a row linked to one taken are weighed inside the query rather than by the application after a top k.
```sql
-- what memory says about the task, in at most 4,000 tokens
SELECT id, kind, text FROM memory
WHERE superseded = false
ORDER BY rrf(bm25(text, :task), similarity(emb, :q)) DESC
PACK 4000 TOKENS DEDUPE 0.85 FOLLOW links 1 HOP WITH RECEIPT;
```
Each row, in the query's order, is:
- **taken** whole when its text fits what is left of the budget;
- **excerpted** when it is longer than one row may be (`EXCERPT n`; a quarter of the budget by default) or than what is left: the stretch of its longest text column with the most terms of the query's `bm25` and `MATCH` texts (or its start, when it has none), marked `… ` where it was cut. Terms are found as the column's analyzer makes them (stemmed for `english`, dictionary words for Chinese and Japanese under `standard`), and the text is cut between words, or inside a run without spaces (Chinese, Japanese, Thai, a URL, base64), so an excerpt never spends more than its room;
- **skipped as a near-duplicate** of a row taken before it, with `DEDUPE x`: at least the share x of the shorter one's terms (as its analyzer makes them) are in the other, or, with `DEDUPE x ON emb`, the cosine of their vectors is at least x;
- **skipped as over budget** when not even an excerpt of 32 tokens fits;
- **skipped as no text** when none of its counted columns holds text.
With `FOLLOW edges n HOP` (1 to 3 hops, 1 by default), each row taken brings the rows its [`EDGES`](#graphs) field reaches, up to 16, right after it in the order of its edges, if they pass the query's `WHERE`, decided the same way (`linked from k`). The rows are read by key, a hop at a time, so `FOLLOW` works through a coordinator, in one read per hop: a decision a file note links to is taken with the note, though it shares no word with the task.
The answer is the rows taken, in that order, with two more columns: `pack_tokens`, the tokens the row spends, and `pack_decision` (`take`, `excerpt`, `linked from k`). `WITH RECEIPT` adds the rows skipped (`skip: near-duplicate of k`, `skip: over budget`, `skip: no text`), with their text columns `NULL`, so that the text of the rows answered is still what fits the budget, and the columns `pack_score`, the query's score of the row, and `pack_used`, the tokens spent up to and with it. In Rust, `Db::pack` answers the rows and a receipt with every decision and the snapshot read (`txn` and `seq_no`).
- **The budget** is a whole number from 1 to 10,000,000, or a parameter that holds one: `PACK :budget TOKENS`.
- **The text counted** is every column a row read holds text in, but the key's, or the columns `OF a, b` names. Tokens are an estimate (`chloedb::query::pack::count_tokens`), as the real count depends on the model's tokenizer: a run of Latin letters is a token per six letters, a run of another alphabet's (Cyrillic, Greek, Arabic, Hebrew, the scripts of India) a token per three, a run of digits a token per three, a CJK or Thai character or a punctuation mark one each. Against OpenAI's cl100k_base and o200k_base it counts English and code 13 to 27% high, the safe side; other scripts are counted high against o200k_base but low against cl100k_base, by up to 2.4 times for Hindi ([measured](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/pack/README.md)).
- **Reads.** The rows are read in growing reads, the first 64, then the first 320, 1,344 and so on, each from `OFFSET`, and the rows seen before are passed over by their keys; reading stops once what is left of the budget is too small for any row, or once 16 rows in a row were skipped over budget (what is left is too small for the rows the query finds, such as a title and a description, which need room for both and an excerpt; the rows already read are still decided), so a query whose first rows fill the budget reads once. A deeper read rather than the next page, because a fused ranking (`rrf`, a weighted sum) ranks its candidates to a depth that grows with the `LIMIT`: a deeper read is a better ranking of the same rows, and one that comes back short is the end of the ranking. (In a table without a primary key the reads are pages instead.) `LIMIT` is the most candidates read (1,000 without one), and `OFFSET` where they start. Every read, and every row followed, is a query of its own on the same snapshot: on a server, a lease held for the pack (kept for the client with `hold`, or the client's own `snapshot`), and the statement is admitted once, by its text, and held to one deadline. Through a coordinator each shard reads its latest version at each read.
- **Choosing** is greedy in the query's order. A row that does not fit whole is excerpted rather than skipped, so that one long log cannot spend the budget, and a smaller row after one over the budget is still taken.
- **Where.** On a file, a server and a coordinator alike: a coordinator merges each read from its shards, and packs. A key limited to tables runs it as it runs the query without the clause. `PACK` inside a subquery is not the clause (`pack` stays a name there, and anywhere it is not followed by a number and `TOKENS`).
## Graphs
Rows with an `EDGES` field are nodes of a graph. Graph predicates and scores take **seeds**: a key (`'p1'`), a parameter, a tuple of keys (`('p1', 'p2')`), or a subquery, whose filters, ranking and `LIMIT` are those of any query. A subquery over the same table seeds with its rows; one over another table returns one column, whose values are the keys to start from, such as the items a user's recent events name: `ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 20))`. With `weighted => 1`, a seed's restart weight is its row's score, summed over the rows that name it: `ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY w DESC), weighted => 1)` starts from each item in proportion to the sum of its events' `w`, and ordering the events by `decay(ts, ...)` instead weighs recent ones more.
```sql
-- papers within two citations of p1, either way, nearest first
SELECT id, title, hops() FROM papers
WHERE REACHABLE(cites, 'p1', hops => 2, dir => 'both') ORDER BY hops(), id LIMIT 20;
-- one shortest path, only through surveys
SELECT id, hops() FROM papers
WHERE PATH(cites, 'p1', 'p9', max_hops => 6, through => kind = 'survey') ORDER BY hops();
-- vector search as the way in: what the two nearest papers cite, by similarity
SELECT id FROM papers
WHERE REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2))
AND NOT REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2), hops => 0, min_hops => 0)
ORDER BY similarity(emb, :q) DESC LIMIT 20;
-- personalized PageRank from the same seeds, fused with BM25
SELECT id FROM papers
ORDER BY rrf(bm25(body, :t), ppr(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 5))) DESC LIMIT 20;
```
| function | what it is | options (defaults) |
|---|---|---|
| `REACHABLE(f, seeds, …)` | rows *v* with `min_hops` ≤ *d*(seeds, *v*) ≤ `hops` | `hops 1`, `min_hops 1`, `dir 'out'` (or `'in'`, `'both'`), `label 'a,b'`, `through `, `max_nodes 100000` |
| `PATH(f, from, to, …)` | the rows of one shortest (unweighted) path | `max_hops 6`, `dir`, `label`, `through`, `max_nodes` |
| `hops()` | a row's distance from the seeds, or its position on the path; `ORDER BY hops()` is nearest first | |
| `ppr(f, seeds, …)` | personalized PageRank, usable wherever a score is, including `rrf` and weighted sums | `alpha 0.15`, `eps` (a row is pushed while its residual is at least `eps` times its number of edges, so scaling every weight alike changes nothing; not given, the walk starts at `1e-4` and halves it while its scores hold less than half of the walk, for at most 100,000 pushes, [below](#how-far-ppr-walks)), `dir 'both'`, `label`, `max_pushes 1000000` (a walk cut there says so: `max_pushes_reached` in the stats), `weighted 0` (`1`: the seed subquery's scores are the restart weights) |
| a `VECTOR` field as `f` | `REACHABLE` and `PATH` follow similarity edges: a row's neighbours are its `k` most similar rows | `k 10`, `min_sim` |
Through a [coordinator](server.md#sharding-one-coordinator-many-shards), graph queries over an `EDGES` field or an edge table are walked by the coordinator, a round of reads by key over every shard per hop, and answer as one database does ([graphs on a cluster](graphs.md#on-a-cluster)); a walk over a `VECTOR` field is refused there.
The [query console](server.md#the-query-console)'s Graph tab builds these queries (seeds from keys, a search or a condition; links or similarity; neighbourhood, path or PageRank) and draws the answer.
`through` restricts the rows a traversal may pass through (seeds and end points are exempt); the rest of `WHERE` filters the rows it ends at. **Changed:** a `PATH` with `through` could pass through a row that fails it, where the two halves of its search met, and so answer a path where none keeps to `through`; every middle row of a path now satisfies it. `max_nodes` bounds the rows a traversal meets besides its seeds (and a path's ends): a `REACHABLE` that would meet more, or a `PATH` that meets more before it finds a path, is an error saying so, never a part of the answer. `max_hops => 0` is a path of no hops (a seed that is also a target); `max_nodes` and `k` are 1 or more. `REACHABLE(f, seeds, hops => 0, min_hops => 0)` is the seed set itself, so `NOT` of it removes the seeds from a result. `hops()` refers to the first `REACHABLE` or `PATH` in `WHERE`. The [Graphs](graphs.md) page explains how edges are stored and what these queries cost.
Edges are written as part of their row: a JSON array of target keys, each optionally with a label and a positive weight.
```text
["p2", ["cites", "p7"], ["extends", "p9", 0.5], {"to": "p11", "label": "refutes"}]
```
### How far `ppr` walks
A row's score is the share of the walk that has settled on it, and a row is pushed (its residual spread over its edges) while that residual is at least `eps` times its number of edges. From a seed whose neighbours have thousands of edges, `eps => 1e-4` pushes nothing past the seed: on the tests' user-item graph of 3,000 users with 30 items each, whose 100 items have 900 edges on average and at least 300, a user's items get 0.028 each, below 10⁻⁴ times their edges, so the walk ranks the user and no item. Without `eps`, the walk then halves it and pushes on from where it stopped, until its scores hold half of the walk (there, `eps` 3.1e-6, after 9,078 pushes), for at most 100,000 pushes; its plan line says where it went (`eps lowered to 3.1e-6, 72% settled`). With `eps`, it walks exactly as far as asked. A walk whose scores hold less than half of the walk, by its `eps` or its pushes, says so: `ppr_unsettled` in the stats, and in its plan line how much it settled and what to change. **Changed:** `eps` was 10⁻⁴ when not given, and such a walk returned only its seeds with no warning.
### Edge tables
An `EDGES` field belongs to its source row, so adding one edge rewrites the row, its text and its vectors. A graph kept up as events arrive, such as items seen together, goes in an **edge table** instead: a table whose rows are edges, declared with `OPTIONS(edges = 'src, dst, w')`. A walk over the table whose keys it holds names the edge table where it would name a field:
```sql
CREATE TABLE cooc (
id KEYWORD PRIMARY KEY, -- 'src>dst'
src KEYWORD NOT NULL REFERENCES items,
dst KEYWORD NOT NULL REFERENCES items,
w FLOAT DEFAULT 0
) OPTIONS(edges = 'src, dst, w');
SELECT id FROM items
ORDER BY ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 20)) DESC LIMIT 200;
```
- Each row is an edge from the row whose key is in `src` to the row whose key is in `dst`, weighted by `w`, or by 1 without a weight column (`edges = 'src, dst'`). `src` and `dst` are stored, single-valued `KEYWORD` or `INT` columns of the type of the other table's key, and the weight is a stored `FLOAT` or `INT`. If `src` references a table, walks are over that table.
- Writing an edge writes its row and nothing else: insert it, delete it, or add to its weight with an `add` operation, whose `doc` creates the row on the edge's first event ([writes](server.md#writes)).
- Edges are directed, from `src` to `dst`. For a click on item *i* after the user's last items *h*₁ … *h*₅ (*h*₁ the most recent), adding 1/*g* to the edge *h*_g → *i* records what comes after what: `ppr(cooc, :x, dir => 'out')` and `REACHABLE(cooc, :x, dir => 'out')` follow the items that came after *x*, and `dir => 'both'`, `ppr`'s default, reads them as seen together. That is five `add` operations per event. For the next item alone, counts of what came after the last one or two items are cheaper and exact ([Next items](next-items.md)).
- An edge is followed while its weight, as it is now, is above 0. `UPDATE cooc SET w = w * 0.9` decays every weight in place, and an edge whose weight is 0 or `NULL` stays in the table without being followed. `src` and `dst` are never changed in place: an `UPDATE` of a `KEYWORD` one rewrites the row, and `set`, `add` or an `UPDATE` of an `INT` one is refused, as for `shard_by` (delete the row and insert it again).
- `REACHABLE`, `PATH`, `hops()` and `ppr` take an edge table with every option but `label`, since its edges have none. A walk over `cooc` and a walk over an `EDGES` field holding the same edges and weights find the same rows at the same hops and the same PageRank, up to rounding.
- Each segment of the edge table indexes its rows by the keys they link, which flushes and merges build, so a walk finds a row's edges with one lookup of its key in each of the edge table's segments ([how, and what it costs](graphs.md#edge-tables)).
## Stored functions
A function is kept in the database under a name, and any query calls it as it calls a built-in one. Its body is SQL: an expression of its parameters for a function that returns a value, a `SELECT` for one that returns rows (`RETURNS TABLE`).
A function that returns rows stands where another database has a view (`CREATE VIEW` is refused here): `CREATE FUNCTION spend_by_country() RETURNS TABLE AS SELECT country, SUM(total) AS spend FROM invoices GROUP BY country`, read with `SELECT * FROM spend_by_country()`, joined or filtered like a table, and it may take parameters and keeps its versions.
```sql
CREATE FUNCTION boosted(s FLOAT, importance FLOAT, w FLOAT DEFAULT 0.2)
RETURNS FLOAT AS :s * (1 + :w * :importance);
SELECT id FROM memories WHERE MATCH(body, :q)
ORDER BY boosted(bm25(body, :q), importance) DESC LIMIT 10;
CREATE FUNCTION recall(q TEXT, k INT DEFAULT 10) RETURNS TABLE AS
SELECT id, body FROM memories WHERE MATCH(body, :q)
ORDER BY bm25(body, :q) DESC LIMIT :k;
SELECT * FROM recall('tokio runtime', k => 5);
SELECT r.id, m.created FROM recall(:q) AS r JOIN memories m ON m.id = r.id;
CREATE OR REPLACE FUNCTION boosted(...) RETURNS FLOAT AS ...; -- version 2
SELECT "boosted@1"(bm25(body, :q), importance) FROM memories ...; -- pins version 1
CREATE OR REPLACE FUNCTION boosted FROM VERSION 1; -- a rollback: version 3, as 1
DROP FUNCTION IF EXISTS boosted; -- a tombstone: version 4
DROP FUNCTION boosted VERSION 2; -- deletes an old version
```
- **The definition**: `CREATE [OR REPLACE] FUNCTION name(parameter TYPE [DEFAULT value], ...) RETURNS TYPE | RETURNS TABLE [LANGUAGE sql] [OPTIONS (description = '...')] AS body`, the body also between `$$` and `$$`. Types are `INT`, `FLOAT`, `TEXT`, `KEYWORD`, `BOOL`, `TIMESTAMP`, `JSON`, `VECTOR` or `VECTOR(n)`, and `KEYWORD[]` and `INT[]`; a default is a number, a quoted string, `TRUE`, `FALSE` or `NULL`, and the parameters after one with a default have one too. In the body a parameter is `:name`, as in a [rank profile](#rank-profiles-a-ranking-kept-with-its-table), so the body runs as written as a query with the same parameters. A body that returns a value reads only its parameters: a column is passed in as an argument. Names are letters, digits and `_`, in any case; the name of a built-in function (`lower`, `bm25`, `coalesce`, ...) is refused, and there is one function of a name, whatever its parameters. `CREATE` checks that a `RETURNS TABLE` body plans against the tables, its parameters given their defaults or a value of their type. A text parameter where a field's vectors go (`similarity(emb, :q)`, in the body or in the rank profile it ranks by) is checked as a vector of the field's size, since a call embeds it; a body that reads a blend (`SELECT * FROM blend('serp', q => :q) LIMIT :k`) is checked when it runs. A call whose body (or its rank profile) [understands](#understanding-a-querys-words-understand) or [expands](#query-expansion-expand) its words, reads a blend or gives text where vectors go runs as its body written out, so the server takes those steps as it does for a query's own.
- **A call is written out**: binding replaces each call with its body, the arguments in place of the parameters, so the query plans and ranks as if it were written out (indexes, `score()` and a shard's pushdown included), and `EXPLAIN` begins with `calls stored function boosted@2`. Arguments are by position, then by name (`w => 0.5`); a missing one takes its default. A literal argument of another type than its parameter's is refused; any other expression is computed as the body would with it, and the value is the body's (`RETURNS FLOAT` of `:a + :b` with two `INT`s is an `INT`). A function that returns rows is called in `FROM`, alone, joined, or in `WITH`, and its arguments are values or parameters of the query, not columns. A function may call others, up to 16 deep.
- **Versions never change**: `CREATE` writes version 1; `CREATE OR REPLACE` the next version, or nothing when the definition is the current one's; a new version returns what the old one did (a value, or rows). `DROP FUNCTION` writes a tombstone version, so version numbers keep rising and `"f@2"` always means one body. A query calls the current version, the highest that is not a tombstone, or pins one with its name and version in double quotes, which still runs after a drop. `CREATE OR REPLACE FUNCTION f FROM VERSION n` makes a new version with version *n*'s definition; `DROP FUNCTION f VERSION n` deletes an old version (not the current one).
- **Kept as rows**: each version is a row of the system table `_functions` (`id` `name@version`, `name`, `version`, `language`, `kind`, `signature`, `body`, `hash`, `description`, `created`, `created_by`, `dropped`), written by its own transaction, so it is logged, numbered and shipped to replicas as writes are, and checkpoints and copies carry it. `SELECT * FROM _functions` reads it; it is not one of the database's tables, and only `CREATE` and `DROP FUNCTION` write it. The first function adds it, and the database then needs the format 3 feature `functions`, which a version of ChloeDB from before stored functions refuses by name. A database from before field ids keeps none (upgrade it first).
- **From Rust**, `Db::sql` runs both statements, `Db::define_function` runs a parsed one and records who wrote it, and `Db::functions` lists every version.
- **On chloedb-server**, `CREATE` and `DROP FUNCTION` need an admin key, whose name is the version's `created_by`; any key that may read calls them. `GET /v1/functions` lists each function with its current version and every version's definition.
- **Through a coordinator**, a version has one number and one body on every shard: `CREATE` and `DROP FUNCTION` ask every replica which versions it holds, number the new one past all of them, and write it on each shard, so they wait for every replica to answer. A coordinator calls the versions every replica holds alike (a new version once every shard has it) and stops calling a dropped function as soon as any replica holds the drop. A shard added to the cluster gets every version under its number. Each shard records the coordinator's credential as `created_by`.
## Language models: `llm()`
`llm(model, instructions, input, ...)` is a language model's answer to the instructions about the inputs, for each row a query returns. A stored function keeps the prompt and the model under a name, versioned as any function is: a new prompt or model is a new version, `"summarize@1"(body)` still asks the old one, and `FROM VERSION n` rolls back.
```sql
CREATE FUNCTION summarize(t TEXT) RETURNS TEXT
AS llm('anthropic/claude-haiku-5-5', 'Summarize this review in one sentence.', :t);
CREATE FUNCTION mood(t TEXT) RETURNS KEYWORD
AS llm('anthropic/claude-haiku-5-5', 'How does this review feel?', :t, choices => 'positive,negative,mixed');
SELECT id, title, summarize(body), mood(body) AS mood
FROM reviews WHERE MATCH(body, :q) ORDER BY bm25(body, :q) DESC LIMIT 10;
-- the stored summary where there is one, else the model's
SELECT id, coalesce(summary, summarize(body)) FROM reviews ORDER BY rating DESC LIMIT 20;
-- BM25's top 50, ranked by a grade the model gives each
WITH top AS (SELECT * FROM reviews WHERE MATCH(body, :q) ORDER BY bm25(body, :q) DESC LIMIT 50)
SELECT id, title, score() FROM top
ORDER BY llm('anthropic/claude-haiku-5-5', 'Grade from 0 to 10 how well the review answers the question.',
'Question: ' || :q, body, returns => 'number') DESC LIMIT 10;
```
- **Where it runs.** A query that calls `llm()` runs in two steps: the query without the calls finds its rows (its `WHERE`, `ORDER BY` and `LIMIT` as written), computing what the calls read of each row, and then the model is asked about those rows, eight at once, and the columns are computed of the answers. A call may be part of a column, in arithmetic, `||`, comparisons, `CASE` and functions of values; a `CASE` asks only for the branch it takes, and `coalesce` only where the values before the call are `NULL`. `llm()` is a column of `SELECT` or part of `ORDER BY`; anywhere else (`WHERE`, `GROUP BY`, `HAVING`, a join, a `WITH`, a subquery, `UNION`) it is refused, as it would run for rows the query reads rather than returns.
- **In `ORDER BY`** the calls rank the rows the query finds without that `ORDER BY` and its `LIMIT`: the top rows of a first ranking, as a [rerank phase](#rerank-phases) ranks them. Rows that tie keep the first ranking's order, a `NULL` ranks last, `LIMIT` and `OFFSET` cut the ranked rows, and `score()` is the first key's value.
- **Arguments.** `model` is a string: `anthropic/` (a Claude model, its key in `ANTHROPIC_API_KEY`), `openai/`, or the name of a model directory whose `endpoint.json` names a chat server (`"api": "chat"` for OpenAI's `/chat/completions`, as vLLM, Ollama and LiteLLM serve it, or `"api": "anthropic"`), as for [text made of text](server.md#text-from-text). A directory's name is letters, digits, `_`, `-` and `.` (two such names joined by `/` at most): an absolute path, `..` or a backslash is refused, so a query reads no `endpoint.json` outside the models directory, and an `endpoint.json`'s `key_env` names a provider's key variable or a `CHLOEDB_MODEL_KEY_*` one. A query or a row cannot choose the model. The instructions are the system prompt, a string or a parameter; each input is a part of the user's message, apart by a blank line, and a `NULL` input is left out. A call with no input is `NULL`, and asks nothing.
- **Answers** are text, trimmed. `choices => 'a,b,c'` asks for one of them and gives it as written there (the answer in any case, or the one choice an answer that says more names), else `NULL`. `returns => 'number'` gives the first number of the answer as a `FLOAT`, and `returns => 'bool'` its yes or no as a `BOOL`, else `NULL`. `max_tokens => n` bounds the answer (1024 for text, 64 otherwise). The model answers with its own sampling defaults: no temperature is sent (current Claude models refuse one).
- **Cost.** Each distinct question (model, prompt and input) is asked once, and its answer kept in memory (10,000 of them), so the same query again asks nothing. A query asks about 100 rows at most, and a process makes 600 requests a minute at most for `llm()`: past either, the query fails before asking (chloedb-server's `--llm-rows` and `--llm-per-minute`, `chloedb::query::llm::set_limits` from Rust). A failed request fails the query (503), after the endpoint's retries. The answer's plan lines end with one that says how many rows were asked about, how many requests were made, and how many answers came from memory; `EXPLAIN` shows the plan of the rows.
- **Inputs are data.** A row's text is the user's message and the instructions the system prompt, and the model has no tools, so a row's text can change that row's answer and nothing else.
- **A coordinator** asks the model about the merged rows, on the coordinator, so no shard asks about a row the merge cuts, and its shards need no key. A body that calls `llm()` is a function that returns a value: `CREATE` refuses one in a `RETURNS TABLE` body, and checks each call's model and options. chloedb-server counts the requests in `chloedb_llm_requests_total`, `chloedb_llm_cached_total` and `chloedb_llm_failures_total`.
## Classifiers: `CREATE CLASSIFIER` and `classify()`
> **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release.
A classifier learns a table's labels from its rows' embeddings, and is kept as a [stored function](#stored-functions) of a vector: versioned, rolled back and dropped as any function is, and held by every shard of a cluster. It classifies rows by their stored vectors, and a query's text by the same model's vector of it.
```sql
-- trains on the rows with a label; answers what it measured
CREATE CLASSIFIER topic ON products(emb) LABELS category
OPTIONS (method = 'logistic', holdout = 0.2) WHERE in_stock;
-- each row's class, a column of the rows a query returns
SELECT id, title, topic(emb) AS topic FROM products WHERE MATCH(title, :q) LIMIT 20;
-- a query's class: :v is the query's vector ({"embed": "red leather sofa", "field": "emb", "table": "products"})
SELECT topic(:v), topic(:v, 'score'), topic(:v, 'labels');
SELECT id FROM products WHERE MATCH(body, :q)
ORDER BY bm25(body, :q) * (1 + 0.25 * CASE WHEN category = topic(:v) THEN 1 ELSE 0 END) DESC LIMIT 10;
CREATE OR REPLACE CLASSIFIER topic ON products(emb) LABELS category; -- version 2
CREATE OR REPLACE FUNCTION topic FROM VERSION 1; -- back to the first
DROP CLASSIFIER topic;
```
- **Training.** `CREATE CLASSIFIER name ON table(vector_field) LABELS column [OPTIONS (...)] [WHERE condition]` reads `SELECT vector_field, column FROM table WHERE column IS NOT NULL [AND condition]`, at most `max_rows` rows (200,000), keeps the labels with at least `min_rows` rows (2), and holds out a share of them (`holdout`, 0.2, chosen by a hash of each vector, so the same rows every time) to measure the model it keeps. `method = 'logistic'` (the default) fits softmax regression (Adam, `epochs` 30, `learning_rate` 0.01, `l2` 0.0001); `method = 'centroid'` takes each label's mean vector, in one pass. The labels are the values of a `KEYWORD`, `TEXT`, `INT` or `BOOL` column, and the field a `VECTOR` field of one vector a row; a classifier has 10,000 labels at most. The statement answers one row: `labels`, `rows`, `train_accuracy`, `holdout_rows`, `holdout_accuracy`, `took_ms`. A coordinator reads the rows from its shards, trains, and writes the function on every shard.
- **The function** is `name(v VECTOR, returns TEXT DEFAULT 'label') RETURNS KEYWORD`, its body a call of `classify(:v, model, returns => :returns)`, `model` the classifier as text: its labels, a row of weights a label quantized to 8 bits with a scale of its own, and a bias (about a kilobyte a label for a 512-number vector), and the table, field and embedding model it was trained on. `name(v)` is the label with the highest probability (the softmax of the scores), `NULL` for a `NULL` vector or one below the classifier's `min_score` option (0); `name(v, 'score')` that probability; `name(v, 'labels')` the best label and those whose probability is at least `min_score` and a tenth, best first.
- **Where it runs.** A call of a value of no row, a parameter's vector, is computed before the query is planned, so it stands anywhere: `WHERE`, `ORDER BY`, a join (its `'labels'`, a list, is a column of the rows only). A call of a row's vector is a column of the rows a query returns, or ranks them in `ORDER BY`, as `llm()` is: computed after the query finds them, for 100,000 rows at most. To filter or group rows by their class, keep it in a column: a `KEYWORD` field `OPTIONS (derive = 'title', model = 'classifier:topic')` holds the label of each row written ([keywords made of text](server.md#keywords-made-of-text-languages-keyphrases-near-duplicates-entities)).
- **Text.** `Db::classify(name, text, k)` (Rust) and `POST /v1/classify {"name", "text", "k"}` embed a text with the model of the field the classifier was trained on and give its `k` best labels with their probabilities.
- **Measured** on Wayfair's WANDS (`chloedb-classify-eval`, `chloedb/results/text/classify_wands.json`, an Intel Xeon at 2.10 GHz, 4 cores): 42,994 products, `emb` potion-retrieval-32M's vector of a product's name, 501 product classes. The logistic classifier names the class of 81.9% of held-out products (centroid 81.3%) and the class of 62.9% of the 480 queries (centroid 51.0%; among its best three, 80.4%), at 0.07 ms a query's text, embedding included; it trains in 31 s (centroid 2 s), and a row's class costs 40 µs. As a boost, `bm25(body, :q) * (1 + 0.1 * CASE WHEN class = topic(:v) THEN 1 ELSE 0 END)` raised nDCG@10 from 0.433 to 0.439 (p = 0.002, the same on the odd-numbered queries not used to choose the weight), and a weight of 0.5 lowered it: a wrong class costs the rows that are right.
## Recommenders: `CREATE RECOMMENDER` and `recommend()`
A recommender keeps counts of a table of events (what came right after what, what was seen together, how often each item was seen, each user's last items) as the events are written, and `recommend(name, user)` ranks items for a user by them, fused with the similarity of the user's recent items and with popularity, leaving out the user's recent items (the last `history`; an item the user had before those can come back: filter with `id NOT IN (SELECT item FROM events WHERE usr = :u)` to leave out every one).
```sql
CREATE TABLE events (id KEYWORD PRIMARY KEY, usr KEYWORD, item KEYWORD, ts TIMESTAMP);
CREATE RECOMMENDER shop ON events(usr, item, ts) ITEMS items(emb) OPTIONS (window = 3, history = 20);
-- items for a user, as a score: filter, join and fuse it as any other
SELECT id, title FROM items WHERE in_stock ORDER BY recommend('shop', :u) DESC LIMIT 10;
SELECT id FROM items WHERE MATCH(title, :q) ORDER BY rrf(bm25(title, :q), recommend('shop', :u)) DESC LIMIT 10;
-- the items themselves, and which list each came from (its rank there)
SELECT * FROM recommend('shop', 'u42', k => 5);
-- item | score | next | co | similar | popular
-- 'p9' | 0.0485 | 1 | 2 | 7 | NULL
DROP RECOMMENDER shop;
```
- **The definition.** `CREATE [OR REPLACE] RECOMMENDER name ON events(user, item, time) [ITEMS items[(vector_field)]] [OPTIONS (window = 3, history = 20)]`. The user and the item are stored, single-valued `KEYWORD` or `INT` columns of the events table, and the time a `TIMESTAMP`, `INT` or `FLOAT` column (a `NULL` time places the event last). `ITEMS` names the table whose keys the items are (of the item column's type), and its `VECTOR` field, if any, for the similar items. `window` (1 to 50) is how many events apart two items still count as seen together, and `history` (1 to 1,000) how many of a user's last events are kept, recommended from and left out of the answer. `OR REPLACE` counts the events again.
- **What it keeps.** The statement counts the events already in the table, in one transaction, and answers one row: `recommender`, `counts`, `events`, `users`, `pairs`, `took_ms`. The counts are rows of an ordinary table, `_counts` (`id`, `kind`, `src`, `dst`, `next`, `co`, `n`, `recent`), which any query reads: a `pair` row's `next` is how often `dst` came right after `src` in one user's events, and its `co` how often the two came within `window` events of each other (both ways); an `item` row's `n` its events; a `user` row's `recent` the user's last `history` events as JSON. The definition is a [stored function](#stored-functions) `name()`, whose value is the definition (a function of that name that is not a recommender is refused), so it is versioned, kept by checkpoints and copies, and shipped to replicas as functions are.
- **Fed from writes.** Every transaction that inserts rows into the events table, by SQL, `/v1/write`, an import or the Rust API, also adds to the counts at its commit, in the same transaction, so an event and its counts are written, logged and shipped together, and the next `recommend` sees them. An event placed between two older ones by its time takes back the pair they were and counts the two it makes. A row that replaces a row of its key (an upsert) is not a new event; deleting or updating events changes no count (`CREATE OR REPLACE RECOMMENDER` counts again). An event costs about `2 × window + 3` writes to the counts, each a read and a write by key, so writes of events take tens of times longer than without a recommender, and `CREATE` holds the writer while it counts the table (seconds per hundred thousand events). It also holds every pair it counts in memory until it commits: over MovieLens-1M (994,169 events, window 3, 1.78 million pairs) the process grew by about 2.6 GB while `CREATE` ran (25 s) and kept most of it once it had committed, against 130 MB for the counts on disk (measured on a shared 4-core, 15 GB Linux container, chloedb 0.3.8; since 0.3.10 `CREATE` names each item once while it counts and gives back what it held once it has committed). Give a `CREATE` over millions of events that much room, or create the recommender on an empty events table and load the events after it in batches, so that each batch's transaction counts only its own. Counting at write rather than when asked keeps a call to a few reads by key whatever the size of the events table: counting a million events at each call would read them all. A count an event changes is written in place in its row's segment, and a call reads each count it ranks by as last written, so calls take no longer as events arrive; `optimize()` on an embedded database, or `POST /v1/admin/optimize` on chloedb-server ([admin routes](server.md#http-api)), merges the counts' segments, which takes a call back to its time after `CREATE`.
- **`recommend(name, user [, k => 100, next => 1, co => 1, similar => 1, popular => 0.2])`** reads the user's row and builds four lists of up to 200 items: what came next after the user's last item (and, at 0.4, after the one before), the items seen together with each of the user's recent items (the more recent weighing more, each item's counts as shares of its own), the items nearest the user's last eight by `maxsim` over the items' vectors, and the most popular items. An item scores the sum over the lists of the list's weight over 60 plus its rank there (reciprocal rank fusion); a weight of 0 leaves its list out. The user's recent items are left out, and the best `k` (at most 10,000) are the ranking: the call is then [`ranked(...)`](#rankedkeys-a-ranking-from-elsewhere) of their keys, so a row it does not list scores `NULL`, and `ORDER BY recommend(...)` on its own answers only the rows it lists (in a sum or `rrf` with other scores, the others rank by those). A user with no events gets the popular items. A call reads about two rows by key and one ranked page per recent item, some milliseconds. The answer's plan lines begin with one for each call: `recommend shop for 'u42': 100 items, from 12 next, 85 seen together, 200 similar, 120 popular; 9 of the user's items left out`.
- **`FROM recommend(...)`** is a table of the items, best first, with `item`, `score`, and each list's rank of the item (`next`, `co`, `similar`, `popular`, `NULL` where it is not in a list); a `LIMIT` lowers `k`. It takes no join, `WHERE`, `ORDER BY` or `GROUP BY`: rank a table by `ORDER BY recommend(...)` for those.
- **Where it runs.** On one database, on chloedb-server over its own tables (`CREATE` and `DROP RECOMMENDER` need an admin key), and through a coordinator when the events table is placed by its user column (`CREATE TABLE events (...) OPTIONS(shard_by = 'usr')`; over several shards, `CREATE RECOMMENDER` is refused otherwise). There each shard counts the events it holds in its own rows of the counts table, and `recommend(...)` reads them summed over the shards and ranks as one database does ([graphs and recommenders on a cluster](cluster-limits.md#graphs-and-recommenders)). A version of ChloeDB from before recommenders opens the database, but does not feed the counts.
## Blends: `CREATE BLEND` and `blend()`
A blend makes one list from the rows of several queries, after each has ranked its own: stories and comments on one results page, sponsored rows among organic ones, fresh items beside popular ones. Each row is worth a utility, a weighted sum of values the sources name alike (its heads), each calibrated within its source, and the slots are filled best utility first under the slate's rules: a slot kept for a kind of row, a kind's share of the top rows, its spacing, a cap per value, diversity and near copies.
```sql
CREATE BLEND serp AS
SOURCES (
stories AS (SELECT id, title, author, emb, score() AS relevance, ln(1 + points) AS quality
FROM items WHERE kind = 'story' ORDER BY bm25(title, :q) DESC LIMIT 100),
comments AS (SELECT id, text AS title, author, emb, score() AS relevance, ln(1 + replies) AS quality
FROM comments ORDER BY bm25(text, :q) DESC LIMIT 60)
)
HEADS (relevance CALIBRATE tmm, quality CALIBRATE minmax MISSING zero)
UTILITY 1 * relevance + 0.2 * quality
SLOT 1 => source = 'stories'
QUOTA (source = 'comments' BETWEEN 20% AND 40% IN TOP 10)
DIVERSIFY 0.3 ON emb
MAX 2 PER author
DEDUPE 0.95 ON emb
WITH (k => 10, note => 'stories first, a few comments');
SELECT slot, source, id, title, utility, blend_decision FROM blend('serp', q => :q);
-- slot | source | id | title | utility | blend_decision
-- 1 | 'stories' | 's9' | 'Async Rust...' | 1.18 | 'slot 1 is kept for source = ''stories'''
-- 2 | 'comments' | 'c4' | 'I moved our...'| 0.97 | 'the best utility left'
SELECT * FROM blend('serp@3', q => 'rust async') LIMIT 20; -- version 3
DROP BLEND serp;
```
- **The definition**: `CREATE [OR REPLACE] BLEND name AS SOURCES (name AS (SELECT ...), ...)` (a source may be a blend of its own, `name AS BLEND (...)`: [stacking blends](#stacking-blends-a-blend-as-anothers-source)) and then, each optional and in this order:
- `HEADS (head [CALIBRATE tmm|minmax|rank|raw] [LO n] [MISSING neutral|zero], ...)`: the columns a row is worth by. A head is a column the sources name alike (`... AS relevance`), or `score`, each source's own ranking score, which needs no column. `tmm` (the default) divides by the source's best value, from `LO` (0 by default); `minmax` spans the source's lowest to its best; `rank` keeps only the order, as `rrf` does (61 / (60 + rank)); `raw` keeps the value. A source without the head gives its rows the mean of the others' (`MISSING neutral`, the default) or 0 (`MISSING zero`). Without `HEADS`, the one head is `score CALIBRATE tmm`.
- `UTILITY 1 * relevance + 0.2 * quality - 0.1 * age`: the heads' weights (a head not named weighs 0; a name not among the heads adds one, `tmm`). `BOOST (source w, ...)` adds `w` to every row of a source.
- `SLOT n => column = 'value'`, more than one: slot *n* is kept for rows of that value.
- `QUOTA (column = 'value' BETWEEN a% AND b% IN TOP n, ...)`, or `AT LEAST a%` or `AT MOST b%`, `IN TOP n` the blend's `k` by default; `IF ANY` holds the least only when the sources answered a row of the kind. A kind that could only reach its least by being placed now is placed now; one at its most is passed over.
- `SPACING (column = 'value' AT MOST n PER m ROWS, ...)`: at most *n* rows of the kind in any *m* in a row.
- `DIVERSIFY λ ON column`: each candidate loses λ (0 to 1) of the utilities' range for its likeness to the rows placed, the cosine of a vector column's values or 1 for an equal value of another column (maximal marginal relevance).
- `MAX n PER column`, more than one: at most *n* rows of one value, as [`MAX k PER`](#at-most-k-rows-of-a-value-max-k-per) does for one query.
- `DEDUPE t ON vector_column`: a row whose cosine to a row placed is *t* or more is left out.
- `WITH (k => 10, note => '...')`: the slots filled (1 to 1,000), and a note kept with the version.
At most 16 sources, each a `SELECT` (any ranking: a rank profile, `rrf`, `recommend(...)`, a stored function), named once. The rules' numbers are checked (a quota's least at most its most, spacing's *n* under its *m*, λ from 0 to 1), and so is that the quotas' least shares and the slots kept fit in their top rows. `CREATE` answers one row: `blend`, `version`, `sources`, `k`.
- **A row's key** is its table's key, or the first column where it reads none: rows of one key from two sources are one row, kept where its utility is higher (`also` in the receipts names the others). Its `source` is the source's name, and a rule's column may be `source` or any column the sources answer.
- **The fill** places the rows slot by slot. A slot kept by `SLOT` takes the best row of its kind; otherwise a quota that would fall short if not met now takes its kind's best row; otherwise the best utility left (less its diversity cost) of the rows no rule bars. When no row fits every rule, the fill sets rules aside for that slot, in this order, until one does: spacing, the caps, a quota's least, the slots kept, a quota's most; the row says so (`no row fit every rule: MAX 2 PER author set aside`), so a blend fills its slots while rows are left (`DEDUPE` is never set aside).
- **`FROM blend('name[@version]' [, parameter => value, ...]) [LIMIT k]`** runs each source with the call's arguments and the query's parameters as its parameters (`:q`), and answers a row per slot, best first: `slot`, `source`, the sources' columns (all of them for `*`, each source's `NULL` where it has none), `utility` and `blend_decision`, the reason the row is in its slot. A `LIMIT` fills that many slots instead of `k` (a quota's least may then not fit). A call takes no join, `WHERE`, `ORDER BY` or `GROUP BY`; select the columns, and alias them, as `SELECT id, title AS name FROM blend('serp', q => :q)`. The answer's plan lines say what it did: `blend serp@2: 2 sources, 160 rows (stories 100 rows in 3.1 ms, comments 60 rows in 1.4 ms)`, then `blend placed 10 of 10 slots in 0.04 ms: stories 7, comments 3` and a line for each quota's count.
- **Versions.** A blend is a [stored function](#stored-functions) `name()` whose body is the definition, so `CREATE OR REPLACE BLEND` writes the next version, `blend('serp@1')` reads an old one, `DROP BLEND [IF EXISTS] name` writes a tombstone (its versions stay readable by number), and versions are kept by checkpoints and copies and shipped to replicas as functions are. A function of the name that is not a blend is not replaced by one.
- **From Rust**, `Db::sql` runs the statements and the calls, `Db::blends` lists each blend's current definition, and `Db::blend_run(&def, version, ¶ms, k, Want { costs: true })` runs a definition, stored or not, into a `Blended` whose `receipts()` is the JSON of every row's heads, raw and as weighted parts of its utility, its slot and why, the rows passed over and what barred them, each quota's count and each rule's cost: the share of the slate's discounted utility (each slot's over log2(slot + 1), as DCG discounts) that it gives up, from filling the slate again without it.
- **On chloedb-server**, `CREATE` and `DROP BLEND` need an admin key, and a key limited to tables reads a blend only when it may read every source's tables, of every version the call could read. `GET /v1/blends` lists the blends (each current version's definition, its SQL and how many versions), `GET /v1/blends/:name` every version, `PUT /v1/blends/:name {"def": {...}, "note": "..."}` writes the next version from a definition as JSON, and `DELETE /v1/blends/:name` drops it. `POST /v1/blends/preview {"name": "serp"}` (or `"version"`, or a definition not stored, `"def"`) with `"params"` and `"k"` runs it and answers the receipts, rule costs included unless `"costs": false`. The command center's **Labs → Blending** page edits a blend on these routes, previewing the draft as it changes.
- **Through a coordinator** a blend's versions are written on every shard, as functions are, and each source runs as a query of the cluster, merged from the shards, before the fill: the slate is the one database's.
### Stacking blends: a blend as another's source
A source may be a blend of its own, a node stacked under the one above it: `name AS BLEND ( SOURCES (...) HEADS ... WITH (k => n) )`, the same clauses as a blend's. The node runs first, into its own *k* slots under its own rules, and the rows it places are that source's rows above, so the blend above weighs, places and rules them as one source among its others.
```sql
CREATE BLEND page AS
SOURCES (
organic AS BLEND (
SOURCES (
stories AS (SELECT id, title, author, score() AS relevance, pop AS engagement FROM stories ORDER BY bm25(title, :q) DESC LIMIT 50),
videos AS (SELECT id, title, author, score() AS relevance, pop AS engagement FROM videos ORDER BY bm25(title, :q) DESC LIMIT 30)
)
HEADS (relevance CALIBRATE tmm, engagement CALIBRATE minmax)
UTILITY 1 * relevance + 0.4 * engagement
MAX 2 PER author
WITH (k => 20)
),
sponsored AS BLEND (SOURCES (ads AS (SELECT id, title, author, bid AS score FROM ads ORDER BY bid DESC LIMIT 6)) WITH (k => 3)),
news AS (SELECT id, title, author, 1.0 / age AS freshness FROM news ORDER BY age LIMIT 10)
)
SLOT 2 => source = 'sponsored'
QUOTA (source = 'news' AT LEAST 20% IN TOP 5, via = 'organic/videos' AT MOST 30%)
WITH (k => 10);
SELECT slot, source, via, id, title FROM blend('page', q => :q);
-- slot | source | via | id | title
-- 1 | 'organic' | 'organic/stories' | 's12' | 'Async Rust...'
-- 2 | 'sponsored' | 'sponsored/ads' | 'a3' | '...'
-- 3 | 'news' | 'news' | 'n1' | '...'
```
- **A node's rows**, as the blend above reads them: its sources' columns, `slot` (its own), `via` and `utility`, which is also their score, so the head `score` above is the node's utility; their keys stay theirs, so a row a node and another source both give is one row above. `via` names the source a row came from, through each node on the way (`organic/stories`): every blend answers it, and a rule above may read it (`QUOTA (via = 'organic/videos' AT MOST 30%)`).
- **Its rules hold among its own rows**: a node's quotas, caps and diversity shape the rows it gives, and the blend above may pass over some of them. A node is named as its source; its own `name` may be left out in JSON.
- **Limits**: blends stack at most 4 deep, the top one counted, and a blend runs at most 32 queries under every node. A source that reads `blend('...')` is refused: stack the blend as a node instead.
- **Logged and valued**, a stacked blend explores at the top only (each node takes its best rows), and the log keeps the rows each node gave as that source's rows, so [Value on the log](#valuing-a-blend-on-its-log-exploring-fills-cascade-doubly-robust-and-snips) and tuning work on the top blend's heads, quotas and diversity as they do for any blend.
- **The receipts** of a stacked blend carry each node's own under `nodes` (`"nodes": {"organic": {...}}`, nodes of nodes within them), each row's `via`, and the SQL writes nodes back as `name AS BLEND (...)`. On chloedb-server a key limited to tables reads a stacked blend only when it may read the tables of every query under every node.
### Valuing a blend on its log: exploring fills, cascade doubly robust and SNIPS
A blend served with a [log](#the-rank-log-what-each-query-served) can explore, and a log of exploring pages values any other blend of the same sources (its weights, shares and rules changed) without serving it: what people clicked is reweighted by how likely each page was.
```sql
-- POST /v1/query, or Db::query_logged with a Log
{"sql": "SELECT slot, source, id, title FROM blend('serp', q => :q)",
"params": {"q": "rust async"},
"log": {"context": "u42", "explore": {"policy": "softmax", "tau": 0.3, "top": 5}}}
```
- **The exploring fill.** At each slot the rows that fit the rules there (the same rows the best-taken fill would weigh) are ordered by their utility, less diversity's cost, and the slot draws among the best `top` of them with chances `exp(u / (tau × range))` (the range of those utilities, so `tau` is a share of it, not a number of the heads' units). `top` 1, or no `explore`, takes the best. The draws come from the request's id (`log.request`, or a random one), so a request served again draws the same page. Only `softmax` explores a blend (`by` the score, the utility); `candidates` and `interleave` are refused.
- **What is logged**: every row of every source, not only those placed, with its cells (a vector column the rules read as its numbers; text up to 256 characters), its source and rank in it and its utility as the row's `score`; the rows placed come first, in slot order, each `shown` with its slot's chance (`propensity`) and the page's chance down to it (`prefix_propensity`); the first row's `policy` names the blend, its version, `k`, `tau`, `top` and sources. The answer has the chances as `propensities`, one a slot.
- **Replay.** From the logged rows, a blend's fill runs again over each logged page, the logged rows above each slot taken as placed: it gives that blend's chance of the logged row at every slot, and the rows it would have weighed. Replayed through the logging blend's own version, it gives back the chances logged (a difference is reported as drift, and the verdict is not proven: the rows or the definition changed).
- **Cascade doubly robust** (Kiyohara et al., 2022) values a blend over the logged pages as `Σ_l γ_l (w_l (r_l − q̂_l) + w_{l−1} Σ_a π(a | slot l) q̂(a))`, plus the model's value of the rest of the page where the weight is cut: `w_l` is the product, down to slot `l`, of the blend's chance of each logged row over the logging blend's, `r_l` the click at slot `l`, and `q̂` a click model (ridge regression over the slot, the rows' numbers and their numbers over log2(slot + 1)) fitted on one half of the searches to value the other (two folds by request). A search whose weight passes `max(1% of the searches, 10)` is valued by the model from that slot down (the share is `switched`). Without `"discount": true` a page is worth its clicks; with it, each slot's over log2(slot + 1).
- **SNIPS beside it** (self-normalized importance sampling) reweights the clicks slot by slot with no model, normalized by the weights' sum, over the top slots that each have 100 effective searches or more (`check_depth`); cascade doubly robust over those same slots is compared with it. Far apart, beyond their intervals, the model or the chances are off.
- **Support and coverage.** `support` is the effective number of searches at slot 1, `(Σw)² / Σw²` (400 or more is trusted). `coverage` is the share of the blend's value, slot by slot as the model weighs it, on pages the logging blend could have drawn: a blend far from the one that logged puts some of its rows where the log never could, and that part is the model's alone (below 95% the verdict is not proven: explore wider, a larger `top` or `tau`).
- **The verdict.** The first blend valued is judged against the logged blend's own value, each other one against the first, paired search by search: `better` or `worse` when the 95% interval of the difference leaves 0, `same` when it holds 0, and `not proven`, with why, when there are no exploring searches, the replay drifts, coverage is short, support is thin or the two estimates disagree.
- **Tuning** tries blends near a start (each head's weight scaled, a quota's shares moved, diversity changed; one or two changes each), values each by cascade doubly robust on one half of the searches (its click model cross-fitted over that half's two quarters), and values the best of those the log covers (95% or more), with the start, on the other half, which chose nothing: that held-out estimate is the one to trust. A blend the log mostly could not have drawn is not chosen, however well the click model guesses it does.
- **From Rust**, `Db::blend_requests(&export, "serp")` gathers a log's exploring requests of a blend ([`Export`](#exporting-the-log-for-training): the log, the events and the window a click counts in), `blend_eval::evaluate(&mut requests, &logging, &targets, Options { discount })` values blends (`Target { label, def, explore }`, `explore` to value an exploring fill, the best taken without), and `blend_eval::tune` tunes one; `blend_eval::versions` gives the logging blend's definition of each version.
- **On chloedb-server**, `POST /v1/blends/:name/evaluate {"export": {...}, "targets": ["serp@3", {"def": {...}, "label": "draft"}], "discount": false}` and `POST /v1/blends/:name/tune {"export": {...}, "start": ..., "rounds": 24}`, with read on the log and the events; through a coordinator, the log's rows are read from every shard. The command center's **Labs → Blending** sets a draft against the serving version this way (**Value on the log**) and tunes it toward the clicks.
## Chunks of a table's text: `chunks_of()`
> **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release.
`chunks_of(table, text_field)` is a table of the pieces of each row's text, for a table of chunks that a vector field embeds, or a budgeted context packs from.
```sql
SELECT id, n, tokens, chunk FROM chunks_of(docs, body, max_tokens => 256, overlap => 32)
WHERE lang = 'en' LIMIT 20;
CREATE TABLE chunks (id KEYWORD PRIMARY KEY, doc KEYWORD, n INT, body TEXT, tokens INT,
emb VECTOR(512) OPTIONS (embed = 'body', model = 'potion-retrieval-32M'));
INSERT INTO chunks (id, doc, n, body, tokens)
SELECT chunk_id, id, n, chunk, tokens FROM chunks_of(docs, body, max_tokens => 256);
```
- **Splits.** A text is cut where it says most: before a Markdown heading, then at blank lines, then after a sentence's end, then between words, and between characters only for a word longer than a chunk. The pieces are joined in order while a chunk holds at most `max_tokens` (256, from 16 to 8192), and a heading always starts a chunk. With `overlap => m` (0), each chunk after the first starts with about `m` tokens of the end of the one before, from a word's start.
- **Tokens** are estimated as a quarter of the characters, rounded up: close for English and most models' tokenizers, and the same on every machine.
- **Columns.** `id` (the row's key), `n` (0, 1, ...), `chunk_id` (`'#'`, a key for a table of chunks), `chunk`, `tokens` (with the overlap), and `start_char` and `end_char`, where the chunk's own text is in the row's, in characters. The query names some of them, or `*`.
- **The query** is read as written: its `WHERE` is a condition of the source table's rows, and its `LIMIT` cuts the chunks. It takes no join, `ORDER BY`, `GROUP BY` or `OFFSET`: write the chunks to a table to do those. `INSERT INTO t (columns) SELECT ... FROM chunks_of(...)` writes them, as `INSERT`s of 500 rows each. A coordinator reads the rows from its shards and splits them itself. The field is a stored `TEXT` field. A call reads as many of the table's rows as its `LIMIT` needs (each row with text gives a chunk at least; when rows without text leave the `LIMIT` unfilled it reads twice as many again), 1,000,000 at most without one, and what it reads may hold 1 GiB at most (or the query memory budget, if smaller): a read the database makes for itself is not held to a server's `--max-rows`, so this bounds it.
## Running SQL
A statement reaches ChloeDB from a program, over HTTP or in the command center. ChloeDB serves no Postgres wire protocol, so `psql` and the tools built on Postgres's drivers (DBeaver, Metabase, dbt's Postgres adapter, SQLAlchemy's Postgres dialect) do not connect to it. The ways in, quickest first:
- **Python, on a file.** `pip install chloedb`, then `chloedb.open(path).sql(statement)` runs any statement on a database file in the process, and `chloedb.dbapi` is a DB-API 2.0 driver that pandas' `read_sql`, and tools written for `sqlite3`, take ([Python](python.md)):
```sh
python3 -c 'import chloedb; print(chloedb.open("products.chloedb", read_only=True).sql("SELECT category, COUNT(*) FROM products GROUP BY category").rows)'
```
- **A server, and its SQL workbench.** `uvx chloedb-server --demo 20000 --db products.chloedb` (or `pip install chloedb-server`, then `chloedb-server ...`) serves a database on `http://127.0.0.1:7700`, whose command center has a SQL workbench (completion with the columns' types, parameters, the plan as a tree, and a check before a write). `POST /v1/sql` takes one statement, and `chloedb-server cc` is the command center in a terminal, with a SQL screen:
```sh
curl -s localhost:7700/v1/sql -H 'content-type: application/json' \
-d '{"sql": "SELECT category, COUNT(*) FROM products WHERE MATCH(body, '"'"'waterproof'"'"') GROUP BY category ORDER BY 2 DESC LIMIT 5"}'
```
- **Other languages.** `db.sql` in [JavaScript](javascript.md), the JDBC driver (`jdbc:chloedb:`) in Java, and `Db::sql` in Rust, which takes any statement, on any table, writes and `CREATE TABLE` included.
- **The `chloedb` shell**, built from source, runs one statement or reads statements from standard input. It opens a database that exists and does not create one; these lines read the demo catalogue the server above makes:
```sh
cd chloedb && cargo build --release
target/release/chloedb products.chloedb "SELECT category, COUNT(*) FROM products WHERE MATCH(body, 'waterproof') GROUP BY category ORDER BY 2 DESC LIMIT 5" --plan
target/release/chloedb products.chloedb --param t='waterproof tent' < queries.sql
```
| flag | effect |
|---|---|
| `--param name=value` | binds `:name`: a number, a string, or a JSON array for a vector |
| `--plan` | prints the plan lines the executor recorded for each statement |
| `--repeat n` | runs each statement *n* times and reports the median time |
| `--read-only` | opens the database read-only, to read it while another process writes it ([readers in other processes](index.md#readers-in-other-processes)); without it, the shell opens a database another process has open to write read-only, and says so |
From Rust, `Db::query` takes a `SELECT` and a `Params` map. Over the network, [chloedb-server](server.md) serves the same SQL over every table of a database.
### The types of an answer's columns
An answer gives each column's type, as its values have it, whatever the column is named: `int`, `float`, `bool`, `timestamp`, `text`, `vector` or `list`, and none (`null`) for a column of only `NULL`s or of values of types that do not mix (a `CASE` of text and numbers). So `MAX(ts)`, `ts AS d`, `i.ts` in a join, `date_trunc('month', ts)`, `date_bin(...)`, `CAST(ts AS DATE)` and `ts + INTERVAL '1 day'` are `timestamp`, as `ts` is, and `CAST(ts AS TEXT) AS ts` is `text`. A column of `INT`s and `FLOAT`s is `float`. Over HTTP the answer's `types` lists them beside `columns` , in Python and JavaScript `result.types`, and in Rust `ResultSet::types`; Python's [DB-API driver](frameworks.md#db-api) and `Result.to_pandas()` make a `timestamp` column's values datetimes, and an [Arrow answer](server.md#http-api) types each column as an Arrow array. The values themselves stay as JSON has them: a `TIMESTAMP` as ISO 8601 text in UTC, a `BOOL` as `true` or `false`.
## Tables
A database starts with the table it was created with, and `CREATE TABLE` adds more. `SHOW TABLES` lists their names, a row each (through `db.sql` or `POST /v1/sql`; a key limited to tables sees its own), and `GET /v1/tables` their columns too. An example, a table of orders:
```sql
CREATE TABLE orders (id KEYWORD PRIMARY KEY, customer KEYWORD, status KEYWORD, total FLOAT, note TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
```
`KEYWORD` holds exact values (ids, statuses), `TEXT` words searched with `MATCH`, `INT` and `FLOAT` numbers, `TIMESTAMP` times, and `VECTOR` embeddings; a type followed by `[]` holds a list. It needs an admin key. A larger example: Each table has its own columns, primary key, indexes and merges; the tables share the file, its write-ahead log and transactions.
```sql
CREATE TABLE authors (
id KEYWORD PRIMARY KEY,
name TEXT OPTIONS(analyzer = 'simple'),
born INT,
topics KEYWORD[],
bio TEXT OPTIONS(positions = false),
emb VECTOR OPTIONS(embed = 'name, bio', model = 'potion-retrieval-32M')
);
CREATE TABLE IF NOT EXISTS wrote (
id INT PRIMARY KEY,
author KEYWORD NOT NULL REFERENCES authors,
paper KEYWORD REFERENCES papers (id),
role KEYWORD NOT NULL DEFAULT 'author',
added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE events (
id INT PRIMARY KEY,
usr KEYWORD NOT NULL,
item KEYWORD,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) OPTIONS(shard_by = 'usr', cluster_by = 'usr', retain = '400 days');
DROP TABLE IF EXISTS wrote, authors;
```
- **Types** are `TEXT`, `KEYWORD`, `INT` (or `INTEGER`, `BIGINT`), `FLOAT` (or `DOUBLE`, `REAL`), `BOOL` (or `BOOLEAN`), `TIMESTAMP` (or `TIMESTAMPTZ`, `TIMESTAMP WITH TIME ZONE`, `DATETIME`, and `DATE`, which is a `TIMESTAMP`: a date written alone is its midnight UTC), `VECTOR(dimensions)` (1 to 65,536 dimensions), `SPARSE`, `MEDIA` and `EDGES`; `KEYWORD[]` and `INT[]` hold lists, and `VECTOR(dimensions)[]` several vectors per row ([multi-vector fields](#maxsimfield-vectors-several-query-vectors)). A `BOOL` or `TIMESTAMP` column holds one value and is neither the primary key nor a reference. PostgreSQL's and MySQL's other names take the type that holds the same values, so a schema written for them runs as it is, its lengths and precisions ignored: `VARCHAR(n)`, `CHAR(n)`, `CHARACTER VARYING`, `NVARCHAR`, `UUID` and `CITEXT` are `KEYWORD` (exact values, as `CAST(x AS VARCHAR)` makes; write `TEXT` for a column searched by its words), `SMALLINT`, `TINYINT` and `INT2`/`INT4`/`INT8` are `INT`, `NUMERIC(p, s)`, `DECIMAL` and `FLOAT8` are `FLOAT` (a double, not an exact decimal), and `TIMESTAMP WITHOUT TIME ZONE` is a `TIMESTAMP`. `SERIAL` is refused: ChloeDB has no sequences, so a row is given its number (`INT PRIMARY KEY`) or a `KEYWORD` key such as a UUID.
- **`OPTIONS(...)`** takes the options of the [JSON schema](server.md#schemas): `substring` (true: `LIKE` and `ILIKE` on the column read a [substring index](#substrings-like-and-ilike-anywhere-in-a-value)), `positions`, `stored` and `indexed` (true or false; an indexed `TEXT` or `SPARSE` field is stored unless generated, since merges rebuild its index from the stored values), `from` (the fields a generated `TEXT` field joins), `analyzer` (`'english'`, the default: stopwords dropped and words stemmed, so `running` finds `run`; `'simple'`: every word kept as written, for names and codes; `'standard'`: text in [any language and script](index.md#text-in-other-languages), Chinese, Japanese, Korean and Thai included; `'cjk'`: `standard` with pairs of characters as the terms of Chinese and Japanese; or a language, such as `'french'`, `'german'`, `'arabic'`, `'hindi'` or `'chinese'`, which is `standard` with what the language needs, a stemmer for most), `index` (`'hnsw'` with `m` and `ef_construction`, `'flat'`, or `'ivf'` with `nlist`), `partition_by` with `partition_bounds` (a graph per range or value of a column, for [filtered searches](#vector-partitions)), `codes` (`'sq8'`, `'binary'`, `'rabitq1'`, `'rabitq2'` or `'rabitq4'`; a multi-vector field searches `'binary'` by default), `keep_f32` (a multi-vector field keeps its float32 vectors to score with, four times the bytes of its 8-bit codes), `pool` (a multi-vector field merges a row's vectors whose cosine similarity is at least this, such as `0.9`, into their mean when it is written), `pool_factor` (a multi-vector field clusters a row's vectors into one group for every this many, such as `2`, by Ward's linkage, and keeps each group's mean when it is written; exclusive with `pool`), `kind` of a `MEDIA` field, `derive` (a `MEDIA` field) with `model` for [text made from media](server.md#text-from-media), `embed` with `model` for an [embedded vector field](server.md#embedded-vector-fields), which may leave out its dimensions when ChloeDB knows the model's (`VECTOR` alone), or an [embedded `SPARSE` field](server.md#term-weights-of-a-learned-sparse-model), and on a `KEYWORD[]` `semantic_id` (the vector field) with `codebook` for a [semantic-ID field](server.md#semantic-ids): `sid KEYWORD[] OPTIONS(semantic_id = 'emb', codebook = 'items-rq')`. Field lists are a string, `'name, bio'`, or `ARRAY['name', 'bio']`.
- **The primary key** is one column: `PRIMARY KEY` on it, or a `PRIMARY KEY (column)` constraint. A table without one only takes plain `INSERT`.
- **`REFERENCES table`**, or `FOREIGN KEY (column) REFERENCES table`, records that a `KEYWORD` or `INT` column holds primary keys of that table, which must exist (or be the table being created) and have a primary key of the column's type. References are not enforced: a row may name a key that is not there, and an inner join along the reference leaves that row out (`LEFT JOIN` keeps it). Joins along them are [ordinary joins](#subqueries-with-and-joins) (`FROM wrote w JOIN authors a ON w.author = a.id`).
- **`NOT NULL`** refuses a row without a value in that column, from any write: SQL, JSON, a file or the Rust API. **`DEFAULT value`** is the value a write that leaves the column out gets: a constant of the column's type on a single-valued `TEXT`, `KEYWORD`, `INT`, `FLOAT`, `BOOL` or `TIMESTAMP` column that is not the key, or `CURRENT_TIMESTAMP` (or `now()`) on a `TIMESTAMP`, the time of the statement, the same in all its rows. An `INSERT` that leaves a column out, a JSON row without its key and a CSV file without its column give it the default; a `NULL` that a write gives stays `NULL`, and a column with `NOT NULL` refuses it. In SQL the keyword `DEFAULT` stands for a column's default, in `VALUES` and in `SET`, and `CURRENT_TIMESTAMP` (or `now()`, `LOCALTIMESTAMP`) is the time of the statement there and in conditions (`SET seen = CURRENT_TIMESTAMP`, also in `ON CONFLICT ... DO UPDATE`). The Rust API writes a row as it is given; `Schema::defaults` returns a row of the defaults to start from. The JSON schema's options are `"not_null": true` and `"default"` (`"now"` for the time of the write).
- **`OPTIONS(shard_by = 'column')`** after the columns places the table's rows on [shards](server.md#tables-on-shards) by that column instead of by the primary key, so that a user's events sit on one shard together. The column is a stored, single-valued `KEYWORD` or `INT` with `NOT NULL`, other than the key, and a row keeps it: `UPDATE` does not change it (delete the row and insert it again). In JSON it is `"shard_by": "usr"`. One database places nothing, so the option only matters to a coordinator.
- **`OPTIONS(cluster_by = 'column')`** stores each segment's rows sorted by that column, rows of one value in the order they were written: a flush sorts the rows it writes, and a merge sorts the rows of the segments it joins. A user's history then sits in one run of each segment instead of scattered across it, so reading it touches a few pages rather than one per row. The column is an indexed, single-valued `KEYWORD`, `INT` or `TIMESTAMP`, and a row keeps it (`UPDATE` does not change it). Queries return the same rows either way; only `ORDER BY` fixes their order. In JSON it is `"cluster_by": "usr"`.
- **`OPTIONS(retain = '400 days')`** drops rows once their time is older than the period: a flush does not write them, and a merge leaves them out of the segment it writes, or drops a segment whose rows are all past it without rewriting or reading anything; the merger looks for such segments on its own. Such a table's segments merge only within windows of time, a thirtieth of the period each (from a second to a day): a segment holds rows of one window, as of its newest row, so a table kept 30 days holds segments of a day at most, and each leaves whole once its newest row is past the period rather than being rewritten as its rows expire. Until then a query still finds them, so filter on the time where that matters (`WHERE ts > '2025-10-01'`). The time is the table's only `TIMESTAMP` column, or the one `retain_by = 'column'` names (indexed, single-valued, and not changed by `UPDATE`); a row without one is kept. A period is a whole number and a unit: seconds, minutes, hours, days or weeks (`'90 s'`, `'12h'`, `'2 weeks'`). In JSON it is `"retain": "400 days"` with `"retain_by"`.
- **`OPTIONS(expire_by = 'column')`** expires each row at the time its column holds, as a key-value store's TTL does: from that moment on queries, counts, joins and reads by key leave the row out, and a write by its key finds no row there (an `INSERT` of the key succeeds, an `UPDATE` changes nothing). Rows without a time never expire, and `UPDATE ... SET until = ...` (or a `set` in place) moves a row's time. A server that takes writes deletes expired rows every few seconds, and `Db::expire` (Python: `expire()`) does it at once; those deletes are logged as any delete is, so [replicas](server.md#replication-a-primary-and-its-replicas) hold the same rows without reading a clock. Unlike `retain`, which drops old rows when segments are written and leaves them visible until then, an expired row is gone for reads at once. The column is an indexed, single-valued `TIMESTAMP`, the table has a primary key, and `DROP COLUMN` keeps the column (`RENAME COLUMN` renames the option too). It makes the database format 3, feature `expire_by`. In JSON it is `"expire_by": "until"`.
```sql
CREATE TABLE sessions (
id KEYWORD PRIMARY KEY,
usr KEYWORD,
until TIMESTAMP
) OPTIONS(expire_by = 'until');
INSERT INTO sessions (id, usr, until) VALUES ('s1', 'u7', '2026-11-02T12:00:00Z');
```
- **`OPTIONS(compression = 'zstd')`** compresses the table's stored rows (its doc store) with zstd in 32 KiB blocks instead of LZ4 in 16 KiB ones. On four logs from Loghub the doc store took 32% to 39% less, and the database 9% to 16% less, while a read of one row by key took 12% to 40% longer (48 µs instead of 34 on 11M lines) and a scan of every row about as long (`chloedb/results/log-bytes/`, on a 4-core cloud container). It suits tables that are written far more than read row by row, such as logs; queries that count, filter, group or search without returning rows read no stored rows either way. Segments written after the option use it, and older ones keep LZ4 until a merge rewrites them. It makes the database format 3, feature `zstd`. In JSON it is `"compression": "zstd"`; `'lz4'` is the default.
- **`OPTIONS(edges = 'src, dst, w')`** makes each row an edge of a graph over another table's rows, which walks over that table follow ([edge tables](#edge-tables)). In JSON it is `"edges": "src, dst, w"`.
- **`DROP TABLE`** drops tables other than the first. A table that another table references goes with it (`DROP TABLE wrote, authors`) or with `CASCADE`, which removes those references.
- **`CREATE TABLE ... AS SELECT`** makes a table of a `SELECT`'s rows ([below](#rows-from-a-select-insert--select-and-ctas)).
- Every other clause (`UNIQUE`, `CHECK`, `ON DELETE`, constraint names, a `DEFAULT` that is an expression, `CREATE OR REPLACE TABLE`, temporary tables) is an error.
`CREATE TABLE`, `ALTER TABLE` and `DROP TABLE` run through `Db::sql`, Python's in-process [`chloedb.Database`](python.md), and [chloedb-server](server.md#schemas)'s `POST /v1/sql`, where a coordinator runs them on every shard.
### Changing a table's columns
```sql
ALTER TABLE products ADD COLUMN stock INT NOT NULL DEFAULT 0;
ALTER TABLE products ADD COLUMN IF NOT EXISTS brand KEYWORD, ADD note TEXT;
ALTER TABLE products ADD COLUMN emb2 VECTOR OPTIONS(embed = 'title', model = 'potion-retrieval-32M');
ALTER TABLE products RENAME COLUMN note TO notes;
ALTER TABLE products DROP COLUMN IF EXISTS notes;
ALTER TABLE IF EXISTS drafts DROP COLUMN body, DROP COLUMN title;
```
`ALTER TABLE` changes the columns of any table, the first included, while it holds rows; the changes of one statement apply in order, as one change.
- **`ADD COLUMN`** (or `ADD`) takes a column as `CREATE TABLE` does, with its type, `NOT NULL`, `DEFAULT`, `REFERENCES` and `OPTIONS`, and puts it last. Rows written before it read it as its default, or `NULL` without one (a `TIMESTAMP` with `DEFAULT CURRENT_TIMESTAMP` too: the default is the time of each later write): in `SELECT`, `WHERE`, `ORDER BY`, aggregates and searches alike. Writes from then on take it. A `NOT NULL` column without a default can only be added to a table without rows. A column added with `embed` gets its model and embeds the rows written from then on; the rows before get theirs from [the backfill](server.md#embedded-vector-fields), which a server runs once the model opens, Python's `Database` before the `ALTER TABLE` (or `add_column`) returns, and Rust with `Db::embed_backfill`; until then they have none, and `similarity()` does not find them. A generated `TEXT` column, a semantic-ID column, `EDGES` and a primary key cannot be added.
- **`DROP COLUMN`** drops a column and its values; a column added again under the same name is a new column, `NULL` in the older rows. The primary key, a table's only column, a column another field names (as the source of a generated text, an embedding, a caption or semantic IDs) and one the table's options name (`shard_by`, `cluster_by`, `retain_by`, `expire_by`, `edges`) stay, and the statement says what names it; so do columns a [rank profile](#rank-profiles-a-ranking-kept-with-its-table) of the table ranks by.
- **`RENAME COLUMN a TO b`** keeps the column's values, and the fields and options that name it follow it; a rank profile does not, so a column a profile ranks by keeps its name until the profile is dropped or replaced.
- **`IF EXISTS`** after `ALTER TABLE` skips a table that is not there; `ADD COLUMN IF NOT EXISTS` and `DROP COLUMN IF EXISTS` skip a column that is, or is not. Positions (`FIRST`, `AFTER`), `ALTER COLUMN`, `RENAME TO` (of the table) and `CASCADE` are errors.
A change writes nothing but the table's schema: it waits for writes in flight, writes the memtable as segments (a write-ahead log names columns by position), and commits the new schema. A segment written before a column was added does not hold it; when it is opened, the column's index is built in memory over its rows' default, and the next merge that rewrites the segment writes the column for real. A dropped column's values stay in the older segments, unread, until merges rewrite them. The Rust API is `Db::alter_table(table, &[Alter::AddField(field), Alter::DropField(name), Alter::RenameField { from, to }])`; a database with a column added later needs the feature `added_fields`, so a version of ChloeDB from before it refuses the database.
On chloedb-server, a coordinator runs `ADD COLUMN` and `RENAME COLUMN` on every shard and then serves the table as altered; it refuses `DROP COLUMN`, since its plans name a table's columns by position and a query planned while some shards had dropped the column would read the next one. A primary ships the change to its replicas in its place among the writes, as it ships `CREATE TABLE` and `DROP TABLE`, and its replicas give the table the same columns under the same field ids ([replication](server.md#replication-a-primary-and-its-replicas)).
## Writes
```sql
INSERT INTO products (id, title, price, tags, emb) VALUES ('p1', 'red mug', 12.5, ARRAY['kitchen', 'gift'], :v);
INSERT OR REPLACE INTO products (id, title, price) VALUES ('p1', 'red mug, large', 14.0);
INSERT INTO products (id, title, price) VALUES ('p2', 'blue mug', 11.0) ON CONFLICT (id) DO NOTHING;
INSERT INTO products (id, title, price) VALUES ('p1', 'red mug', 12.0)
ON CONFLICT (id) DO UPDATE SET price = excluded.price, stock = stock + 10;
UPDATE products SET stock = stock - 1, price = 11.0 WHERE id = 'p1';
UPDATE products SET stock = DEFAULT WHERE id = 'p2';
UPDATE products SET price = round(price * 0.9, 2), title = title || ' (sale)' WHERE tags = 'gift';
INSERT INTO products (id, stock) VALUES ('p1', 5)
ON CONFLICT (id) DO UPDATE SET stock = coalesce(stock, 0) + excluded.stock;
DELETE FROM products WHERE MATCH(title, 'discontinued');
DELETE FROM products WHERE stock = 0 ORDER BY price LIMIT 100;
```
- A write names its table, any table of the database.
- **`INSERT`** fails on a primary key that already exists. **`INSERT OR REPLACE`** (or `REPLACE INTO`) replaces that row, an upsert. **`ON CONFLICT (key) DO NOTHING`** (or `INSERT OR IGNORE`) writes only the rows whose key is new, and the first of a key the statement repeats. **`ON CONFLICT (key) DO UPDATE SET ...`** inserts the new keys and sets fields of the rows already there, where `excluded.column` is the value the statement gave; a key that comes twice in one such statement is an error. On a cluster, a table placed by `shard_by` keeps its keys unique across shards for `INSERT`, `INSERT OR REPLACE` replaces a row only on its `shard_by` value's shard, `ON CONFLICT DO UPDATE` takes rows of one shard, and `UPDATE`/`DELETE ... LIMIT` pick their rows first ([cluster limits](cluster-limits.md)). Lists are `ARRAY[…]`; a vector is a parameter, `ARRAY[…]` or a JSON array string; a multi-vector value is a list of vectors (`ARRAY[ARRAY[…], ARRAY[…]]`, a parameter holding a list of vectors, or `'[[…], […]]'`), and one vector given to it is a list of one; a `SPARSE` value is a JSON object string, and a `MEDIA` value a URI or a JSON object string.
- **`UPDATE`** takes any `WHERE` a `SELECT` of its table takes, and a `LIMIT`. A `WHERE` the table's indexes answer runs as it is; another (a `TEXT` column compared with `=`, `LIKE` of a `TEXT` column, `lower(...)`, `IN (SELECT ...)`, `[NOT] EXISTS`) picks the rows' keys with that `SELECT`, under the writer lock as the write runs, and writes those rows, so the rows a `SELECT` with that `WHERE` counts are the rows written (`EXPLAIN` says `picks its rows by key`). Through a coordinator, one whose `WHERE` has a subquery picks the keys over every shard first ([cluster limits](cluster-limits.md)). Setting only single-valued `INT` and `FLOAT` fields (`SET clicks = clicks + 1`) changes them in place, without rewriting the row, which suits counters and prices that change often. Setting any other field rewrites the row, which needs every text field stored or generated.
- **`SET`** takes a value or any expression of the row: arithmetic, `||`, `CASE`, `NOT`, comparisons, `lower`, `upper`, `length`, `abs`, `round` and `coalesce` over the row's columns, and in `ON CONFLICT DO UPDATE` over `excluded.column` too. Every expression reads the row as it was, so `SET a = b, b = a` swaps two fields. The result is stored as the field's type: a whole number fits an `INT` (`clicks = price * 2`), but `7 / 2` is 3.5 and an error there (`round(clicks / 2)` fits); one value set to a multi-valued field becomes a list of it. NULL in gives NULL out, as in SQL and as a `SELECT` of the same expression reads it, in every expression (`n + 1`, `1 + n` and `n * 2` alike): a counter that starts from NULL is `coalesce(n, 0) + 1`. **Changed:** 0.3.9 and earlier counted a NULL as zero in `field + number` and `field - number` only. A multi-valued field without values is NULL to `coalesce` and `IS NULL`. Searches, scores and aggregates (`MATCH`, `bm25`, `score()`, `COUNT`) are errors in `SET`. A statement that cannot set one of its rows sets none.
- **`DELETE`** takes any `WHERE` a `SELECT` of its table takes, as `UPDATE` does, and `ORDER BY` with `LIMIT` to delete the first rows in that order. `DELETE FROM t` without one deletes every row (there is no `TRUNCATE`).
- **`INSERT ... SELECT`** writes a `SELECT`'s rows ([below](#rows-from-a-select-insert--select-and-ctas)).
- `RETURNING`, `UPDATE ... FROM`, `DELETE ... USING`, `ON DUPLICATE KEY UPDATE` and `DO UPDATE ... WHERE` are errors.
### Rows from a SELECT: INSERT ... SELECT and CTAS
```sql
CREATE TABLE refunds (PRIMARY KEY (id)) AS
SELECT id, customer, amount, notes FROM tickets WHERE MATCH(notes, 'refund OR chargeback');
CREATE TABLE by_customer AS
SELECT customer, COUNT(*) AS n, SUM(amount) AS total FROM refunds GROUP BY customer;
INSERT INTO refunds (id, customer, amount, notes)
SELECT id, customer, amount, notes FROM tickets WHERE opened > :since AND MATCH(notes, 'refund')
ON CONFLICT (id) DO UPDATE SET amount = excluded.amount;
```
- **The `SELECT`** is any query: joins, `WITH`, `GROUP BY`, `UNION`, searches, parameters. It runs on one snapshot, as a query does, and every row it returns is written: it is not cut at a server's `--max-rows`, only held to the statement's memory budget. A `SELECT` ranked by a score without a `LIMIT`, which returns its best 100 rows ([limits](#statement-shape)), is refused rather than written in part: give it a `LIMIT`, or put the match in `WHERE`.
- **`INSERT ... SELECT`** writes each row as `INSERT ... VALUES` would: to the columns it names, in order, or without a list to the table's columns in order; columns it leaves out take their `DEFAULT`; `ON CONFLICT`, `OR REPLACE` and `OR IGNORE` apply as to `VALUES`. Each value goes in as `SET` gives one: `NULL` stays `NULL`, a whole `FLOAT` fits an `INT`, a number goes into a `KEYWORD` as its text, and a value that fits no column of its type refuses the statement, naming the row.
- **`CREATE TABLE t AS SELECT ...`** (CTAS) makes a table with a column for each of the `SELECT`'s, named as the `SELECT` names them (`a.zone` is `zone`; an expression needs `AS name`), then writes its rows. A column read from a table keeps that column's type and its options (a `TEXT` its analyzer, a `VECTOR` its dimension), but not its key, `NOT NULL`, `DEFAULT`, `REFERENCES` or what made it (an embedding, a generated text). Another column takes the type a `CAST` names (`CAST(x AS TEXT)` is `TEXT`; `AS VARCHAR` or `AS KEYWORD` is `KEYWORD`), else its values' type: whole numbers `INT`, numbers `FLOAT`, `BOOL`, `TIMESTAMP`, and text `KEYWORD` when its values are labels (none over 256 bytes, 2.5 words or fewer on average) and `TEXT` when they are prose, as a [file's import](#loading-a-file-csv-tsv-json-lines) types them. A column with no values takes its expression's type (`COUNT(*)` is `INT`, `amount * 2` `FLOAT`), and one of no known type is `KEYWORD`, as PostgreSQL makes such a column text. The table has no key unless the statement gives one, after the table's name: `(PRIMARY KEY (id))`, or columns defined with their types, `(id INT PRIMARY KEY, body TEXT OPTIONS(analyzer = 'french'))`, which take those definitions (a defined column the `SELECT` does not give is added, `NULL`). The table's `OPTIONS(...)` and `IF NOT EXISTS` (which runs nothing when the table is there) are as for any table. Rows that cannot be written (a key two rows share, a `NULL` key) refuse the statement, and the table is dropped.
- **One transaction.** On one database (`Db::sql`, Python's [`chloedb.Database`](python.md), one chloedb-server) the rows are written in one transaction: all or none. A CTAS makes its table first, in a commit of its own, and drops it when its rows fail. Through a coordinator, the `SELECT` runs over every shard (a shard that does not answer fails it), then its rows go in as `INSERT`s of 500 rows each (one row each with `ON CONFLICT ... DO UPDATE`, which a coordinator runs on one shard's rows), each a write of its own: a failure part way leaves the rows written before it ([cluster limits](cluster-limits.md)). A `SELECT` of one table's rows, each by itself (no `GROUP BY`, aggregate, `ORDER BY`, `LIMIT`, ranking or join), into a table placed by its key runs on the shards instead, each writing its rows straight to the shards of their keys, so they never pass through the coordinator; so does a `GROUP BY` of the column that is the new table's key, each shard sending its partial groups to the shard of their key, which merges and writes them. There the new table needs a key the statement names, or `OPTIONS(shard_by = ...)`, which places each row on a shard: one without is refused before its `SELECT` runs.
- **Changed:** 0.3.9 and earlier refused both, but an `INSERT` of [`chunks_of`](#chunks-of-a-tables-text-chunks_of)'s rows, which runs as before.
### Loading a file: CSV, TSV, JSON lines
Many rows at once come from a file rather than `INSERT`s: `POST /v1/import?table=orders` with the file as the body and its content type (`text/csv`, `text/tab-separated-values`, `application/x-ndjson` or `application/json`), or the MCP tool `import` with the file's text in `data` (or the rows as objects in `rows`). A CSV's first line names the columns; columns the table does not have are skipped and named in the answer, and an empty cell is the column's `DEFAULT` (`?empty=null` makes it `NULL`). The table must exist first (`CREATE TABLE`, above), or, with an admin key, the MCP tool's `create: true` makes it from the rows: whole numbers become `INT`, numbers `FLOAT`, `true`/`false` `BOOL`, ISO dates `TIMESTAMP`, text of two and a half words or more on average `TEXT` and other text `KEYWORD` (labels too: at least 100 values, none over 256 bytes, each repeating ten times on average, however many words they have), with a column named `id` (or the one `key` names) as the primary key, and the answer shows the `CREATE TABLE` it ran. Parquet and SQLite files load the same way ([server](server.md#loading-rows)), and the command center's Import page takes a file dropped on it.
```bash
curl -X POST "$URL/v1/import?table=orders" -H "authorization: Bearer $KEY" -H "content-type: text/csv" --data-binary @orders.csv
```
Each statement is one transaction, and returns the number of rows it wrote. From Rust, the transaction API (`Database::begin`, `WriteTxn::insert`, `upsert`, `set`, `delete`, `commit`, and `WriteTxn::table` for the other tables) groups several writes into one, across tables too; `WriteTxn::upsert_if_newer` keeps whichever version of a row has the highest version number, for replaying a feed out of order.
## EXPLAIN
`EXPLAIN ` shows the plan of a `SELECT`, `INSERT`, `UPDATE` or `DELETE` without running it: a row per line, in a column named `plan`, the root first and each operator's input indented under it. It runs in-process (`db.sql` in Python, `Db::sql` in Rust), over HTTP through `POST /v1/sql` (and so in Python's `chloedb.dbapi`, the SQL workbench and `chloedb-server cc`), and [`POST /v1/explain`](server.md#http-api) answers the same lines as `tree`, for the statement with or without `EXPLAIN` before it. **Changed:** 0.3.9 and earlier refused `EXPLAIN` over `/v1/sql`, and `/v1/explain` took only a `SELECT`.
```sql
EXPLAIN SELECT category, COUNT(*) AS n FROM papers WHERE published >= '2026-10-01'
GROUP BY category HAVING COUNT(*) >= 2 ORDER BY n DESC, category LIMIT 5;
```
```text
Project: category, COUNT(*) AS n
Limit: 5
Sort: COUNT(*) DESC, category
Filter: COUNT(*) >= 2.0
Aggregate by category: COUNT(*)
Search papers
filter: published >= TIMESTAMP '2026-10-01T00:00:00Z'
```
A `Search` is the rows of one table that its `filter` holds for, ranked by its `order`; the operators above it group, keep, sort, cut and name them, and a write's operator (`Insert`, `Update`, `Delete`) sits on top. The plan is the statement as bound: values have their field's type, and a `NOT` over a field that can be null also says `x IS NOT NULL`, since a row without a value matches neither a comparison nor its negation.
`EXPLAIN FORMAT JSON` (or `EXPLAIN (FORMAT JSON)`) gives the plan as one row of JSON: fields by their position in the table, typed values (`{"int": 5}`, `{"text": "5"}`), a version and the features the plan needs. ChloeDB refuses a plan from a newer version by name. `EXPLAIN ANALYZE` and other formats are refused.
A compound query's plan has operators over rows in memory above its `Search`es, and its JSON needs the feature `operators`:
```sql
EXPLAIN SELECT a.id, b.title FROM papers a JOIN papers b ON a.cites = b.id WHERE a.year >= 2019 ORDER BY a.year DESC LIMIT 5;
```
```text
Project: id AS "a.id", title AS "b.title"
Limit: 5
Join on targets(cites) = id
Project: id, year, cites
Search papers
filter: year >= 2019
order: year DESC
Project: title, id
Search papers
```
`Join` (or `Left join`) matches its two inputs on the keys after `on`, `targets(f)` being the rows an `EDGES` field links to, with any other `ON` condition after `AND`; `With` names its results, which `Ref` reads; `Key order of top` puts rows in the order of the `WITH` result `top`; `Distinct` keeps each row once, and `Distinct on: video` the [first row of each group](#the-first-row-of-each-group-distinct-on). A subquery sits in its condition: `IN values of (...)` (its values), `IN keys of (...)` (its rows' keys), `EXISTS (...)` and a scalar `(...)`, each shown on one line with `;` between its operators. `SELECT DISTINCT` of the table alone is a `GROUP BY`, a single-table query.
Every statement runs as its plan, and a plan in JSON runs on its own: `Db::run` in Rust, `Database.run` in [Python](python.md#querying) and [`POST /v1/plan`](server.md#http-api) over HTTP take one, and check it against the table's schema as the SQL binder checks a statement.
## Reading a plan
`--plan` shows what the planner decided, segment by segment. The same statement can get different plans as the data changes. In the evaluation, an `OR` filter matching about 15% of documents was scanned exactly on SciFact's 5,183 documents, but on the larger collections the planner measured 11% near the query and post-filtered the HNSW result. An RRF query's topic filter matched 11% of Quora globally but only 3.4% near the query, so the planner switched to an exact scan of its 58,767 members, at 3.1 ms. [Planning and execution](index.md#planning-and-execution) describes the choices.
## Differences from PostgreSQL
A query written for PostgreSQL mostly runs here and gives the same rows, but not always. These are the differences people porting SQL from PostgreSQL meet most, as this release has them: first the answers that differ without an error, then what is refused (most refusals' messages say what to do instead). The list of refusals is not complete: a statement it does not name can still be refused, and its message says so.
**Connecting.** There is no Postgres wire protocol: `psql`, DBeaver, Metabase, dbt's Postgres adapter and SQLAlchemy's Postgres dialect do not connect, and there is no dbt adapter or SQLAlchemy dialect of ChloeDB's own. [Running SQL](#running-sql) lists the ways in: Python's `chloedb.dbapi` (DB-API 2.0, which pandas' `read_sql` reads), JDBC, HTTP and the SQL workbench. [Following Postgres](postgres.md) copies a Postgres database into ChloeDB; it does not let Postgres's clients in.
**Answers that differ, with no error:**
| expression | ChloeDB | PostgreSQL | to get PostgreSQL's |
|---|---|---|---|
| `7 / 2` | `3.5`: `/` always gives a `FLOAT` | `3` for two integers | `(7 - 7 % 2) / 2` (3.0) |
| `ORDER BY x DESC` with `NULL`s | `NULL`s last | `NULL`s first | `ORDER BY x DESC NULLS FIRST` |
| `greatest(1, 2)`, `least(1, 2)` | `2.0`, `1.0` (`FLOAT`) | `2`, `1` | `CAST(greatest(a, b) AS INT)` |
| `floor(x)`, `ceil(x)` of a `FLOAT` | an `INT` (`floor(2.7)` is 2) | a `float8` (`2`) | `floor(x) * 1.0` |
| `concat('a', TRUE)` | `'atrue'` | `'at'` | `CASE WHEN b THEN 't' ELSE 'f' END` |
| `SELECT a.id, b.title FROM a JOIN b ...` | columns `a.id`, `b.title` | `id`, `title` | `a.id AS id, b.title AS title` |
| a correlated `(SELECT COUNT(*) ... WHERE t.a = o.a)` | `10.0` (`FLOAT`) | `10` | alias it and read it as a number |
Ascending order puts `NULL`s last in both. [Following Postgres](postgres.md#how-postgres-columns-become-fields) makes a `numeric` column a `FLOAT`, so `CAST` and `round` take its halves to the even neighbour (2.5 to 2), where PostgreSQL rounds a `numeric`'s away from zero (to 3). **Changed:** 0.3.7 and earlier rounded every half away from zero, kept the rows without a value in `n != 1.5` on an `INT` column, and gave `'a'` for `'a' || NULL`; each now answers as PostgreSQL does. **Changed:** 0.3.8 and earlier refused `ORDER BY` the alias of a group column after `GROUP BY` or `DISTINCT` ("no such column") and `NULLS FIRST` there, read `json_extract(doc, '$.a.b')` as `NULL` outside `WHERE`, and on DataFusion (a query over more than 4,096 rows) added `FLOAT` sums in order, so totals that tie on fewer rows could differ in their last digit and a `RANK` over them change; each now answers as PostgreSQL does, and as on fewer rows.
**`TEXT` and `KEYWORD`.** A `TEXT` column is text searched by its words (`MATCH`, `bm25`), and a `KEYWORD` a value compared whole; PostgreSQL's `text` is both. A stored `TEXT` column also groups (`GROUP BY country`, `SELECT DISTINCT country`) and compares with `=` and `LIKE`, by its stored text read row by row, where a `KEYWORD`'s index answers both. Imports make a column of prose a `TEXT` one, by its values (more than two and a half words a value on average: [SQLite](sqlite.md#how-sqlite-columns-become-fields), [Parquet](parquet.md#how-parquet-columns-become-fields)), and following Postgres makes every `text` and `varchar` one: create the table first with `KEYWORD` for the columns you group and filter by often.
**Writes.** An `UPDATE` or a `DELETE` takes any `WHERE` a `SELECT` of its table takes ([writes](#writes)); one the indexes cannot answer (a subquery, a `TEXT` column compared, a function of a column) picks the rows' keys first, under the writer lock. **Changed:** 0.3.7 and earlier refused such a `WHERE` in a write. `INSERT ... SELECT` and `CREATE TABLE ... AS SELECT` run ([above](#rows-from-a-select-insert--select-and-ctas)), their rows in one transaction on one database. Refused: `UPDATE ... FROM`, `DELETE ... USING`, `RETURNING`, `TRUNCATE` (`DELETE FROM t` deletes every row), a subquery as a value in `SET` (`SET x = (SELECT MIN(y) FROM t)`: run it first and pass its answer as a parameter), and `ON CONFLICT ... DO UPDATE ... WHERE` (put the condition in the value: `SET x = CASE WHEN n > 3 THEN excluded.x ELSE x END`).
**Transactions.** `BEGIN`, `COMMIT` and `ROLLBACK` are refused: each statement is a transaction of its own. Several writes commit together as the operations of one `POST /v1/write` (or `write(ops)` in Python and JavaScript), and through Rust's transaction API ([Loading a file](#loading-a-file-csv-tsv-json-lines), at its end).
**Tables, views and indexes.** Refused: `CREATE VIEW` and `CREATE MATERIALIZED VIEW` (a [stored function](#stored-functions) `RETURNS TABLE` is a view with parameters, and a [rollup](#rollups-create-rollup-a-materialized-view-of-counts-over-time) keeps counts up to date), temporary tables (the message says what to write instead), `CREATE INDEX` (every column is indexed by its type when the table is made), `ALTER COLUMN ... TYPE`, `ALTER TABLE ... RENAME TO`, `UNIQUE`, `CHECK`, and a primary key of more than one column. `REFERENCES` are recorded, not enforced. The first table of a database cannot be dropped.
**Queries.** Refused: `WITH RECURSIVE` (walk a graph with [`REACHABLE` and `PATH`](#graphs)), `GROUP BY ROLLUP`, `CUBE` and `GROUPING SETS` (a `UNION ALL` of `GROUP BY`s), `CROSS JOIN`, tables listed with commas, `LATERAL`, `JOIN ... USING`, `NATURAL JOIN`, a join whose `ON` has no equality of the two tables' columns, and a window frame `RANGE` with an `INTERVAL` offset; the messages of the `ROLLUP` and `USING` refusals show the query to write instead. Also refused, with what to write:
| refused | write instead |
|---|---|
| `a IS DISTINCT FROM 'x'` | `(a != 'x' OR a IS NULL)` |
| `<`, `>`, `BETWEEN` on a `KEYWORD` (`sku BETWEEN 'A' AND 'C'`, `month >= '2023-01'`) | `IN`, `LIKE 'prefix%'`, or the value kept as a number or a time (`month` as the `INT` 202301, or a `TIMESTAMP`), which compares by range |
| `SUM(DISTINCT x)`, `AVG(DISTINCT x)` | `SELECT SUM(x) FROM (SELECT DISTINCT x FROM t) d` |
| `COUNT(DISTINCT a, b)` | `SELECT COUNT(*) FROM (SELECT DISTINCT a, b FROM t) d` |
| a subquery as a value in `HAVING` (`HAVING SUM(x) > (SELECT AVG(x) FROM t)`) | run the inner query first and pass its answer as a parameter |
| `LIKE ... ESCAPE` | none yet: `%` and `_` in a pattern are always wildcards |
| `ILIKE ANY (ARRAY[...])` | `a ILIKE '%x%' OR a ILIKE '%y%'` |
| `doc->>'color'`, `doc->'a'` | `doc.color`, or `json_extract(doc, '$.color')` ([JSON fields](#json-fields-keys-no-schema-names)) |
`INTERVAL '1 month'` moves a time written as a value, not a column's, and two times do not subtract: [`date_diff('second', a, b)`](#parts-of-times-date_trunc-extract-and-strftime) is the seconds between them (`'day'` the days), and `EXTRACT(epoch FROM b) - EXTRACT(epoch FROM a)` the seconds with their fractions.
**Functions.** Over rows ChloeDB computes `lower`, `upper`, `length`, [`substr` (`SUBSTRING`), `trim` (`TRIM`, `btrim`), `ltrim`, `rtrim`, `replace`, `concat`, `nullif`](#text-and-numbers-substr-trim-replace-concat-nullif-floor-and-ceil), `abs`, `round`, `floor`, `ceil`, `coalesce`, `ln`, `log`, `exp`, `sqrt`, `pow`, `least`, `greatest`, `sigmoid`, `clamp`, `dot`, `date_trunc`, `date_part` (`EXTRACT`), `date_diff`, `strftime`, `date_bin`, `time_bucket`, `hash`, `CASE` and `CAST`, besides its search, vector and JSON functions; over groups, the [aggregates](#aggregates), `STRING_AGG` among them. Among those PostgreSQL has and ChloeDB does not: `left`, `right`, `position`, `split_part`, `regexp_replace`, `lpad`, `initcap`, `concat_ws`, `trunc`, `mod`, `sign`, `random`, `md5`, `to_char`, `age` and `array_agg`. An unknown function's error lists those that exist. **Changed:** 0.3.8 and earlier refused `substr`, `trim`, `replace`, `concat`, `nullif`, `floor`, `ceil`, `date_diff` and `STRING_AGG`.
**The catalog.** There is no `information_schema` or `pg_catalog`, and `DESCRIBE` runs in the SQL workbench only. `SHOW TABLES` lists the tables, and `GET /v1/tables` gives each table's columns and the `CREATE TABLE` that makes it.
---
# Graphs in ChloeDB
Rows can link to other rows. A traversal, a shortest path or personalized PageRank runs in the same SQL statement as BM25, filters and vector search, and can start from any of them. On arXiv, the papers cited by a new paper's two nearest neighbours find twice as many of its references as vector search alone. A graph built from the vectors themselves does not help.
## Rows are nodes
Graph databases keep nodes and edges in stores of their own. ChloeDB keeps them in a table: a row is a node, and an `EDGES` field holds the row's outgoing edges as a JSON array of targets, each a primary key of the same table, optionally with a label and a positive weight.
```sql
-- id KEYWORD PRIMARY KEY, title TEXT, body TEXT, year INT, emb VECTOR(512), cites EDGES
INSERT ... ('p1', 'Attention is all you need', ..., 2017, [...],
'["p7", ["extends", "p9"], ["refutes", "p11", 0.5]]')
```
Formally, a snapshot *S* holds rows *V* with keys κ : *V* → *K*, and edges
$$
E \subseteq V \times K \times L \times \mathbb{R}_{>0},
\qquad (u, k, \ell, w):\ \text{row } u \text{ points at key } k \text{ with label } \ell \text{ and weight } w
$$
An edge is resolved when a query follows it:
$$
\rho_S(k) = \text{the live row } v \in V \text{ with } \kappa(v) = k, \text{ if there is one}
$$
A key has at most one live row in a snapshot, so ρS is a function. When it has none (the target was deleted, or never existed), the edge dangles and traversals skip it, as a foreign key without a constraint would.
Edges belong to their source row and point at keys, not storage positions. They are written, logged, updated, deleted, merged and snapshotted with the row, and nothing else in the engine had to change. A merge rewrites every docID and an update moves a row to a newer segment, but neither changes a key, so no edge is ever rewritten. The price is a lookup per hop, and most of the engineering below goes into making it cheap.
## Storing edges

Every segment, on disk or built from the memtable, gets one section per indexed `EDGES` field, read in place through `mmap`:
- **Out-edges.** A CSR over local docIDs: offsets, then per edge its source, its target key (an `i64`, or offsets and bytes for string keys), a label code and a weight. Labels and weights are stored only when some edge has one.
- **Reverse index.** Edges grouped by target key, the groups ordered by the key's 64-bit hash under the radix directory of the primary-key index, with each edge's source stored in group order. "Which rows point at key *k*" is one directory read and one key comparison per group, then a sequential read. Integer hashes are a bijection and need no comparison; colliding string keys form separate groups.
- **Same-segment hints.** Per edge, the docID its target had in this segment when the segment was built. Since ρS has one answer, a hinted row that is still live is that answer, and the hop needs no lookup.
A hop from *u* along its edges therefore costs, per edge,
$$
c_{\text{out}} = p_{\text{hint}}\,c_{\text{live}} + (1 - p_{\text{hint}})\Bigl(p_{\text{memo}}\,c_{\text{memo}} + (1 - p_{\text{memo}}) \sum_{i \le j^*} c_{\text{probe},i}\Bigr)
$$
where *p*hint is the share of targets built into the same segment and still live, *p*memo the share already resolved earlier in the query, and *j*\* the segment where the key is found. A hop against the edges costs one reverse-index probe per segment for *u*'s key, then a liveness check per source. The section takes about
$$
b \approx \underbrace{8}_{\text{target}} + \underbrace{4}_{\text{source}} + \underbrace{4 + 4}_{\text{reverse}} + \underbrace{4}_{\text{hint}} + \frac{8\,\lvert V \rvert + 16\,\lvert K_E \rvert}{\lvert E \rvert}\ \text{bytes per edge}
$$
with *K*E the distinct targets. That comes to 27 bytes per edge on arXiv, where the graph is under 5% of the file:

## The SQL
Two predicates, a column and a score join the existing functions. Each takes seeds: a key, a parameter, a tuple of keys, or any subquery over the same table, so a vector search, a BM25 query or a facet filter can be the way into the graph.
```sql
-- papers within two citations of p1, either way, nearest first
SELECT id, title, hops() FROM papers
WHERE REACHABLE(cites, 'p1', hops => 2, dir => 'both') ORDER BY hops(), id LIMIT 20;
-- one shortest path, only through surveys
SELECT id, hops() FROM papers
WHERE PATH(cites, 'p1', 'p9', max_hops => 6, through => kind = 'survey') ORDER BY hops();
-- the way in is a vector search: the papers its two best hits cite, by similarity
SELECT id FROM papers
WHERE REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2))
ORDER BY similarity(emb, :q) DESC LIMIT 20;
-- personalized PageRank from hybrid hits, fused with both rankings
SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q),
ppr(cites, (SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q)) DESC LIMIT 2), weighted => 1)) DESC LIMIT 20;
```
The functions and their options are listed in the [query language reference](query-language.md#graphs).
## Planning and traversal

A traversal does not respect segment boundaries, so graph computations run first, over the whole snapshot. Seeds are resolved (a seed subquery runs as a query of its own on the same snapshot), and the traversal runs. Its result becomes, per segment, a materialised document set with exact cardinality, plus each row's distance and PageRank score. The planner then sees a graph predicate as a filter whose size it knows exactly: a vector search over a neighbourhood of a few hundred rows becomes an exact scan of those rows.
```mermaid
flowchart LR
SD["seeds keys, a tuple or a subquery"] --> TR["traversal over the snapshot BFS · bidirectional path · PageRank push"]
TR --> PS["per segment exact document set hops() and ppr() by row"]
PS --> PL["usual plan probe or materialise filters vector, BM25, fusion, facets"]
```
The traversals:
- **Reachability:** breadth-first search, frontier by frontier; a search that would meet more than `max_nodes` rows besides its seeds is an error rather than an answer that depends on the order of the edges.
- **Shortest paths:** bidirectional breadth-first search, always expanding the smaller frontier, forward along the edges or backward against them. With `through`, each side keeps the rows it meets that fail it as dead ends, and the halves meet only at a row that passes it or at an end, so every middle row of the path passes `through`.
- **Personalized PageRank:** forward push (Andersen, Chung and Lang, 2006). The vector π solves
$$
\pi = \alpha\, e_S + (1 - \alpha)\, \pi W, \qquad W_{uv} = \frac{w_{uv}}{\sum_{x} w_{ux}}
$$
where *e*S is the restart distribution over the seeds. Every row has an estimate *p* and a residual *r*, with *r* = *e*S at the start, and pushing a row *u* does
$$
p(u) \mathrel{+}= \alpha\, r(u), \qquad r(v) \mathrel{+}= (1 - \alpha)\, r(u)\, W_{uv}\ \ \forall v, \qquad r(u) \leftarrow 0
$$
while some *r*(*u*) ≥ ε·deg(*u*). Each estimate is then within ε·deg(*u*) of π(*u*), and the work is bounded by 1/(αε) pushes whatever the graph's size. A row is queued only once its residual reaches ε, the least any threshold can be. Rows that merely received a little mass are never resolved, and resolving them had been most of the original cost.
The estimates add up to the share of the walk that has settled, Σ *p*; the rest is residuals no push spread. A fixed ε stops the walk at the seeds when their neighbours have many edges, since ε·deg(*u*) is then far above the residual a neighbour gets: from a user of the tests' user-item graph, whose 30 items have at least 300 edges each, ε = 10⁻⁴ settles the user's 15% and ranks no item. Without `eps` the walk starts at 10⁻⁴ and, while Σ *p* < ½, halves ε and pushes on from the residuals it has (an estimate only grows, so the walk at the lower ε continues the one at the higher), for at most 100,000 pushes; on that graph it stops at 3.1·10⁻⁶ with 72% settled, after 9,078 pushes. A walk that ends with Σ *p* < ½, at a given `eps` or out of pushes, reports `ppr_unsettled` in its stats.
## Speed
Two graphs, each queried from 200 random seeds on a warm cache, on one thread of an Apple M2 MacBook Air, through SQL (parsing and planning included; `COUNT(*)`, so that no rows are fetched):
- **arXiv:** 168,343 papers (ogbn-arxiv, less 1,000 held out) with 1,148,979 citations, in two segments.
- **Synthetic:** a power-law graph of 1,000,000 rows and 9,998,469 edges, in four segments. Row *i* links to 10 earlier rows, each the target of a random earlier edge with probability ½ and a uniform earlier row otherwise.
The baselines answer the same queries, and the benchmark checks that every count and path length agrees:
- **SQLite:** an edge table `(src, dst)` as a `WITHOUT ROWID` primary key, an index on `(dst, src)`, and recursive CTEs.
- **CSR:** the same traversal code on two in-memory arrays. This is the lower bound: no keys, no segments, no SQL.

*arXiv, 200 seeds per query. Source: `chloedb/results/graph/latency_arxiv.json`.*
On the million-row graph (`chloedb/results/graph/synthetic_1000000.json`; loaded in 2.7 s into a 307 MB file, 27 bytes per edge):
| query (200 seeds) | result | ChloeDB p50 / p95 ms | SQLite p50 / p95 ms | CSR p50 / p95 ms |
|---|---|---|---|---|
| `REACHABLE`, 1 hop out | 10 rows | 0.017 / 0.022 | 0.012 / 0.013 | 0.001 / 0.001 |
| `REACHABLE`, 2 hops out | 108 rows | 0.032 / 0.045 | 0.061 / 0.066 | 0.004 / 0.005 |
| `REACHABLE`, 3 hops out | 890 rows | 0.098 / 0.153 | 0.597 / 0.680 | 0.030 / 0.037 |
| `REACHABLE`, 1 hop in | 8 rows | 0.014 / 0.019 | 0.010 / 0.017 | 0.001 / 0.001 |
| `REACHABLE`, 2 hops both ways | 1,586 rows | 0.104 / 0.468 | 0.471 / 3.26 | 0.019 / 0.110 |
| `PATH` either way | 200 of 200 found | 0.079 / 0.145 | — | 0.025 / 0.071 |
| `ppr`, ε = 10−4 | 133 pushes | 3.49 / 4.13 | — | 0.66 / 0.80 |
| `ppr`, ε = 10−5 | 1,020 pushes | 25.6 / 30.1 | — | 5.47 / 6.32 |
**Against SQLite**, one-hop queries cost about the same, roughly 10–15 µs, mostly parsing and planning on both sides. From two hops on, the gap opens, and the tail is where it shows most: two hops both ways on arXiv touch 3,790 rows on average and up to tens of thousands, and their p95 is 1.6 ms in ChloeDB against 14.8 ms in SQLite. The recursive CTE re-expands rows reached at several depths and joins through a B-tree per row, where ChloeDB reads a CSR slice. Shortest paths and PageRank have no practical CTE form.
**Against the CSR**, ChloeDB pays two costs. About 10 µs of SQL per query dominates small traversals. Key resolution dominates large ones: PageRank takes 2.4 times the CSR's time on arXiv and 5.3 times on the million-row graph, because a target outside its own segment is a hash probe into each segment's primary-key index until found, a cache miss each. Three changes found by profiling on the Xeon VM that first ran these benchmarks cut PageRank on the million-row graph from 21.4 to 5.8 ms there (3.5 ms on the M2):
1. reverse groups by key, with the sources stored inline;
2. same-segment hints and a per-query memo;
3. queueing only rows that can pass the push threshold.
## Does the graph help search?
The rows here are nodes with text, vectors and edges at once. The question the engine cannot answer by itself is whether the edges add anything to a search that already has the text and the vectors, and whether edges made from the vectors (each row linked to its nearest rows) add anything.
**The task:** for a new paper, find the papers it cites from its title and abstract. This is citation recommendation, and the same shape as finding the records a new question depends on.
- 1,000 papers of OGB's test split (809 from 2019, 191 from 2020, each citing at least five papers) are held out of the table.
- Each held-out paper's title and abstract is the query. Its references in the table (15.3 on average) are the relevant rows.
- Vectors come from a static embedder (Model2Vec potion-retrieval-32M, 512 dimensions), the same one ChloeCtx uses.
- Each method returns 20 papers. Methods that start from vector seeds have one parameter, the number of seeds *S*, swept from 1 to 50. Papers with even ids choose *S* by nDCG@20 (516 queries) and papers with odd ids report it (484 queries), so no reported number was tuned on its own queries.
- Comparisons are paired over the same queries, with a 95% bootstrap interval and a two-sided sign-flip test.
$$
\mathrm{recall@}k = \frac{\lvert R_k \cap T \rvert}{\lvert T \rvert},
\qquad
\mathrm{nDCG@}k = \frac{\sum_{i \le k} \mathbb{1}[r_i \in T] / \log_2(i + 1)}{\sum_{i \le \min(k, \lvert T \rvert)} 1 / \log_2(i + 1)}
$$

*Source: `chloedb/results/graph/quality_stats.json`. Times are from the quality runs on the M2, after one untimed pass per method.*
**The graph doubles what vector search finds.** The best method is also the simplest: take the two papers nearest the query, follow their citations, and rank what they cite by similarity to the query. It reaches nDCG@20 0.253 against 0.123 for vector search (+0.130, 95% interval 0.111–0.149, p < 0.0001), 0.161 for BM25 and 0.160 for hybrid search, in 0.2 ms. Papers on the same topic cite the same work, and the nearest papers' reference lists are a better candidate set than the nearest papers themselves.
PageRank from the same seeds reaches 0.211 at its best (from one seed), below the plain one-hop expansion: on this graph the papers two or three hops away dilute the direct citations. Fusing PageRank with the vector ranking lowers it to 0.179, because the vector ranking's own top results are mostly not references. Fusing BM25, vectors and PageRank from hybrid seeds also reaches 0.211, at the cost of BM25 over long queries (48 ms).

**Fewer seeds are better.** With more seeds, the citations of papers less similar to the query crowd out those of the nearest ones. In a first version of the experiment the seeds themselves stayed in the candidate set; ranked by similarity they took the top places, and from 20 seeds on the "graph" method returned exactly the vector search's results. Every graph method above removes the seeds with `NOT REACHABLE(cites, seeds, hops => 0, min_hops => 0)`.
**A graph made of vectors adds nothing.** A `VECTOR` field can be traversed as a graph, each row's 10 most similar rows being its neighbours. On this task it returns what vector search already found when the seeds are kept (recall@20 0.112 against 0.111 at 10 seeds, on all queries), and is worse when they are removed (nDCG@20 0.079). A similarity graph only re-expresses the vector space, while citations carry information the text does not. Rows with vectors are useful as the way into a graph of real relations, not as a replacement for one. The implicit similarity graph stays in ChloeDB for exploratory queries, at 0.12 ms per hop of 10 neighbours.
## Edge tables
An [edge table](query-language.md#edge-tables) keeps a graph whose edges change one at a time, such as items seen together, apart from the rows it links: each of its rows is an edge, and adding one, changing its weight or deleting it writes that row alone. Each of its segments indexes its rows by the keys they link, in a section of its own (`edge_table`):
- the distinct keys its rows name, numbered in the order of their hashes, with the same radix directory as the primary-key index;
- each row's source and target as key numbers, and its weight when the segment was built;
- for each key, the rows that leave it and the rows that reach it, in row order.
A hop from row *u* looks up *u*'s key in each segment of the edge table, then reads the rows that leave it (or reach it, or both, by direction). For each row it checks that the row is live and reads its weight as it is now, in-place writes included, so a decayed or zeroed weight counts at once. The neighbour is the row's other end, a key number, which the walk resolves to a row of the walked table once per segment. Two shortcuts keep a long walk cheap without costing a short one anything. A segment's key numbers get a dense memo once the walk has resolved a thirty-second of them. A segment whose weights were written in place gets a flat copy of its weights once the walk has read a sixteenth as many as its in-place layers hold.
The section is smaller than an `EDGES` field's graph for the same edges, because a key is stored once per segment rather than once per edge. A hop costs more, because an `EDGES` field's out-edges sit with their row and most targets resolve through a same-segment hint. `chloedb-edges-bench` (in `chloedb-server`) measures both:
- **Writes.** It streams 300,000 click events of 10,000 users on 50,000 items (Zipf 1.0) through `/v1/stream`. Each event adds 1 to the weight of the edges between its item and the user's last five items, both ways, with `add` operations whose `doc` creates an edge's row on its first event. That is 9.0 edge operations per event and 1,896,100 edges in the end.
- **Walks.** `ppr` is seeded with a user's last 20 items, for 1,000 users, over the edge table and over an `EDGES` field of `items` holding the same edges and weights. Each query runs once to warm up, then once timed.
| | edge table | `EDGES` field |
|---|---|---|
| bytes per edge (index) | 20.6 | 33.2 |
| `ppr` p50 ms | 21.9 | 15.3 |
| `ppr` p90 ms | 30.1 | 26.6 |
| `ppr` p99 ms | 38.7 | 37.4 |
- **Walks cost about 1.4 times as much at the median, and about the same at p99.** Both rank the same 200 rows in the same order in all 1,000 walks. The edge table had 10 segments here. In a first run whose merges had left it 15, its p50 was 28.5 ms against 17.6, since a hop looks up its key in every segment.
- **Writes.** The events alone take 14.1 µs each (71,155 per second). With the edges, they take 190.2 µs (5,257 per second): 19.6 µs per edge operation, most of which create a row.
- **Weights as counts.** 54 of the 1,000 walks found nothing over either graph, when `ppr` pushed a row only once its residual reached `eps` times its weighted degree: at the default `eps` of 10⁻⁴, a seed whose edges' weights added up to more than 500 was never pushed. It now compares the residual with `eps` times the row's number of edges, so that scaling every weight alike (counts against frequencies) changes nothing; the weights still divide what a push spreads. Those numbers were measured before the change. A walk that stops at `max_pushes` says so in its plan line (`stopped at max_pushes`) and in the stats (`max_pushes_reached: true`).
*Cloud VM: 4 cores of an Intel Xeon at 2.10 GHz, 16.9 GB, Linux 6.18. Source: `chloedb-server/results/edges/vm.json`.*
## On a cluster
Graph queries run through a [coordinator](server.md#sharding-one-coordinator-many-shards) too, and answer as one database does. On a sharded cluster a row's edges point at rows that other shards hold, so no shard can walk its part alone. The coordinator walks instead:
1. It runs the walk one database runs (the same breadth-first walk, bidirectional search or forward push) over the rows it has read so far, and notes each row the walk needed and did not have: its out-edges (an `EDGES` field's JSON text), its in-edges, whether it exists, and whether it passes `through`.
2. It reads all of them in one round over every shard, keys in batches of 2,000, four reads at a time (each goes to every shard, so a round of many reads takes its turns beside other queries): `SELECT id, cites FROM papers WHERE id IN (...)` for out-edges, `WHERE REACHABLE(cites, (...), hops => 1, dir => 'in')` for in-edges (each shard answers that from its own rows' edges, by the reverse index), and `SELECT src, dst, w FROM cooc WHERE src IN (...)` (or `dst IN`) over an [edge table](#edge-tables).
3. It walks again from the start, until a walk misses nothing. That walk is the one database's walk.
4. Each shard is then given the walk's answer for its own rows (hops for `REACHABLE`, place for `PATH`, score for `ppr`, in the plan as `graph_given`), and the rest of the query runs as any query does: filters, `bm25`, vector search, `GROUP BY`, joins.
`REACHABLE` and `hops()` take about one round per hop, `PATH` one per hop from either end, and `ppr` one each time its pushes reach rows it has not read. The plan says `walked by the coordinator in N rounds`.
`ppr` over an edge table whose `src` and `dst` both reference the table walked (`src KEYWORD REFERENCES users`) counts a row's edges first (`SELECT src, COUNT(*) FROM replies WHERE src IN (...) GROUP BY src`) and reads them only to push the row, as one database reads a row's edges only as far as the push test needs. Most rows a walk meets are not pushed, and a well-connected row's list is long: on a reply graph of 887,000 people and 2.6 million edges over 4 shards (all on one 4-core Intel Xeon at 2.10 GHz), `ppr(replies, (24 of the busiest people), max_pushes => 2000)` read every list it met, 2.7 million edges in its fourth round, and was refused after 2.6 s; counting first it took 7 rounds and 0.7 s (0.25 to 0.5 s on one database), and queries beside it waited 110 ms at most where they had waited up to 850. The plan says `N rows' edges counted first`. The count takes `REFERENCES` at its word: an edge to a key that is no row counts toward its row's edges, where one database leaves it out, so keep such a table's references whole or give it no `REFERENCES`. An edge table that does not say so has each list read in full. Two answers can differ from one database's: `PATH` may pick another path of the same length, and `ppr` scores may differ in the last digits (by about 10⁻⁸ in the tests), since it pushes rows in the order it read them; with no `eps`, the `eps` it adapts to can differ too (the tests' top five agree within 10⁻³). A walk is refused past `max_nodes`, as on one database, and after 256 rounds. A walk over a `VECTOR` field (its nearest neighbours as edges) is refused on a cluster, since each shard's neighbour graph is its own.
On 20,000 rows of 5 links each, split over 3 shards with the coordinator in one process (gRPC on loopback, a 4-core Intel Xeon at 2.10 GHz, medians of 25 seeds), a 2-hop `REACHABLE` took 4.3 ms in 3 rounds against 0.23 ms on one database, 3 hops 6.3 ms in 4 rounds against 0.30 ms, `PATH` 9.0 ms against 0.20 ms, and `ppr` at `eps => 1e-4` 83 ms in 6 rounds against 1.8 ms; an application's own walk, a read of the frontier's links per hop with no check that its rows exist, took 2.1 ms for 2 hops (`cargo test --profile ci --test all graph_bench:: -- --ignored`, `chloedb-server/results/graph/cluster.json`). Between machines each round adds a network round trip.
A coordinator of one shard that holds every slot, with no move in progress, sends graph queries to that shard, which walks them itself. Joins along links (`JOIN papers b ON b.cites = a.id`) run on a cluster as well.
## Limits and next steps
- **One quality task, one embedder.** With a stronger embedder, vector search would score above 0.123 and the relative gain over it would likely shrink. The gains over BM25 (+57%) and hybrid search (+58%) are the more robust numbers.
- **Cross-segment hops cost lookups**, two to five times the in-memory CSR on these graphs. A snapshot-wide resolved CSR, rebuilt when the segment set changes, would close the gap for read-mostly tables; merging into fewer segments narrows it today.
- **No patterns.** There is no multi-hop pattern matching with a predicate per step; `through` and labels cover one constraint per traversal. SQL/PGQ's `MATCH` would be the standard syntax for more.
- **Unweighted paths.** Weights are used by PageRank only.
- **Walks across shards cost a round trip per hop** ([above](#on-a-cluster)), and a large `ppr` many rounds. A small edge table kept whole on every shard would let each shard walk it alone, in one round; that is not built yet.
- **ChloeCtx.** Its records have natural edges the store does not keep yet: a distilled note to the turn it came from, a superseded decision to its replacement, an error to the edit that fixed it. The arXiv result suggests the pattern to try (recall's best hits as seeds, then the records linked to them), but ChloeCtx's earlier study found that widening a hit to its neighbouring records gained little, so this needs its own measurement first.
The full report, with every table, is [ChloeDB graphs](https://chloetech-ai.github.io/chloedb/reports/graph.html). [Reproducing the results](../reproduce.md#chloedb-graphs) has the commands.
---
# Next items
What a user will open, watch or buy next, from what came after the same items before: counts kept in an ordinary table as events arrive, read with backoff from the last two items to the last one. They update with every event, explain themselves, and are the baseline that a learned sequence model has to beat.
## Counts in a table
Each row counts how often one item came right after one context: the last item, or the last two. The key is the context's items and then the next item, so with `cluster_by = 'id'` a context's rows sit together.
```sql
CREATE TABLE next (
id KEYWORD PRIMARY KEY, -- the context's items, then the next item
ctx KEYWORD NOT NULL, -- the last item, or the last two
nxt KEYWORD NOT NULL,
n FLOAT DEFAULT 0 -- how often (or a decayed weight)
) OPTIONS(cluster_by = 'id');
```
In Python, `chloedb.ngrams` writes the statement (`ngrams.create_table()`) or the schema (`ngrams.schema()`, for `chloedb.open` or `chloedb-server --schema`), the writes of an event and the read:
```python
import chloedb
from chloedb import ngrams
db = chloedb.open("next.chloedb", ngrams.schema())
# after each event: item "c" after the user's history [..., "a", "b"]
db.write(ngrams.ops(["a", "b"], "c"))
chloedb.next_items(db, ["a", "b"], k=10) # [("c", 1.0), ...]
```
`ngrams.ops(history, item)` returns one `add` per order, each of which creates its row on the context's first event, so an event costs two writes; `order=3` also counts the last three items. They are the operations chloedb-server's `/v1/write` takes ([writes](server.md#writes)), so `Client.write` sends them and `Database.write` applies them in-process. Items are strings without the two separators the keys use (`\x1f` between a context's items, `\x1e` before the next item).
Counts can decay in place, so that recent behaviour weighs more: `UPDATE next SET n = n * 0.9` rewrites no row, and a row whose weight reaches 0 is no longer read.
## Reading with backoff
`next_items(db, history, k=10, order=2, backoff=0.4)` scores each item by stupid backoff ([Brants et al., 2007](https://aclanthology.org/D07-1090/)): an item seen after the last two items scores its share of that context's weight; one seen only after the last item scores its share there times 0.4; a pair never seen backs off the same way. It returns `(item, score)` pairs, best first, ties by item.
The answer is the same as scoring every item of both contexts, but it reads less. Per context it runs a sum and then reads rows best first, a page at a time, and stops at the first row that cannot reach the top `k`. Then it checks that the items it takes from the last item's context have no row in the pair's context, by their keys. Over a server it is the same SQL, which any language can run:
```sql
SELECT SUM(n) FROM next WHERE ctx = :c AND n > 0;
SELECT nxt, n FROM next WHERE ctx = :c AND n > 0 ORDER BY n DESC, id LIMIT 64 OFFSET 0; -- ties by key: by item
SELECT nxt FROM next WHERE id IN (...) AND n > 0; -- the candidates' keys under the longer context
```
## Measured
On Amazon Beauty (22,363 users' reviews of 12,101 products in time order, the 5-core set sequential recommenders report on), each user's last item predicted from the items before it, ranked among all items, with the counts in-process on one thread of a 4-core cloud VM (Intel Xeon @ 2.10GHz):
| counts from | order | Recall@10 | NDCG@10 | p50 ms | p99 ms |
|---|---:|---:|---:|---:|---:|
| every transition before each user's last item | 1 | 0.0688 | 0.0459 | 0.57 | 1.46 |
| | 2 | 0.0694 | 0.0450 | 0.64 | 1.69 |
| only those before the last two, as SASRec trains | 1 | 0.0607 | 0.0404 | 0.49 | 1.23 |
| | 2 | 0.0613 | 0.0398 | 0.57 | 1.38 |
SASRec's published numbers on the same split are 0.0605 and 0.0318 (as [TIGER](https://arxiv.org/abs/2305.05065) reports them, from P5), so counted the way SASRec trains, counts match its recall and beat its NDCG: a strong baseline on this data. Two caveats: 43.5% of users wrote their last two reviews on the same day, which the usual preprocessing leaves in product order and which favours counted transitions; and with under nine reviews per user, the pair's context adds little over the last item's (order 3 adds nothing). Answers were the same as scoring every item for the first 2,000 users. Fewer than 10 scored items were filled with the most frequent ones. Script and results: [`results/sequence/ngrams_beauty.py` and `ngrams-beauty.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence).
A sequence model ([`encode()`](query-language.md#sequence-models-encodemodel-history)) trained on the same split, reading items only, has 0.0662 and 0.0406 ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence)), at 0.6 ms a query.
On Beauty, Sports and Toys, the walk of the next section ranks above both that model and a generative decoder over [semantic IDs](server.md#semantic-ids), and `rrf` of the model's scores and the walk's ranks above the walk: on Beauty, Recall@10 0.0834 and NDCG@10 0.0511, and Recall@10 0.0855 with the decoder's answer added ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/generative)).
## Several steps ahead
Counts predict the next item. For items further ahead, or for "seen together", the same events can feed an [edge table](query-language.md#edge-tables), whose edges are directed: adding 1/*g* to the edge from the item *g* steps back to the new one records what comes after what, and `ppr(cooc, :x, dir => 'out')` walks forward from the last items. `dir => 'both'`, `ppr`'s default, reads the same edges as seen together.
```sql
SELECT id FROM items
ORDER BY ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 5), dir => 'out', eps => 1e-6) DESC
LIMIT 20;
```
A walk runs on one database: a coordinator refuses `ppr` and the other graph queries ([graphs on a cluster](graphs.md#on-a-cluster)), while the counts above run anywhere.
Personalized PageRank pushes a row only while its share of the walk is at least `eps` times its number of edges. Without `eps`, the walk starts at 1e-4 and lowers it until half of the walk has settled, so seeds whose neighbours have thousands of edges still reach rows past them ([how far `ppr` walks](query-language.md#how-far-ppr-walks)); a given `eps`, as above, walks exactly that far, and a walk that stopped near its seeds says so in its stats (`ppr_unsettled`).
## Kept for you: `CREATE RECOMMENDER`
`CREATE RECOMMENDER shop ON events(usr, item, ts) ITEMS items(emb)` keeps the counts of order 1 and items seen together from the writes of an events table, and `ORDER BY recommend('shop', :u)` fuses them with the similarity of the user's recent items and with popularity, leaving out the user's recent items (the last `history` of them), not every item the user has had ([recommenders](query-language.md#recommenders-create-recommender-and-recommend)). To leave out everything the user has an event for, filter it: `SELECT id FROM items WHERE id NOT IN (SELECT item FROM events WHERE usr = :u) ORDER BY recommend('shop', :u, k => 500) DESC LIMIT 10`. Events keep feeding the counts as they are written without slowing the calls, and `optimize()` (`POST /v1/admin/optimize` on chloedb-server) merges what they wrote. It runs on one database, and through a coordinator when the events table is placed by its user column ([on a cluster](cluster-limits.md#graphs-and-recommenders)); the tables of this page work on any cluster.
## Which to use
Counts are exact and live: an event changes the next answer, and each suggestion is explained by a count. They know only the last one or two items and nothing about a context never seen, where they fall back to the last item alone. A walk over directed edges reaches several steps ahead and related items, at five writes per event. Learned sequence models, which read long histories and combine what they have not seen together, are the next step; these counts are the baseline they have to beat.
---
# Slices: search on the device, the server as fallback
A slice is a copy of the rows of a table near a device's user, which the device searches itself: near in space (a geo slice, for "near me" search) or near in meaning ([a vector slice](#vector-slices-more-like-this-on-the-device), for recommendations and "more like this"). chloedb-server builds a geo slice from a table with a text field and a latitude and longitude: a manifest (the schema, a grid of square tiles, the text field's statistics) and one file of rows per tile. An app fetches the manifest and the tiles around its user, and searches them with the server's statistics, so every place it holds scores exactly as on the server. When it can prove that its answer is the server's, nothing leaves the device; otherwise it sends the same query to the server. Each answer says where it was answered and why.
## When an answer comes from the device
The server ranks by `bm25(text, q) / (1 + d² / d0²)`, where `d` is the distance to the user and `d0` the distance at which a place counts half. A place the device does not hold is at least `e` away, the distance to the nearest tile it lacks, so it scores at most the sum of the query words' best scores (in the manifest) divided by `1 + e² / d0²`. When the k-th score on the device reaches that, the device's top k is the server's. Each answer's `why` is one of:
| why | where | what it means |
|---|---|---|
| `proved` | device | the k-th local score beats the most a place not held could score |
| `no_match` | device | no place in the table has a word of the search |
| `short` | server | the device holds fewer than k matching places |
| `bound` | server | a place beyond the tiles held could have scored higher |
| `stale` | server | the table changed since the slice was built |
So a device answers short searches for common things near its user (pizza, a pharmacy) itself, and asks the server for rare things, for large k, and for wide `d0`.
## Turn it on
Slices exist only on a server started with `--slices DIR`. Build one from the command center (**Data → Slices → Build a slice**) or over HTTP:
```bash
chloedb-server --db places.chloedb --slices ./slices --slices-rebuild-s 300 &
curl -X POST localhost:7700/v1/admin/slices -H 'content-type: application/json' \
-d '{"text": "body", "lat": "lat", "lon": "lon", "lat0": 40.7, "lon0": -73.98, "tile_m": 1000}'
```
`lat0`, `lon0` are the grid's origin (the middle of the area, usually), `tile_m` the side of a tile in metres. `POST /v1/admin/slices` with `{"table": "places"}` alone rebuilds a slice as it was built, and `--slices-rebuild-s N` rebuilds every stale slice each N seconds. Without a slice the helpers below fail to open, and an app sends its searches to the server as it would without them.
## Fresh or stale
Before a device trusts its slice it asks `GET /v1/slices/
/status` (every 30 seconds by default), which answers the slice's version and whether the table changed since the build. A device fetches a slice of another version, and while the table has changed it sends every search to the server (`max_lag` lets it keep answering for a while). A slice is a snapshot: a row written after the build is not on any device until the next build.
## From Python
```python
import chloedb
near = chloedb.nearby("http://127.0.0.1:7700", "places", "./slice")
near.move_to(40.7484, -73.9857) # fetches the tiles around the user
r = near.search("pizza", k=10, d0=1000)
print(r.where, r.why) # "device" or "server", and why
for row in r:
print(row["name"])
near.close()
```
`chloedb.nearby(url, table, dir, token=None, reach=2, status_every=30, max_lag=0, report_every=20)`: `reach` is how many tiles each way it holds (2 is a 5 by 5 square), `dir` a cache it may delete. The result is a `Result` with `where`, `why`, `bound`, `edge_m`, `device_ms`, `server_ms`, and `ask`, the request that asks the server.
## From JavaScript
```js
import { openNearby } from "chloedb";
const near = await openNearby("http://127.0.0.1:7700", "places", "./slice");
await near.moveTo(40.7484, -73.9857);
const r = await near.search("pizza", { k: 10, d0: 1000 });
console.log(r.where, r.why);
for (const row of r) console.log(row.name);
await near.close();
```
It runs where the native addon does (Node, Bun, Deno), with the same options as Python's in camel case (`statusEvery` and `maxLag` in milliseconds).
## Vector slices: "more like this" on the device
A slice can also cut a table by meaning: its VECTOR field into k-means clusters, each a file of rows. A device holds the clusters nearest its user's taste (a vector, such as the user's history summed) and answers `similarity` searches itself (recommendations for the user, tracks like the one playing) when it can prove that no row it lacks could beat its k-th.
```bash
curl -X POST localhost:7700/v1/admin/slices -H 'content-type: application/json' -d '{"table": "tracks", "vector": "emb"}'
```
`clusters` sets their number (about the square root of the rows by default, at most 4,096 then). The server's search is exact (`similarity(emb, :v, strategy => 'flat', rerank => )` re-scores every row), so a device's proved answer is the server's to the last bit.
The manifest holds each cluster's centre, radius, angular radius and longest and shortest vector, from which a device bounds the most a row of a cluster it lacks could score. In many dimensions that bound is loose (a cluster's rows point every way from its centre, so none comes near the worst case), and on its own it proves few answers. So the slice also holds `codes.bin.gz`: every row's vector as one byte a dimension (64 bytes a row for 64 dimensions, a sixteenth of the rows' JSON), which bounds each row within half a step a dimension. A device that fetched the codes proves most searches near its user's taste, and when it cannot, the answer names the few clusters (`need`) whose rows could still beat its k-th. Once it holds them its answer is proved, so the helpers fetch them when they come to at most `refine` bytes (2 MB by default) and answer on the device.
```python
tracks = chloedb.nearby("http://127.0.0.1:7700", "tracks", "./tracks")
tracks.focus(taste, rows=20_000) # the clusters nearest the taste, up to 20,000 rows
r = tracks.similar(taste, k=10) # or any vector
print(r.where, r.why, r.fetched) # "device", "proved", clusters it fetched to prove it
```
```js
const tracks = await openNearby("http://127.0.0.1:7700", "tracks", "./tracks");
await tracks.focus(taste, { rows: 20000 });
const r = await tracks.similar(taste, { k: 10 });
```
`focus` keeps the clusters that fit in `rows` rows and drops those that fall beyond half as many again, so a taste that drifts does not fetch and drop the same clusters over and over. A cluster dropped is deleted from the device's database, and once the rows deleted since the last time outnumber the rows held (and are 1,000 or more), the database is compacted, so the folder stays within about twice what the device holds however far the taste drifts; a geo slice's tiles go the same way. `codes=False` (`codes: false`) skips the codes; `{"codes": false}` builds a slice without them.
On Yambda's 629,298 tracks (64-dimension vectors, 4,599 users, measured in a cloud container; [the replay](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/slices#vector-slices-on-yambda-proving-similarity-search-on-the-device) has every number), with 4,096 clusters and 20,000 tracks on the device:
| search | proved by the clusters' centres | proved with the codes | proved after fetching what the codes name |
|---|---:|---:|---:|
| recommend for me, top 10 | 4.5% | 94.9% | 100%, a median 64 KB when it fetches |
| recommend for me, top 100 | 2.1% | 61.3% | 100%, a median 157 KB |
| more like the last track, top 10 | 4.6% | 54.6% | 100%, a median 340 KB |
The codes are 30 bytes a track gzipped (19 MB for the catalogue). No proved answer was wrong. More clusters (smaller ones) make each fetch smaller and the manifest larger: 4,096 clusters of this catalogue make a 3.6 MB manifest, the default 793 a 0.7 MB one with fetches about seven times as large.
## What the server sees
Each helper reports its counts every 20 searches (`POST /v1/slices/
/usage`: searches, why, time on the device and on the server), and the server counts the manifests and tiles it serves. The command center's **Slices** view shows them since the server started: the share answered on the device, the devices, a map of the tiles by rows, size or downloads, the reasons searches went to the server, the last hour by minute, the busiest tiles, and the slice's version with Rebuild and Delete.

For a vector slice the map is a grid of its clusters, busiest first:

| route | what |
|---|---|
| `POST /v1/admin/slices` | builds a geo slice (`text`, `lat`, `lon`, `lat0`, `lon0`) or a vector slice (`vector`, `clusters`, `codes`), or with `{table}` alone rebuilds one as it was built |
| `GET /v1/admin/slices` | every slice, with its counts, and the tables that could have one |
| `GET`, `DELETE /v1/admin/slices/
` | a slice's tiles and last hour; deletes it |
| `GET /v1/slices/
/manifest.json`, `/tiles/_.jsonl.gz`, `/codes.bin.gz` | the files a device fetches (read scope); a vector slice's tile `x` is its cluster |
| `GET /v1/slices/
/usage` | a device's counts |
`chloedb-slice` (in the chloedb crate) writes the same files from a database file without a server, for any web server or CDN to serve. `chloedb-server/demo/nearby` is a demo over New York's places.
---
# ChloeDB: design
ChloeDB is to search what SQLite is to relational data: a library that keeps a whole database in one file, needs no server or configuration, gives ACID transactions, and is queried with SQL. Every table is indexed for full text (posting lists), structured columns (a columnar forward index) and vectors, rows can hold graph edges to other rows, and a cost-based planner combines all of it in one statement.
This page is the design: the file format, transactions, every index and the planner. To use ChloeDB, start with the [README](../../README.md) or [Build an app](build-an-app.md).
## Goals
- **Embedded and single-file.** One `.chloedb` file plus a `-wal` sidecar, like SQLite in WAL mode. Opening a database maps the file and loads nothing eagerly, so databases larger than RAM work and a cold open costs the same whatever the size.
- **ACID with snapshot isolation.** One writer, any number of readers. Readers never block and always see a consistent snapshot; a crash at any point leaves the last committed state. Threads that write at once take turns, and those that wait share the next commit.
- **SQL with search extensions.** `SELECT … WHERE … ORDER BY … LIMIT`, `GROUP BY` for facets, plus `MATCH` (boolean full text), `bm25()`, `similarity()` and `distance()` (vectors and learned sparse weights), `rrf()`, weighted sums and products (fusion and boosts), `decay()` (closeness to a value or a time) and graph traversal, and `INSERT`, `UPDATE` and `DELETE`. The [query language](query-language.md) page is the reference.
- **Index families, freely combined.** Full text (BM25, boolean and phrase queries), structured fields (equality, `IN`, ranges, facets) and vectors (approximate and exact nearest neighbours), in any combination: filtered vector search, filtered BM25, hybrid ranking, facets over any result.
- **Graphs over the same rows.** A row can hold typed, weighted edges to other rows. Traversals, shortest paths and personalized PageRank run in the same statement as everything else ([Graphs](graphs.md)).
- **Disk-aware.** Every structure is read in place through `mmap`, with no deserialisation, and laid out so that a query's I/O is proportional to its work.
One process writes a database at a time; other processes can [read it while it is written](#readers-in-other-processes). Joins across tables, and sharding and replication in [chloedb-server](server.md), came later; [current limits](#where-it-fits) has where they stand.
## Architecture

A statement goes through four stages. The binder turns SQL into a predicate tree and a scorer; the planner picks, per segment and from exact statistics, how to evaluate each part; operators run against zero-copy views of the segment's sections; per-segment results are merged.
```mermaid
flowchart LR
SQL["SQL text"] --> B["parser + binder (sqlparser, MATCH grammar)"]
B --> L["bound query predicate tree · scorer · projection"]
G["graph traversal (across segments, first)"] -.-> P
L --> P["cost-based planner per segment"]
ST["statistics df · histograms · list sizes · ANN params"] --> P
P --> T["text operators MaxScore · Block-Max WAND · boolean"]
P --> S["structured operators range scan · postings · facets"]
P --> V["vector operators flat · IVF · HNSW · pre / in / post-filter"]
T --> F["fusion and output RRF · weighted · top-k merge"]
S --> F
V --> F
```
## Storage engine
### Immutable segments, not a B-tree
SQLite updates B-trees in place. Compressed posting lists, bit-packed columns and vector graphs do not survive that: inserting one docID into a compressed partition means re-encoding it, and the best encodings are chosen per whole list. SQLite's own FTS5 already stores its index as immutable segments merged in the background, as do Lucene, Tantivy and PISA. ChloeDB uses that log-structured design for the whole table: every index lives in immutable segments, writes go to a WAL and an in-memory memtable, and segments are merged in the background.
### One file

Pages are 4 KiB. Pages 0 and 1 are two meta slots (magic, format version, transaction id, manifest and freelist locations, page count, CRC32); the rest are extents, runs of pages holding segment data, manifests, delete sets and freelists. Segments are written once, never modified, and freed only when no snapshot references them.
**Backups.** While a database is open, its rows since the last flush are in the `-wal` sidecar only, so a copy of the file alone misses them, and copying both while it is written is not consistent either. The safe ways: `Database::checkpoint(dest)` (Python `db.checkpoint(dest)`, chloedb-server `POST /v1/admin/checkpoint`) writes a consistent copy while the database is in use, checking every segment against its checksum first, so that damage is never copied into a backup under a fresh checksum, and checking the copy before naming it; and a clean close (`Db::close`, `close()` in the bindings) flushes the rows in memory into the file and leaves the log empty, so the file alone is then a complete copy, as `Database::flush` makes it at any moment until the next write.
The file is read through one `mmap`. Sections read at random positions (the HNSW graph and its codes, float32 vectors for re-ranking, dictionaries, the doc store, the key index) are advised `MADV_RANDOM`, so a cold page fault reads one page instead of the kernel's read-around of up to 32. Sections read a run at a time (postings, document lengths, columns, IVF clusters) keep read-ahead. Readers open lazily per field, so a query touches only the headers of the fields it uses.
### Commits by shadow paging
```mermaid
sequenceDiagram
participant W as writer
participant F as data extents
participant M as meta slot (txn+1) mod 2
W->>F: write segment data, delete sets, manifest, freelist (free pages or file end)
W->>F: fsync
W->>M: new txn id, manifest location, checksum
W->>M: fsync: committed
Note over F,M: recovery takes the valid slot with the larger txn id
```
A torn meta write fails its checksum and the other slot still names the previous, fully written state. Nothing reachable from a valid meta slot is ever overwritten (the LMDB discipline), so there is no rollback journal. When the newest version itself is damaged (its meta slot, manifest or free list fails its checksum, a segment it names does not open, or the file is shorter than it says), the version in the other slot is still whole, but falling back to it is right only if the write-ahead log still holds what the newer version had flushed: otherwise the log, emptied after that flush, would be replayed onto a version it does not follow, and acknowledged rows would be gone without a word. Opening falls back only when the log's transactions show it covers the gap (the newer version flushed nothing, the log still holds a transaction it flushed, or it holds the first transaction after the older version's), says so in `Database::damaged`, and the next commit overwrites the damaged slot. Otherwise it fails, naming the file, what is damaged and the way out, and changes nothing (it no longer cuts the newer version's pages off the file first): restore a backup, or open with `DbOptions::recover` (Python `recover=True`, chloedb-server `--recover`), which copies the file to `.damaged-