LatticeDB
Embedded property graph with native vector, full-text, and durable event primitives.
LatticeDB is a single-file local database for connected, semantic, and textual data. It lets applications traverse relationships, run HNSW vector similarity, run BM25 full-text search, and consume durable graph/application events from the same file.
- One file. Your entire database is a single portable file. No server, no configuration.
- One query layer. Graph traversal, HNSW vector similarity, and BM25 full-text — in one query.
- One event log. Durable named streams and the built-in graph changefeed share the same transaction/WAL path as graph writes.
- Fast in process. 0.2 us reads by node id and 2.3 us Cypher lookups through the C API; top-10 vector search over 100K vectors in 0.12 ms. See Benchmarks.
// Find chunks similar to a query, traverse to their document, then to the author
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query_vector < 0.3
AND doc.content @@ "neural networks"
RETURN doc.title, chunk.text, author.name
ORDER BY chunk.embedding <=> $query_vector
LIMIT 10
Features
Graph
- Nodes and edges with labels and arbitrary properties
- Multi-hop traversal, variable-length paths (
*1..3) - ACID transactions with snapshot isolation
- Property indexes on nodes and relationships, for equality, ranges, prefixes and sorting
- MERGE, WITH, UNWIND, aggregations (
count,sum,avg,min,max,collect)
Vector Search
- HNSW approximate nearest neighbor, with
ef_searchtunable per query - Built-in hash embeddings or HTTP client for Ollama/OpenAI
- Batch insert for bulk loading
Full-Text Search
- BM25-ranked inverted index; words split by Unicode, lowercased and accent-folded, with English stop words dropped
- One query language everywhere:
OR,-exclusions,"phrases",prefix*andfuzzy~ - Fuzzy search with configurable Levenshtein distance
Cypher Query Language
- MATCH, OPTIONAL MATCH, WHERE, RETURN, CREATE, DELETE, SET, REMOVE, FOREACH
- ORDER BY, LIMIT, SKIP, DETACH DELETE, UNION, CASE,
CALL { }subqueries - Named paths,
shortestPath, list and pattern comprehensions,EXISTS,COUNTandCOLLECTsubqueries - Vector distance operator:
<=> - Full-text search operator:
@@ - Parameters:
$name
Operations
- Single-file storage with write-ahead log for crash recovery
- Durable streams and semantic graph changefeeds, with a retention policy for the changefeed
- Import and export JSON, JSONL, CSV and RDF (Turtle, N-Triples)
- Zero configuration — open a file and start working
- Clean C API; Python, TypeScript, Go, and Java bindings wrap it
Use Cases
- RAG Systems — Vector search finds relevant chunks, graph traversal gathers context
- Knowledge Graphs — Linked notes and documents with semantic search
- AI Agents — Persistent memory with relationship awareness
- Local Development — Lightweight alternative to Neo4j or Weaviate for prototyping
Getting Started
Head to the Installation page to install LatticeDB, then follow the Quick Start guide to build your first knowledge graph.
Installation
CLI
On Linux and macOS:
curl -fsSL https://raw.githubusercontent.com/jeffhajewski/latticedb/main/dist/install.sh | bash
The script installs the lattice binary and the shared library. It does not run on
Windows; Windows users take the .zip archive from the
GitHub releases page, which
holds lattice.exe and lattice.dll.
Python
pip install latticedb
Requires Python 3.9+ and NumPy. The published wheels bundle the native library for Linux (x86_64, aarch64), macOS (x86_64, arm64) and Windows (x64, ARM64), so nothing else needs installing.
TypeScript / Node.js
npm install @hajewski/latticedb
Requires Node.js 18+. The published package bundles the native library for Linux
(x64, arm64), macOS (x64, arm64) and Windows (x64, arm64). Electron apps must unpack
it from app.asar; see the
TypeScript README.
Go and Java
The Go binding needs the shared library, header and pkg-config file installed; see Go. The Java binding is built from source; see Java. Both are tested on Linux and macOS only.
Platforms
CI runs the core test suites and the Python and TypeScript binding tests on Linux, macOS and Windows x64. Windows ARM64 is built but not run.
Building from Source
LatticeDB is written in Zig and needs no other dependencies (it links the C library).
git clone https://github.com/jeffhajewski/latticedb.git
cd latticedb
zig build # build everything
zig build test # run tests
zig build -Doptimize=ReleaseFast # optimized build
Build the shared library for language bindings:
zig build shared
This produces liblattice.dylib (macOS) or liblattice.so (Linux) in
zig-out/lib, or lattice.dll in zig-out/bin (Windows).
See Building from Source for more details.
Quick Start
This guide walks through creating a small knowledge graph with documents and authors, storing embeddings, indexing text, and querying across all three search modes.
The fastest thing that works
Before the full example, here is the smallest one. Pass :memory: as the path and
you get a real database with nothing to create and nothing to clean up:
from latticedb import Database
with Database(":memory:") as db:
db.query("CREATE (a:Person {name: 'Alice'})")
print(db.query("MATCH (p:Person) RETURN p.name"))
Everything works the same as a database on disk — transactions, indexes, vector and text search — it just disappears when you close it. It is the easiest way to try a query, and it is what tests usually want. See In-Memory Databases.
Swap ":memory:" for a filename when you want to keep the results.
Python
from latticedb import Database
from latticedb.embedding import hash_embed
with Database("knowledge.db", create=True, enable_vectors=True, vector_dimensions=128) as db:
# --- Build the graph ---
db.create_node_fts_index("Chunk", "text")
with db.write() as txn:
# Create authors
alice = txn.create_node(labels=["Person"], properties={"name": "Alice", "field": "ML"})
bob = txn.create_node(labels=["Person"], properties={"name": "Bob", "field": "Systems"})
txn.create_edge(alice.id, bob.id, "COLLABORATES_WITH")
# Create documents with chunks
for title, text, author in [
("Attention Is All You Need", "The transformer architecture uses self-attention...", alice),
("Scaling Laws for LLMs", "We find that model performance scales predictably...", alice),
("Log-Structured Merge Trees", "LSM trees optimize write-heavy workloads...", bob),
]:
doc = txn.create_node(labels=["Document"], properties={"title": title})
chunk = txn.create_node(labels=["Chunk"], properties={"text": text})
# The chunk's text is indexed because Chunk.text was declared above.
txn.set_vector(chunk.id, "embedding", hash_embed(text, dimensions=128))
txn.create_edge(chunk.id, doc.id, "PART_OF")
txn.create_edge(doc.id, author.id, "AUTHORED_BY")
txn.commit()
# --- Query: vector search + text match + graph traversal ---
results = db.query("""
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query < 0.5
RETURN doc.title, chunk.text, author.name
ORDER BY chunk.embedding <=> $query
LIMIT 5
""", parameters={"query": hash_embed("transformer attention mechanism", dimensions=128)})
for row in results:
print(f"{row['doc.title']} by {row['author.name']}")
# --- Full-text search ---
for r in db.fts_search("Chunk", "text", "self-attention transformer"):
print(f"Node {r.node_id}: score={r.score:.4f}")
# --- Aggregations ---
stats = db.query("""
MATCH (doc:Document)-[:AUTHORED_BY]->(p:Person)
RETURN p.name, count(doc) AS papers
ORDER BY papers DESC
""")
for row in stats:
print(f"{row['p.name']}: {row['papers']} papers")
TypeScript
import { Database } from "@hajewski/latticedb";
import { hashEmbed } from "@hajewski/latticedb/embedding";
const db = new Database("knowledge.db", {
create: true,
enableVectors: true,
vectorDimensions: 128,
});
await db.open();
// Build a graph
await db.write(async (txn) => {
const alice = await txn.createNode({
labels: ["Person"],
properties: { name: "Alice", field: "ML" },
});
const doc = await txn.createNode({
labels: ["Document"],
properties: { title: "Attention Is All You Need" },
});
const chunk = await txn.createNode({
labels: ["Chunk"],
properties: { text: "The transformer architecture uses self-attention..." },
});
await txn.setVector(chunk.id, "embedding", hashEmbed("transformer self-attention", 128));
await txn.createEdge(chunk.id, doc.id, "PART_OF");
await txn.createEdge(doc.id, alice.id, "AUTHORED_BY");
});
// Query across vector search + graph traversal
const results = await db.query(
`MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query < 0.5
RETURN doc.title, chunk.text, author.name
ORDER BY chunk.embedding <=> $query
LIMIT 5`,
{ query: hashEmbed("attention mechanism", 128) }
);
for (const row of results.rows) {
console.log(`${row["doc.title"]} by ${row["author.name"]}`);
}
await db.close();
Next Steps
- Core Concepts — understand the data model
- Cypher Overview — learn the query language
- Data Export — export to JSON, JSONL, CSV, or DOT
- Building a RAG System — end-to-end tutorial
The lattice Command
Installing LatticeDB gives you a lattice command. It is the fastest way to create a
database, poke around in one, and move data in and out — no code required.
Every command follows the same shape:
lattice <command> [options] <path>
The path is the database file. Almost every command needs one; version, help, and
update are the exceptions.
If you ever forget what something does, ask it:
lattice help # everything at a glance
lattice export --help # detail for one command
A quick tour
Here is the whole thing in five commands. Create a database, put something in it, and look at what you have.
lattice create social.lattice
lattice exec social.lattice --query="CREATE (a:Person {name: 'Alice', age: 30})"
lattice exec social.lattice --query="CREATE (b:Person {name: 'Bob', age: 41})"
lattice exec social.lattice --query="MATCH (a:Person {name:'Alice'}), (b:Person {name:'Bob'}) CREATE (a)-[:KNOWS {since: 2020}]->(b)"
lattice count social.lattice
That last command prints:
┌───────────┬────────────┐
│ Type │ Count │
├───────────┼────────────┤
│ Nodes │ 2 │
│ Edges │ 1 │
│ Labels │ 1 │
│ EdgeTypes │ 1 │
└───────────┴────────────┘
Creating a database
create makes a new database file. On its own it gives you a graph with full-text
search turned on:
lattice create social.lattice
Created database: social.lattice
Full-text search enabled
If you plan to store embeddings, turn the vector index on at creation time and say how many dimensions your vectors have. This is decided up front, because the index is built into the file and the file records how it was built:
lattice create embeddings.lattice --enable-vector --vector-dims=1536
Created database: embeddings.lattice
Vector index enabled (dimensions: 1536, metric: cosine)
Full-text search enabled
| Option | What it does |
|---|---|
--enable-vector | Turn on the vector index for similarity search |
--vector-dims=<n> | How many numbers are in each vector, 1 to 4096 (default 128) |
--vector-metric=<m> | How distance is measured: cosine (default), euclidean, or dot_product (the negated dot product) |
--vector-m=<n> | HNSW connections per node, 2 to 32 (default 16) |
--vector-ef-construction=<n> | HNSW candidate list size while building, 1 to 4096 (default 200). These four options need --enable-vector: without it the command is refused rather than creating a database with no index |
--enable-fts | Turn on full-text search — already the default |
--no-fts | Leave full-text search out |
--cache-size=<mb> | How much memory to keep pages in, in MB (default 64) |
--page-size=<bytes> | Page size, 4096 to 65535 (default 4096) |
Pick --vector-dims to match whatever produces your embeddings. OpenAI's
text-embedding-3-small gives you 1536 numbers per vector, so that is the number you
would use. The metric and the two HNSW settings cannot be changed later either; to
change them, create a new database with the ones you want and import an export of
the old one into it. (A JSON import into a database with no vector index, given
--enable-vector, copies the original's settings instead.)
Opening a database that stores vectors
The database file records its vector index: dimensions, metric and build settings.
Every command opens the index as it was created, with no vector options, including
export, dump and import, which carry node vectors, and the first command after
a crash, which replays the vector changes in the log.
A --vector-dims that contradicts the file is refused:
lattice count embeddings.lattice --enable-vector --vector-dims=4
Error: Failed to open database embeddings.lattice: its vector index has a different number of dimensions than --vector-dims gives. A database with a vector index opens with it as it was created; leave out --vector-dims.
The vector options of commands other than create are needed in two cases only.
--enable-vector --vector-dims=<n> on a database that has no vector index creates
one, for example to import a file that carries vectors into a database created
without them. And a database last written by LatticeDB 0.16.0 records no vector
settings: its dimensions are read from its vector pages, and in the rare case that
fails, a command that has to replay vector changes from its log stops and asks for
--enable-vector --vector-dims=<n> with the dimensions it was created with.
Running queries
There are two ways to run Cypher. Use exec for one query, and query when you want
to sit and explore.
One query at a time
lattice exec social.lattice --query="MATCH (p:Person) RETURN p.name, p.age"
You can keep a longer query in a file instead of fighting with shell quoting:
lattice exec social.lattice --file=report.cypher
When a query fails, the error says at which stage it failed, what went wrong and where, with a caret under the part of the query it is about, and the command exits with status 1:
lattice exec social.lattice --query="MATCH (p:Person) RETURN p.name, p.age / 0"
Error: Execution error (DivisionByZero) at 1:39: Division by zero: 30 / 0
1 | MATCH (p:Person) RETURN p.name, p.age / 0
| ^
A misspelt function is found before the query runs, whether or not any rows would reach it:
Error: Semantic error (unknown_function) at 1:25: Unknown function 'toUppr'
1 | MATCH (p:Person) RETURN toUppr(p.name)
| ^^^^^^
An interactive shell
lattice query social.lattice
This drops you into a prompt where you can type queries and see results immediately. It also understands a few commands of its own, all starting with a dot:
| Command | What it does |
|---|---|
.help | List these commands |
.labels | List every node label |
.types | List every edge type |
.schema | Show what the data looks like |
.format table|json|csv | Change how results are printed |
.timing on|off | Show how long each query took |
.exit or .quit | Leave |
Looking at what is in there
Four commands answer "what is actually in this database?".
count gives you the totals, as shown in the tour above.
labels and types list the node labels and edge types, with how many of each:
lattice labels social.lattice
┌────────┬────────────┐
│ Label │ Count │
├────────┼────────────┤
│ Person │ 2 │
└────────┴────────────┘
1 label(s)
schema puts both together. LatticeDB does not make you declare a schema up front, so
this is worked out by looking at the data that is actually there:
lattice schema social.lattice
Schema
══════
Node Labels:
(:Person) - 2 node(s)
Edge Types:
[:KNOWS] - 1 edge(s)
Total: 1 label(s), 1 edge type(s)
info describes the file rather than its contents — size, counts, which features
it was built with, and which releases can open it. Here for a database
with a vector index and two property indexes:
lattice info people.lattice
Database: people.lattice
─────────────────────────────
Size: 68 KB
Nodes: 2
Edges: 1
Format: v4
Min reader: v4, so 0.16.0 cannot open it (ordered property index, changefeed events)
Vector: enabled
Dimensions: 384
Metric: cosine
M: 16
ef_construction: 200
FTS: enabled
Changefeed: keep all, events 1..10
Index: :Person(age) ordered_dense
Index: [:KNOWS](since) ordered
Min reader is the oldest LatticeDB that can open the file, and, when 0.16.0
cannot, what keeps it out: changefeed events, ordered property index,
vector index settings (a metric other than cosine, or an M other than 16)
or full-text positions. Storing changefeed events is the usual reason, since
the database keeps them by default. A file that has none of these says v3
and still opens in 0.16.0
(Opening with 0.16.0).
Vector gives the index's settings, which are fixed when it is created.
Changefeed is the changefeed: the record of every
change, its retention policy and the events it holds. Here the two people and
the edge between them, with their labels and properties, took ten events.
Each Index line is a property index and how its keys are encoded. An index
created by LatticeDB 0.16.0 shows digest: it answers equality only until
compact --upgrade-indexes rebuilds it.
--format=json gives the same as one object, with the reasons as a list and
the indexes as objects:
{"path":"people.lattice","size_kb":68,"nodes":2,"edges":1,"format_version":4,"vector_enabled":true,"min_reader_version":4,"min_reader_reasons":["ordered property index","changefeed events"],"vector_dimensions":384,"vector_metric":"cosine","vector_m":16,"vector_ef_construction":200,"fts_enabled":true,"changefeed_retention":"all","changefeed_oldest_sequence":1,"changefeed_last_sequence":10,"property_indexes":[{"entity":"node","scope":"Person","property":"age","encoding":"ordered_dense"},{"entity":"relationship","scope":"KNOWS","property":"since","encoding":"ordered"}]}
--format=csv gives property,value rows with the same names, the reasons
joined by ; (min_reader_reasons,ordered property index;changefeed events)
and one property_index row per index (property_index,:Person(age) ordered_dense).
Moving data in and out
Importing
import reads JSON, JSONL or CSV, chosen by the file extension. It also reads
RDF in Turtle (.ttl) and N-Triples (.nt), which
RDF: Turtle and N-Triples describes:
lattice import social.lattice --file=people.json
Importing people.json into social.lattice...
Import complete
Nodes imported: 2
Edges imported: 1
JSON should have a nodes array and an edges array:
{
"nodes": [
{"id": "n1", "labels": ["Person"], "properties": {"name": "Carol", "age": 29}},
{"id": "n2", "labels": ["Person"], "properties": {"name": "Dan", "age": 35}}
],
"edges": [
{"source": "n1", "target": "n2", "type": "KNOWS", "properties": {"since": 2021}}
]
}
In JSON, id is a name local to the file: edges refer to nodes by it, and each
node gets a fresh ID in the database. A node can also carry a "vector" array,
which is stored as its embedding; that needs a database with a vector index. Into a
database without one, the import stops and asks for --enable-vector, which
creates the index with the dimensions, metric and HNSW settings an exported JSON
file records in its header; a file without them also needs --vector-dims=<n>.
Files that export writes
also have a "version" field and write some values in a tagged form; see
Data Export for the format.
JSONL is what export writes to a .jsonl file: one record per line, each a
node ("kind":"node") or an edge ("kind":"edge"), with edges naming nodes
from earlier lines.
CSV files are read as RFC 4180 describes: a quoted field can hold commas, line
breaks and doubled quotes (""). Columns are found by name in the header. A
nodes file has an _id column, _labels with the labels separated by ;, an
optional _vector, and a column per property:
_id,_labels,name,age
n1,"Person;Employee","Smith, Jr",30
n2,Person,"Ann ""The Hat"" Lee",41
An edges file has _source, _target and _type, and a column per property:
_source,_target,_type,since
n1,n2,KNOWS,2020
A property column holds plain text, read as an integer, a float, or else a
string. A column named <key>:json holds a value in the JSON export encoding
instead, which is how a list, a map, bytes or a string that looks like a number
gets through CSV; export writes every property column that way.
How an edges file names its nodes depends on how you import it. Give import
the --file value an export was given, and it imports <base>_nodes.csv and
<base>_edges.csv together, matching _source and _target against the nodes
file's _id values:
lattice import social.lattice --file=people.csv
Importing people_nodes.csv and people_edges.csv into social.lattice...
Import complete
Nodes imported: 2
Edges imported: 1
An edges file imported on its own names nodes by their numeric database IDs, and an ID that is not a node in the database is an error.
When a record is wrong
Without further options, import stops at the first record it cannot import and
says which one it was and why:
Error: Import failed at nodes[1]: its "labels" is not an array
Nothing was imported. Use --on-error=skip to import the records that are valid.
Records are named by where they are: nodes[1] and edges[0] in JSON, line 12
in JSONL and CSV, edges file line 4 when a CSV pair is imported together. A
record is imported whole or not at all: a property that cannot be read or
stored, a label or property of the wrong JSON type, or an edge whose endpoint
names no node fails the record.
A CSV file that cannot be read as CSV at all, such as one with a quote that is never closed or text after a field's closing quote, stops the import at the line where the problem starts:
Error: Import failed at line 2: a quoted field that starts here has no closing quote
Nothing was imported. Fix the file and import it again.
--on-error=skip cannot skip past such a fault, since the reader cannot tell where
the next record begins, so it stops the import too, and the message does not
suggest it.
Two options are worth knowing about for large imports:
| Option | What it does |
|---|---|
--batch-size=<n> | Commit every N records (default 1000) |
--on-error=skip | Leave out records that fail instead of stopping |
When an import stops, batches committed before the failing one stay in the
database, and the message says how many records they held. With
--on-error=skip, each record is committed on its own, so a bad one leaves
nothing behind, and every record left out is listed (up to 20, then a count):
Skipped nodes[1]: its "labels" is not an array
Skipped edges[0]: target "n9" is not the id of any node in the file
Importing bad.json into bad.lattice...
Import complete
Nodes imported: 1
Nodes failed: 1
Edges imported: 0
Edges failed: 1
Committing record by record is slower, but one bad row in a large file does not cost you the import.
Exporting
export writes JSON, JSONL, CSV, or DOT, or RDF as Turtle or N-Triples. It
picks the format from the file extension:
lattice export social.lattice --file=backup.json
lattice export social.lattice --file=graph.jsonl
lattice export social.lattice --file=people.csv --labels=Person
lattice export social.lattice --file=graph.dot
JSON, JSONL and CSV exports import back with import. Every node gets a new ID
when they do.
CSV export writes two files named after the one you give:
--file=people.csv produces people_nodes.csv and people_edges.csv:
_id,_labels,age:json,name:json
1,"Person",29,"""Carol"""
2,"Person",35,"""Dan"""
_source,_target,_type,since:json
1,2,KNOWS,2021
DOT is the format Graphviz reads, so you can turn a small graph into a picture:
digraph G {
n1 [label="1 : Person"];
n2 [label="2 : Person"];
n1 -> n2 [label="KNOWS"];
}
You can narrow what gets exported in one of two ways. --labels=Person,Company
exports the nodes with any of those labels and the edges between them.
--query exports what a query returns: the nodes and relationships in its rows,
plus the endpoints of every relationship, so the file imports on its own:
lattice export social.lattice --file=knows.json --query="MATCH (a:Person)-[k:KNOWS]->(b:Person) RETURN k"
The query has to return nodes or relationships, not just their properties
(RETURN p, not RETURN p.name); otherwise the export fails and says so.
--labels and --query cannot be combined.
Node vectors are included whenever the database has a vector index. The one
exception is a database last written by 0.16.0 whose dimensions cannot be read
from its vector pages: its export works, with a warning that the vectors are left
out unless you pass --enable-vector --vector-dims=<n>.
An export that fails removes the file it was writing rather than leave a partial one behind.
Dumping
dump writes the whole database to standard output as JSON, in a stable order:
lattice dump social.lattice > snapshot.json
Because the ordering is fixed, two dumps of the same data produce identical files. That
makes dump useful in tests and for spotting what changed between two databases with a
plain diff. It uses the same format as a JSON export, with each edge's ID added,
and it takes --labels, --query and the vector options the same way export
does. The summary line (Dumped 2 nodes, 1 edges) goes to standard error, so
it does not end up in the file.
Looking after a database
Checking for damage
check opens the file read-only and verifies the checksum stored on every page:
lattice check social.lattice
Database file checks passed
Pages checked: 15
Min reader: v4, so 0.16.0 cannot open it (changefeed events)
Note: sibling WAL file exists but was not validated
One thing to be aware of: this checks the main database file only. If a write-ahead log
file is sitting next to it, check will tell you it exists but will not look inside it.
The write-ahead log is the file LatticeDB appends changes to before applying them, so
that a crash cannot leave the database half-written.
Backing up
backup copies a database to another file without closing it:
lattice backup social.lattice --file=/backups/social-2026-08-25.lattice
Backed up social.lattice to /backups/social-2026-08-25.lattice
Bytes copied: 65536
Pages: 16
Pages flushed: 0
Duration: 1 ms
Pending writes are folded into the file before the copy starts, so what you get is a complete database on its own — you can open it directly, and it needs no write-ahead log beside it.
The copy is written next to the destination and renamed into place only once it is finished. An interrupted backup leaves nothing that looks usable, rather than a truncated file you discover is bad when you need it.
Two things to know. The backup captures the database as of the moment it starts, so writes that land during it are not included. And it will refuse to run while a transaction is open, because a copy taken while writes land underneath it is torn in ways no later check would catch.
Do not back up by copying the file yourself while the database is open. The
write-ahead log holds committed data that is not in the main file yet, so
copying just the main file gives you a database that opens and then fails on
query, and copying both files catches them at different instants and fails on
open. Neither announces itself at copy time — you find out at restore. Use
backup, or stop the process first.
Shipping changes somewhere else
A backup taken by hand is only as good as the last time you remembered to take
one. replicate copies a database into a directory you can restore from later:
lattice replicate social.lattice --to=social-backup
Started generation 1 for social.lattice in social-backup
Snapshot bytes: 65536
Generation: 1
Frames shipped: 0
Bytes shipped: 0
Duration: 4 ms
The first pass starts a generation: a full snapshot of the database, which later passes extend with the write-ahead log frames written after it. Run it again with nothing changed and it ships nothing:
Nothing new to ship for social.lattice
Generation: 1
Frames shipped: 0
Bytes shipped: 0
Duration: 2 ms
That is normal and not an error: the command exits successfully, so you can put it on a timer without filling your logs with things that look like failures.
Frames can only be shipped while the log still holds them. A process that writes
to the database and then closes it, as lattice exec or an application does,
folds the log into the file and resets it, and a reset log starts a new
generation. So when the writers are separate processes, as they are from the
command line, every pass after a change takes a fresh snapshot:
lattice exec social.lattice --query="CREATE (:Person {name: 'Carol'})"
lattice replicate social.lattice --to=social-backup
Started generation 2 for social.lattice in social-backup
Snapshot bytes: 65536
Generation: 2
Frames shipped: 0
Bytes shipped: 0
Duration: 5 ms
The destination then holds a manifest and one directory per generation:
social-backup/manifest.json
social-backup/gen-0000000001/snapshot.lattice
social-backup/gen-0000000002/snapshot.lattice
Older generations are left alone, because restoring to a moment inside one still
needs them. Delete a gen- directory to reclaim its space, at the cost of
restoring to any moment inside it.
Passes that ship frames rather than snapshots come from a process that keeps the
database open while it writes and replicates through the same handle: the Zig
API's replicateTo. Its log is reset only by a checkpoint (automatically after
about a thousand frames, by default) or when the database closes, and between
resets each pass copies only the new frames, into a frames/ directory inside
the generation. The C API and the
language bindings do not expose replication.
This command opens the database for writing, so it takes the file lock. It
cannot run against a database another process has open; it stops with the error
described under One process at a time. --follow
keeps it running and replicating on an interval:
lattice replicate social.lattice --to=social-backup --follow --interval=30
Each pass opens the database and closes it again, so other processes can use
the database between passes. A pass that finds the database open elsewhere is
skipped until the next interval; a process that opens the database while a pass
is running gets the same error and can retry. To replicate a database your
application keeps open, call replicateTo from the application.
Getting a database back
restore turns a replication directory back into a database:
lattice restore social-backup --output=recovered.lattice
Restored social-backup to recovered.lattice
Generation: 2
Segments: 0
Frames replayed: 0
Bytes written: 65536
Restored to: 2026-11-12T00:17:49Z
Duration: 500 ms
It copies the snapshot, replays the frames shipped after it (none here, since every pass in this generation came from the command line), and folds the result into one file. You can open that file, copy it, or move it, with nothing else beside it that has to be kept together with it.
To go back to an earlier moment, say when:
lattice restore social-backup --output=recovered.lattice --at="2026-11-12T00:18:00Z"
Times are read as UTC, so a restore means the same thing wherever you run it. A bare date works too and means midnight.
There is a limit worth understanding here. What you get is the state as of the last replication pass at or before the moment you asked for, not the state at that exact instant. If you replicate every thirty seconds, you can rewind to within thirty seconds. That is why the output tells you the moment it actually restored to, rather than repeating the one you asked for.
restore will not write over a file that already exists unless you pass
--force, because the thing most likely to be sitting at the output path is a
database somebody still wants.
Flushing pending writes
Changes are written to a write-ahead log first, and folded into the database file
later. checkpoint does that folding on demand and then resets the log:
lattice checkpoint social.lattice
Checkpointed database: social.lattice
Pages flushed: 0
Checkpoint LSN: 2
WAL truncated: yes
Duration: 0 ms
You mostly do not need this. A database checkpoints itself as the log grows, and again when it closes. It is worth running by hand in two situations: before copying a database file, so the copy is complete on its own, and on a database that has been open a very long time under heavy writes, if you want to pick the moment the flush happens rather than let it land mid-request.
How often a command's commits checkpoint is set with --auto-checkpoint=<frames>
on any command that writes: a checkpoint runs once the log holds that many frames
(one per page written), and 0 means none while the command runs, though closing
still folds the log into the file. Without the option the
LATTICE_AUTO_CHECKPOINT_FRAMES environment variable decides, else 1000:
lattice import social.lattice --file=people.jsonl --auto-checkpoint=0
This is not the same as compact. Checkpointing shrinks the log, not the
database file.
After a crash nothing has to be run first. The commands that only read
(info, count, labels, types, schema, export and dump) open the file
read-only and recover it in memory, so they show every committed transaction
without changing the files; the first command that writes recovers the files
themselves. check reads the database file's pages rather than the log, but it
too finishes a flush the crash interrupted, in memory from the journal, before it
checks, and adds a note saying so; the files stay as they were until a writing
command finishes the flush on disk.
Reclaiming space
Deleting a lot of data leaves free pages behind, and the file stays the same size
because those pages are kept for reuse. compact hands the unused ones at the end of
the file back to the operating system:
lattice compact social.lattice
Compacted database: social.lattice
Pages before: 16
Pages after: 16
Pages removed: 0
Bytes reclaimed: 0
Nothing was reclaimed here because nothing had been deleted. A few things are worth knowing before you run it on real data:
- It only truncates free pages at the end of the file. Free pages in the middle stay where they are and get reused normally, so a file with holes in the middle will not shrink much.
- Live pages are never moved, which is what makes it safe to interrupt.
- It will refuse to run on a read-only database, or while any transaction is open.
With --upgrade-indexes it first rebuilds every property index still in an older
encoding, so that one created by 0.16.0 answers ranges and sorting too, and
reports how many it rebuilt as Indexes rebuilt:.
Keeping the changefeed in check
Every change to the graph is recorded as an event in the changefeed, and by
default every event is kept, so a database that is edited a lot grows with its
history. changefeed shows how much there is and how much the file keeps:
lattice changefeed social.lattice
Changefeed of social.lattice
Retention: all
Events held: 10
Bytes: 136
Sequences: 1..10
--changefeed=<policy> sets how much to keep: all, off, last:<events>,
or age:<duration> such as age:30d. The file records it, and old events are
dropped as the database checkpoints; --trim drops them now:
lattice changefeed social.lattice --changefeed=last:2 --trim
Changefeed of social.lattice
Retention: last:2
Events held: 2
Bytes: 32
Sequences: 9..10
Trimmed: 8 events
Every command that writes takes --changefeed too, so
lattice create big.lattice --changefeed=off makes a database that keeps no
history at all. The Changefeed explains what the
history is for and how to choose.
Updating
update replaces your installed copy with the latest release:
lattice update
Working without a file
Pass :memory: instead of a path and the database lives only in memory:
lattice exec :memory: --query="CREATE (n:Note {t: 'scratch'}) RETURN n"
Nothing is written to disk and nothing survives the command, which makes it handy
for trying a query out or checking what some Cypher does. There is no file to
lock, so --no-lock means nothing here.
One process at a time
A database can only be open in one process at a time. If you run a command against a database your application already has open, it stops before touching anything:
Error: social.lattice is open in another process. Close it first, or pass
--no-lock if you are certain nothing is writing to it.
A command that writes needs the database to itself, and a command that only reads is also refused while something else is writing. That second part surprises people, so it is worth saying why: a reader in another process cannot see the writer's pending changes, and would be reading a file that is being rewritten underneath it. The answer it gave you would be stale at best.
Any number of read-only commands can run at once against a database nobody is writing.
Every command accepts --no-lock, which skips the check. It exists for
filesystems where locking does not work, such as some network filesystems. It
does not make concurrent access safe — it removes the thing that was going to
tell you it was not.
Files from a newer release
A database file can say that releases older than some version may read it but not write it. A command that writes stops on such a file and names the ones that still work:
Error: future.lattice was written by a newer LatticeDB that does not let this version write to it. info, count, labels, types, schema, export, dump, backup, query and exec (for statements that only read) still read it; use that newer version for anything else.
exec opens the database read-only for a statement that cannot write, and
backup always does, so both work on such a file; query opens it read-only
with a notice. The commands that write, import, compact, checkpoint and an
exec of a writing statement, are refused.
A file whose header asks for a newer reader than this release is refused by every command, with a message saying a newer LatticeDB wrote it.
Output formats
Most commands can print in a different format, which is what you want when something else is going to read the output:
lattice count social.lattice --format=json
lattice count social.lattice --format=csv
type,count
nodes,2
edges,1
labels,1
edge_types,1
table is the default and is meant for reading. It prints floats with six
decimals, and in the shortest scientific form that reads back as the same number
when they are 1e16 or more, or below 1e-6, in size (1e300, 1e-300), so a very
small number never shows as 0.000000. json and csv are meant for piping
somewhere else, and print floats in full, as plain decimals. A float that is not
a number or is infinite is written NaN, Infinity or -Infinity: as strings
in JSON ("NaN", also inside lists and maps), since JSON has no number for
them, and as the bare words in CSV and in a table. These are the spellings
toFloat() reads back. A query's JSON is for display, not a typed format: a
float such as 2.0 prints as 2; exports keep
types.
lattice exec social.lattice --query="MATCH (p:Person) RETURN p.name" --format=json | jq
A query's CSV follows RFC 4180, with one line per row ending in a newline: a
column name or value that holds a comma, a quote or a line break is put in
quotes, with each quote inside doubled. A list or map is written as its JSON, in
quotes, so {k: 'v'} becomes "{""k"":""v""}". A query without RETURN prints
nothing in CSV, an empty columns list in JSON and "Query executed" in a table.
Output redirected to a file can be appended to with >>, for example to keep a
log of counts taken over time:
lattice count social.lattice --format=csv >> counts.csv
Every command at a glance
| Command | What it does |
|---|---|
create <path> | Make a new database |
info <path> | Show file size, counts, features, indexes, and which releases can open it |
compact <path> | Give free pages at the end of the file back to the OS |
checkpoint <path> | Flush pending writes into the file and reset the log |
changefeed <path> | Show the changefeed, set how much of it to keep, trim it |
backup <path> | Copy to another file while the database stays open |
replicate <path> | Keep a directory up to date with the database |
restore <dir> | Rebuild a database from a replication directory |
check <path> | Verify page checksums in the main file |
query <path> | Open an interactive Cypher shell |
exec <path> | Run one query and exit |
import <path> | Load data from JSON, JSONL, CSV, Turtle or N-Triples |
export <path> | Write data to JSON, JSONL, CSV, DOT, Turtle or N-Triples |
dump <path> | Print the whole database as canonical JSON |
labels <path> | List node labels and their counts |
types <path> | List edge types and their counts |
schema <path> | Show the shape of the data |
count <path> | Show node and edge totals |
update | Update your LatticeDB installation |
version | Print the version and file format version |
help | Show usage |
Where to go next
- Quick Start for the same ideas from Python or TypeScript
- Core Concepts for what nodes, edges, and properties actually are
- Cypher Overview for the query language itself
Core Concepts
Property Graph
LatticeDB stores data as a property graph: a collection of nodes connected by edges, where both nodes and edges can have labels and key-value properties.
Nodes
A node represents an entity. Each node has:
- A unique ID (assigned automatically)
- Zero or more labels that categorize it (e.g.,
Person,Document,Chunk) - Zero or more properties — key-value pairs (e.g.,
name: "Alice",age: 30)
alice = txn.create_node(
labels=["Person"],
properties={"name": "Alice", "age": 30}
)
Edges
An edge represents a relationship between two nodes. Each edge has:
- A source node and a target node
- An edge type (e.g.,
KNOWS,AUTHORED_BY,PART_OF) - A direction — edges always point from source to target
- Zero or more properties, like a node
txn.create_edge(alice.id, bob.id, "KNOWS")
Properties
Properties are typed key-value pairs attached to nodes and edges. Supported types:
| Type | Python | TypeScript | C |
|---|---|---|---|
| Null | None | null | LATTICE_VALUE_NULL |
| Boolean | bool | boolean | LATTICE_VALUE_BOOL |
| Integer | int | number | LATTICE_VALUE_INT |
| Float | float | number | LATTICE_VALUE_FLOAT |
| String | str | string | LATTICE_VALUE_STRING |
| Binary | bytes | Uint8Array | LATTICE_VALUE_BYTES |
| Vector | numpy.ndarray (float32) | Float32Array | LATTICE_VALUE_VECTOR |
| List | list | array | LATTICE_VALUE_LIST |
| Map | dict (string keys) | object (string keys) | LATTICE_VALUE_MAP |
TypeScript also accepts bigint for integers. Lists and maps nest to any depth.
Cypher Query Language
LatticeDB uses Cypher — a declarative graph query language. Nodes are written in parentheses, edges in square brackets:
MATCH (person:Person)-[:KNOWS]->(friend:Person)
WHERE person.name = "Alice"
RETURN friend.name
LatticeDB extends Cypher with two operators:
<=>— vector distance for similarity search@@— full-text search with BM25 scoring
Vector Search
LatticeDB includes an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search on vector embeddings.
To use vector search:
- Enable vector storage when creating the database, with the number of dimensions and, if not cosine, the distance metric; the file records them, so later opens need no vector options
- Attach vector embeddings to nodes
- Search by similarity using
vector_search()or the<=>operator in Cypher
# Store an embedding. A node has one vector; Cypher reads it as n.embedding.
txn.set_vector(node.id, "embedding", vector)
# Search by similarity
results = db.vector_search(query_vector, k=10)
# Or in Cypher
db.query("MATCH (n:Chunk) WHERE n.embedding <=> $q < 0.5 RETURN n", parameters={"q": query_vector})
Embeddings
LatticeDB provides two ways to generate embeddings:
hash_embed— a built-in deterministic hash function. No external service needed. Useful for testing and simple keyword-based similarity.EmbeddingClient— an HTTP client that connects to Ollama, OpenAI, or any compatible API for production-quality embeddings.
Full-Text Search
LatticeDB includes a BM25-scored inverted index for full-text search. Declare an index on a label and property, and every write to that property keeps it current. A search reads one declared index.
# Declare an index over the property holding the text
db.create_node_fts_index("Chunk", "text")
# Writing that property is what indexes it
txn.set_property(node.id, "text", "The transformer architecture uses self-attention")
# Search
results = db.fts_search("Chunk", "text", "transformer attention")
# Fuzzy search (typo-tolerant)
results = db.fts_search_fuzzy("Chunk", "text", "transformr atention")
# Or in Cypher
db.query('MATCH (n:Chunk) WHERE n.text @@ "transformer attention" RETURN n')
Transactions
All operations in LatticeDB happen within transactions. LatticeDB uses snapshot isolation: each transaction sees a consistent snapshot of the database as of when it started.
- Read transactions can run concurrently — readers never block other readers.
- Write transactions are exclusive — only one can be open at a time. Beginning a second one while the first is open fails immediately with a lock-timeout error; it does not wait.
# Read transaction
with db.read() as txn:
node = txn.get_node(node_id)
# Write transaction
with db.write() as txn:
txn.create_node(labels=["Person"], properties={"name": "Alice"})
txn.commit()
If a write transaction is not explicitly committed, it is rolled back when the context exits.
Single-File Storage
The entire database — nodes, edges, properties, vector index, and text index — lives in a single file, with the write-ahead log beside it while the database is open. That makes a database easy to move: back it up or deploy it by moving one file.
It also makes it easy to move without a file at all. Because a database is one file, serializing it is reading that file, so you can hand a whole database around as bytes and open it again elsewhere:
blob = db.serialize()
db2 = latticedb.deserialize(blob)
That is what makes it practical to keep a database per case or per tenant in object storage, pulling one down when you need it.
One caveat worth learning early: do not copy the file while the database is
open. The log holds committed changes the main file does not have yet, so a copy
taken then is broken in a way you only discover when you try to use it. Use
lattice backup, or stop the process first.
Databases Without Files
A database does not have to be on disk at all. Open :memory: and it lives
entirely in memory:
import latticedb
with latticedb.Database(":memory:") as db:
db.query("CREATE (n:Note {text: 'hello'})")
Everything works the same — transactions, indexes, vector and text search — and it disappears when you close it. It is the quickest way to try something, the usual choice for tests, and what a database loaded from bytes runs on.
See In-Memory Databases.
When to Use LatticeDB
LatticeDB is fast, but speed is not the only thing that matters. Here are cases where a different tool is the better choice.
You need multiple applications writing to the same database at the same time
LatticeDB is embedded, and one process opens the file and owns it. If you need many clients connecting over a network, use Neo4j, PostgreSQL, or another database built around a server.
This applies inside a single process too: only one write transaction can be open at a time. Beginning a second one while the first is still open fails immediately rather than waiting. Reads are unrestricted — as many as you like, at the same time, alongside the writer. If your program writes from several threads, they need to take turns. See One writer at a time for what that looks like in practice.
Your data is fundamentally tabular
If your data fits naturally into rows and columns — sales records, user accounts, time series — a relational database like SQLite or PostgreSQL will be simpler and just as fast. Graph databases shine when relationships between records are the point, not an afterthought.
You need to scale beyond a single machine
LatticeDB stores everything in one file on one machine. If you need sharding, replication, or distributed queries across billions of nodes, look at Neo4j cluster, Dgraph, or a managed service like Neptune.
You need the full Cypher language
LatticeDB implements most of the Cypher people write day to day, OPTIONAL MATCH, UNION, CASE, CALL { } subqueries, comprehensions and
shortestPath among it, but not all of the language. These are not
implemented:
- quantified path patterns (
((a)-->(b)){1,3}) LOAD CSVandCALL { } IN TRANSACTIONS- user-defined procedures and functions; the only procedures are the catalog
ones, such as
db.labels() - temporal and spatial types
- schema and administration statements (
CREATE INDEX,SHOW,EXPLAIN)
If your queries depend on these, Neo4j is the complete implementation. See Not Supported for the full list; each one fails with an error that names it.
You need mature tooling and ecosystem
Neo4j has visualization tools, admin dashboards, monitoring, drivers in every language, and years of community resources. PostgreSQL has decades of tooling. LatticeDB is new and lean — which is a strength for embedding, but a weakness if you need a rich operational ecosystem around your database.
Choosing an Embedded Graph Database
Embedded graph databases run inside your process instead of behind a network socket. This page compares LatticeDB with the other options in that space, and with the databases people most often reach for instead.
If you are deciding whether LatticeDB fits your problem at all, start with When to Use LatticeDB — it is candid about where a different tool is the better answer.
The landscape
| LatticeDB | LadybugDB (ex-Kùzu) | SQLite | Neo4j | Chroma / LanceDB | |
|---|---|---|---|---|---|
| Deployment | Embedded, one file | Embedded | Embedded, one file | Server (JVM embedded available) | Embedded |
| Data model | Property graph | Property graph | Relational | Property graph | Vectors + metadata |
| Query language | Cypher subset | Cypher | SQL | Full Cypher | Python/SDK API |
| Graph traversal | Native | Native | Recursive CTE | Native | No |
| Vector search | Native HNSW | Native | Extension (sqlite-vec) | Native vector index | Native |
| Full-text search | Native BM25 | Native | FTS5 extension | Lucene index | Varies |
| Durable streams | Native | No | No | No | No |
| Storage shape | Row-oriented, OLTP | Columnar, analytical | Row-oriented | Row-oriented | Columnar / Lance |
| Maturity | New | Fork of a mature engine | 25 years | 15+ years | Young |
Detailed comparisons
- LatticeDB vs SQLite — the closest philosophical relative, and the only comparison here measured head to head on the same machine
- LatticeDB vs Kùzu and LadybugDB — the other embedded property-graph engines, and what happened to Kùzu
- LatticeDB vs Neo4j — embedded versus server, and what you give up
- LatticeDB vs vector databases — Chroma, LanceDB, pgvector, and sqlite-vec for RAG workloads
How to read the numbers
Benchmark comparisons in this section come from two very different places, and it matters which is which.
Head-to-head measurements. The SQLite comparison runs both engines on the same machine, over the same data, each through its own public C API with the same durability settings (a log fsynced on every commit), in one program (zig build capi-benchmark), and you can reproduce it yourself. Competitive Analysis states the settings and the queries on both sides.
Published third-party figures. Numbers for Kùzu, Neo4j, Weaviate, Qdrant, Chroma, and the rest are taken from their own documentation or from third-party blog posts, on hardware we do not control, with methodology we did not choose. They are useful for order-of-magnitude orientation and nothing more. Do not read a 2x difference between LatticeDB and a third-party figure as meaningful.
Every figure and its source is listed in Competitive Analysis. The raw LatticeDB measurements, including the hardware they were taken on, are in Benchmarks.
The short answer
Use LatticeDB when relationships, vector similarity, and text relevance are all part of the same question, and you want that answered locally without running a server or synchronising two stores.
Use SQLite when your data is fundamentally tabular and traversal is occasional.
Use LadybugDB when your graph workload is analytical — large scans, aggregations, Arrow and Parquet interoperability.
Use Neo4j when you need full Cypher, multi-client access, clustering, or the operational tooling of a mature ecosystem.
Use a dedicated vector database when vectors are the whole problem and there is no graph in it.
LatticeDB vs SQLite
SQLite is the closest thing LatticeDB has to a design ancestor: one file, no server, embedded in your process, and boring in all the right ways. The difference is what the file is organised for. SQLite organises rows into tables; LatticeDB organises nodes into a graph, with vector and full-text indexes over their properties.
This is the only comparison in this section measured head to head. Both engines run on the same machine, over the same generated data, each through its own public C API with comparable durability settings, in the same program — zig build capi-benchmark -- --suite core --suite sqlite. You can reproduce every number below.
When SQLite is the right answer
Start here, because it often is.
- Your data is tabular. Sales records, user accounts, event logs, time series. If your queries are filters and aggregations over rows, SQLite will be simpler, smaller, and just as fast.
- You need many concurrent readers across processes. SQLite in WAL mode handles this well. LatticeDB is single-writer and single-process.
- You need ubiquity. SQLite ships inside every phone, browser, and operating system on earth, has bindings for every language, and will still be readable in thirty years. LatticeDB is new.
- You need the ecosystem. Migration tools, GUI browsers, ORMs, hosted replicas. SQLite has all of it. LatticeDB has continuous backup and point-in-time restore built in, and almost nothing else yet.
If relationships in your data are an occasional join rather than the point of the query, use SQLite.
Traversal: closer than you might think
Traversal in SQLite means joins of an edge table on itself, or a recursive common table expression for paths of any length. With the edge table indexed on its source column, that is fast, and for a few hops it is as fast as LatticeDB.
The figures below are LatticeDB 0.17.0 and SQLite 3.51.0 on an Apple M5 (macOS 26.5, 2026-11-13). Both write a log and fsync it on every commit (journal_mode=WAL and synchronous=FULL for SQLite, LatticeDB's defaults), with a 100 MB page cache each. The graph is Person nodes (rows) with 5 KNOWS edges out of each to random others; each query starts from a random node found through an index on an integer uid and counts what it reaches. Medians of five runs, p50 of 2,000 queries each.
| Workload | 10K nodes: LatticeDB | SQLite | 100K nodes: LatticeDB | SQLite |
|---|---|---|---|---|
| 1 hop (5 paths) | 2.5 us | 2.5 us | 4.8 us | 3.6 us |
| 2 hops (25) | 4.4 us | 5.4 us | 8.8 us | 8.9 us |
| 3 hops (125) | 14 us | 14 us | 21 us | 29 us |
| 1 to 5 hops (about 3,905) | 472 us | 1,038 us | 600 us | 1,361 us |
LatticeDB runs Cypher (MATCH (a:Person {uid: $uid})-[:KNOWS*1..5]->(b) RETURN count(b)); SQLite runs joins, and a recursive CTE with UNION ALL for the last row. Both count the same paths. For a few hops the two are level; enumerating longer paths, LatticeDB is about twice as fast. Neither has a reachability operator that visits each node once: both enumerate paths, so the cost of a deep pattern follows the number of paths.
Point lookups by an indexed value are level too: 2.3 us for the Cypher query against 3.0 us for SQLite at 100,000 rows. Writes are not: SQLite inserts rows in transactions of 1,000 at 1.8 million a second, LatticeDB creates nodes at 330,000 a second, because a node also writes a label index entry, separate property records and changefeed events. A single durable commit costs about the same in both (44 us and 42 us at p50, within run-to-run noise). The full table is in Competitive Analysis.
Earlier editions of this page showed LatticeDB tens to thousands of times faster than SQLite at traversal. Those figures came from Zig code calling the storage layer over an in-memory adjacency cache that queries and the bindings never use, with LatticeDB's log off and SQLite doing more work per query; they are withdrawn.
Search: one engine or three
The more practical difference is what you have to assemble.
Doing hybrid retrieval on SQLite means composing three things: FTS5 for text, sqlite-vec or a similar extension for vectors, and recursive CTEs for relationships. Each is good. But they are separate indexes with separate query syntax, and combining them means either multiple round trips or a query you would rather not maintain.
In LatticeDB, all three are the same query:
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query_vector < 0.3
AND chunk.text @@ 'transaction isolation'
RETURN doc.title, author.name, chunk.text
ORDER BY chunk.embedding <=> $query_vector
LIMIT 10
We have not measured FTS5 or sqlite-vec against LatticeDB's full-text and vector indexes. sqlite-vec searches by brute force, which its author measured at around 17 ms over 1M vectors; LatticeDB's own full-text and vector figures are on Benchmarks. Those are not a head-to-head comparison — see how to read the numbers.
Durability and transactions
Both engines are ACID with write-ahead logging and recover committed transactions after a crash. LatticeDB's crash tests simulate a crash by resetting the file header after a clean close; they do not kill a running process or tear data pages. LatticeDB's WAL, checkpointing, and recovery design is documented in Architecture.
LatticeDB adds one thing SQLite has no equivalent for: durable streams and changefeeds. Graph mutations can be consumed as an ordered, replayable log from inside the same file, which is useful when something downstream — an index, a cache, an embedding pipeline — needs to react to writes.
Summary
| LatticeDB | SQLite | |
|---|---|---|
| Best at | Hybrid retrieval, connected data in one query | Tabular data, universal deployment |
| Query language | Cypher subset | SQL |
| Vector search | Native HNSW | Extension, brute force |
| Full-text search | Native BM25 | FTS5 extension |
| Concurrency | Single writer, single process | Multi-reader, single writer |
| Streams | Native | None |
| Maturity | New | 25 years, everywhere |
The honest framing: SQLite is a better general-purpose embedded database and will remain so. LatticeDB is a better embedded database for the specific shape of problem where relationships, semantics, and text all matter to the same query.
LatticeDB vs Kùzu and LadybugDB
Kùzu was the reference implementation of an embedded property-graph database: Cypher, vector search, and full-text search in a library you linked into your process. In October 2025 its creators were acquired by Apple and the repository was archived. It has received no commits since. If you are running Kùzu today, you are running unmaintained software, and this page exists partly to help you decide what to do about that.
What replaced Kùzu
The community forked it. LadybugDB is the most active continuation, under development and positioning itself as a graph lakehouse — DuckDB storage interoperability, Arrow and Parquet in and out, object-store backends. It is a genuine successor and, if you want a drop-in path off Kùzu, it is the shortest one.
LatticeDB is not a Kùzu fork. It is an independent engine written in Zig with a different centre of gravity, so migrating to it is a port rather than a swap.
The architectural difference that matters
Kùzu was built columnar, for analytical graph workloads: scan a large fraction of the graph, aggregate, join against tabular data. LadybugDB is doubling down on that with the lakehouse direction. It is the right design for "compute something over the whole graph."
LatticeDB is row-oriented and transactional. It is built for "answer this question about this neighbourhood, now, while a user waits" — point lookups, bounded traversals, retrieval, and writes that need to land durably and immediately.
Neither shape is better. They are answers to different questions, and the workload should pick.
| LatticeDB | LadybugDB (ex-Kùzu) | |
|---|---|---|
| Storage | Row-oriented | Columnar |
| Optimised for | Transactional, point and neighbourhood queries | Analytical, large scans and aggregations |
| Written in | Zig | C++ |
| Interoperability | Single self-contained file | Arrow, Parquet, DuckDB, object stores |
| Durable streams | Native | No |
| Cypher coverage | Subset | Broader |
| Maturity | New | Inherits a mature codebase |
Published performance figures
We have not measured Kùzu or LadybugDB. The one figure in circulation is a third-party blog post's 19 ms for a 2-hop traversal over 100K nodes, on hardware and with a query we do not know in detail. LatticeDB's own 2-hop figure (a Cypher count from an indexed node, 100K nodes and 500K edges, 8.8 us at p50) is on Benchmarks, measured by a different method on different data, so the two are not a comparison. If you care about the answer for your workload, run both.
What LatticeDB has that Kùzu did not
Durable streams and changefeeds. Graph mutations are consumable as an ordered, replayable log from inside the same file. See Durable Streams. Nothing in the Kùzu or LadybugDB lineage offers this.
A single self-contained file. No external format dependencies, no runtime, no dependencies at all. The database is one file you can copy.
Active maintenance. Relative to Kùzu specifically, which has none.
What Kùzu had that LatticeDB does not
Being honest about this matters more than the section above.
Broader Cypher coverage. LatticeDB implements a subset. Quantified path patterns, LOAD CSV, user-defined procedures and functions, and temporal types are not there — see When to Use LatticeDB.
A mature codebase with real production mileage. Kùzu had years of academic and industrial work behind it, and LadybugDB inherits all of it. LatticeDB is new, and new means undiscovered bugs.
Analytical throughput. If your query touches most of the graph, a columnar engine will beat a row-oriented one, and that is a structural property, not a tuning problem.
Ecosystem interoperability. Arrow, Parquet, and DuckDB integration are real advantages if your graph is one stage in a larger data pipeline.
Choosing
Coming off Kùzu and want the shortest path with the least porting? LadybugDB.
Running analytical workloads over large graphs, or your graph lives in a lakehouse? LadybugDB.
Building an application that asks bounded questions about connected data — retrieval, recommendations, knowledge graphs behind an LLM — and wants vector similarity, text relevance, and traversal answered together, locally, with durable change streams? That is what LatticeDB is for.
Start with the Quick Start, or read Core Concepts if you want the data model first.
LatticeDB vs Neo4j
Neo4j is the reference property-graph database and the reason most people know Cypher at all. LatticeDB speaks a subset of the same language over the same data model, but it is a library rather than a server, which changes almost everything downstream of that choice.
If you are looking for a Neo4j alternative, the first question is not performance. It is whether you actually want a database process at all.
Server versus embedded
Neo4j runs as a service. Your application opens a Bolt connection, sends a query, and receives a result set over the network. That indirection buys you multi-client access, independent scaling, clustering, and an operational surface you can monitor and back up with standard tools.
LatticeDB runs inside your process. There is no connection, no serialisation, no network hop, and no second thing to deploy. A query is a function call against pages cached in your own process. The database is one file you can copy, ship, or delete.
Neo4j does offer an embedded mode, but it is JVM-only — you embed it in a Java or Kotlin application. If your application is Python, TypeScript, Rust, Go, or C, embedded Neo4j is not available to you and the server is the only option.
What you give up
This is the important section, and When to Use LatticeDB says it plainly. Summarised:
Full Cypher. LatticeDB implements a substantial subset, including OPTIONAL MATCH, UNION, CASE, CALL { } subqueries and shortestPath. Quantified path patterns, LOAD CSV, user-defined and APOC procedures, temporal and spatial types, and schema statements are not implemented. If your queries depend on them, Neo4j is the complete implementation and LatticeDB will refuse those queries.
Multi-client access. LatticeDB is single-writer, single-process. One process opens the file and owns it. If several applications need to write concurrently over a network, you need a server, and that server is Neo4j or Postgres.
Scale beyond one machine. Everything lives in one file on one host. Neo4j clusters; LatticeDB does not. Sharding, replication, and distributed query are out of scope by design.
Tooling. Neo4j Browser and Bloom for visualisation, admin dashboards, monitoring integrations, official drivers in every language, a decade of Stack Overflow answers, certification courses, and a consulting ecosystem. LatticeDB has documentation and a GitHub repository.
Operational maturity. Fifteen years of production deployments have found bugs that a new engine has not yet found.
What you gain
No server. No process to deploy, secure, monitor, upgrade, or pay for. For a desktop application, a CLI tool, an edge deployment, a notebook, or a test suite, this is often the entire argument.
No network hop. A third-party comparison put Neo4j point lookups around 28 ms at p99; a Cypher lookup by an indexed property in LatticeDB, in process, takes about 2.3 us (Benchmarks). Most of that gap is the network and serialisation, not the storage engine — which is exactly the point of embedding, but it also means the comparison is measuring architecture rather than engineering, and the two figures come from different machines and methods. See how to read the numbers.
Vector and text search in the same engine. Neo4j does vector indexes and Lucene-backed full-text, but LatticeDB was designed around combining them with traversal in one query rather than adding them alongside it.
Durable streams. Graph mutations as an ordered, replayable log inside the same file. See Durable Streams.
One file. Backup is cp. Distribution is shipping a file. There is no import step for a colleague to run.
Side by side
| LatticeDB | Neo4j | |
|---|---|---|
| Deployment | Library, in-process | Server (JVM embedded available) |
| Languages | C, Python, TypeScript, Go, Java | Drivers for everything; embedded is JVM-only |
| Cypher | Subset | Complete, plus procedures |
| Concurrency | Single writer, single process | Many clients |
| Clustering | No | Yes |
| Vector search | Native HNSW | Vector index |
| Full-text search | Native BM25 | Lucene index |
| Durable streams | Native | Change Data Capture (Enterprise) |
| Visualisation | None | Browser, Bloom |
| Licence | MIT | GPL / commercial |
| Operational cost | A file | A cluster |
Choosing
Choose Neo4j when multiple services query the same graph, when you need Cypher features LatticeDB does not implement, when the graph outgrows one machine, or when the tooling and ecosystem are worth the operational cost.
Choose LatticeDB when the graph belongs to one application, when you want retrieval that mixes relationships with vector similarity and text relevance, and when not running a database server is a feature rather than a compromise.
A common and reasonable pattern is both: Neo4j as the system of record for a shared graph, LatticeDB embedded in an application or on a device holding the slice it needs to query locally and quickly.
LatticeDB vs Vector Databases
Most RAG systems start with a vector database — Chroma, LanceDB, pgvector, or sqlite-vec — and that is usually the right first move. This page is about the point where a pure vector store stops being enough, which arrives sooner than most teams expect.
Where vector-only retrieval breaks down
A vector database answers one question well: which chunks are semantically nearest this query. The problems show up around that answer.
Chunks have context that similarity does not capture. The nearest chunk came from a document, which has an author, a date, a version, and a place in a hierarchy. Retrieval quality usually improves when you can pull that context in — and in a vector-only store, that means a second database and a join in application code.
Similarity misses exact terms. Someone searching for an error code, a function name, or a product SKU wants lexical matching, not semantic neighbourhood. This is what BM25 is for, and it is why hybrid retrieval consistently outperforms pure vector search.
Relationships are the answer sometimes. "What else did this author write", "what supersedes this document", "what is two hops from this concept" are traversals. No amount of embedding quality answers them.
The usual response is to run a vector store plus a relational database plus a search index, and keep three systems consistent. LatticeDB's argument is that these are one question and should be one query.
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE (chunk.embedding <=> $query_vector < 0.3
OR chunk.text @@ 'connection pool exhausted')
AND doc.version = $current_version
RETURN doc.title, author.name, chunk.text
ORDER BY chunk.embedding <=> $query_vector
LIMIT 10
Vector similarity, lexical matching, graph traversal, and a metadata filter, resolved together against one file. The full worked example is in Building a RAG System.
Feature comparison
| LatticeDB | Chroma | LanceDB | pgvector | sqlite-vec | |
|---|---|---|---|---|---|
| Deployment | Embedded | Embedded / server | Embedded | Postgres extension | SQLite extension |
| Vector index | HNSW | HNSW | IVF / HNSW | HNSW / IVFFlat | Brute force |
| Full-text search | Native BM25 | BM25 and sparse vectors | Native | tsvector | FTS5, separate |
| Graph traversal | Native Cypher | No | No | Recursive CTE | Recursive CTE |
| Metadata filtering | Cypher WHERE | Dict filters | SQL-like | Full SQL | Full SQL |
| Durable streams | Native | No | No | Logical decoding | No |
| Transactions | ACID | Limited | Limited | ACID | ACID |
| Needs a server | No | Optional | No | Yes | No |
Published latency figures
Every number below comes from the vendor's own documentation or a third-party benchmark, on hardware, data and settings we did not control, and none was measured here. They are order-of-magnitude orientation, not a head-to-head result — see how to read the numbers.
| System | Published 10-NN latency at 1M vectors | Type |
|---|---|---|
| FAISS HNSW (single thread) | 0.5–3 ms | Library |
| Weaviate | 1.4 ms mean, 3.1 ms p99 | Server |
| Qdrant | ~1–2 ms | Server |
| Milvus + SQ8 | 2.2 ms p99 | Server |
| LanceDB | 3–5 ms | Embedded |
| Chroma | 4–5 ms mean | Embedded |
| pgvector HNSW | ~5 ms at 99% recall | Extension |
| Pinecone P2 | ~15 ms including network | Cloud |
| sqlite-vec | 17 ms (brute force) | Extension |
Sources for each row are in Competitive Analysis. LatticeDB's own measurements, on synthetic clustered vectors, are in Benchmarks: at 1M vectors, 1.34 ms at p50 with 95.6% recall@10 and the default 100 MB cache, 0.21 ms with a 2 GB cache.
When a vector database is still the better choice
Your retrieval genuinely has no graph in it. A flat corpus of independent chunks with no meaningful relationships is exactly what a vector store is for. Adding a graph model buys you nothing.
You need to scale past one machine. LatticeDB is one file on one host. Qdrant, Weaviate, Milvus, and Pinecone shard and replicate.
You are already on Postgres. If your metadata lives in Postgres, pgvector keeps everything in one database and one transaction. That consolidation is worth more than a few milliseconds.
You need the ecosystem. LangChain and LlamaIndex integrations, managed hosting, hybrid-search tuning knobs, and reranking pipelines are mature in the dedicated vector stores and thin here.
Billions of vectors. LatticeDB is benchmarked to 1M vectors; its index estimates about 1 GB of pages for them, and the benchmark ran with a 4 GB buffer pool. Beyond that scale you want a purpose-built distributed system.
When LatticeDB fits
When your retrieval corpus has structure — documents, authors, versions, topics, citations, conversations — and you want that structure to participate in retrieval rather than sit in a separate database. When exact-term matching matters alongside semantic similarity. When you would rather ship one file than operate three services.
Start with Building a RAG System for a worked example, or Working with Embeddings for the vector-indexing details.
Opening a Database
Almost everything you can configure is decided when you open a database. This page is the reference for those options: what each one does, when to change it, and what it costs you to get wrong.
db = latticedb.Database(
"graph.lattice",
create=True,
enable_vectors=True,
vector_dimensions=1536,
)
db.open() # or use it as a context manager: with latticedb.Database(...) as db:
Not every option below is available everywhere. The bindings and the C API expose
create, read_only, cache_size_mb, enable_vectors, vector_dimensions,
vector_metric, vector_m, vector_ef_construction, enable_wal,
enable_adjacency_cache, lock, sync_mode, full_fsync and
changefeed_retention; the C API, Go and Java also take page_size (Python and
TypeScript always use 4096). In the C API the vector, durability and changefeed
settings after lock are fields of lattice_open_options_v5. enable_fts and
the query-cache settings are options of the Zig API only — everywhere else they
keep their defaults. auto_checkpoint is an open option in Zig only; everywhere
else it is set on the open database, or through LATTICE_AUTO_CHECKPOINT_FRAMES
(see Checkpointing).
Decided at creation, and permanent
| Option | What it does |
|---|---|
page_size | Size of a page in bytes, 4096 to 65535. Fixed when the file is created and stored in it. The default of 4096 matches almost every filesystem and is the right answer unless you have measured otherwise. |
vector_dimensions | How many numbers are in each vector, 1 to 4096 (default 128). This has to match whatever produces your embeddings. |
vector_metric | How the vector index measures distance: cosine (the default), euclidean, or dot_product. See below. |
vector_m | HNSW connections per node, 2 to 32 (default 16; layer 0 keeps twice as many). More connections give better recall for more memory and slower inserts. |
vector_ef_construction | HNSW candidate list size while building, 1 to 4096 (default 200). Larger builds a better graph, more slowly. |
The vector settings take effect when an open creates the vector index (with
enable_vectors on a database that has none), and the file records them. A
database that has a vector index opens with it whatever the options say, so
reopening it needs no vector options at all, after a crash included. Any vector
setting you do pass must match what the file records, or the open fails with a
configuration-mismatch error (LATTICE_ERROR_CONFIG_MISMATCH): the settings cannot
be changed after creation. To change them, export the data and import it into a new
database. With vectors enabled, dimensions 0 means "whatever the file records" in
every binding (vector_dimensions=0, vectorDimensions: 0, VectorDimensions: 0,
vectorDimensions(0)); where the open would have to create an index, 0 is
refused as an invalid argument.
The metric decides what <=> and vector search return, smallest first:
| Metric | Distance | Vectors are stored |
|---|---|---|
cosine | 1 − cos(a, b), from 0 to 2 | scaled to unit length |
euclidean | the L2 distance, √Σ(aᵢ − bᵢ)² | as given |
dot_product | the negative dot product, −(a · b), so the largest product comes first | as given |
Getting vector_dimensions wrong is the one that bites, because it is only
discovered when the first vector is rejected. OpenAI's text-embedding-3-small
produces 1536 numbers, so that is the number you would pass for it.
0.16.0 refuses to open a file whose index uses euclidean or dot_product, or an
m other than 16, because it would misread it. A cosine index with the default m
does not keep 0.16.0 out, though other things do, the changefeed above all; see
Opening with 0.16.0.
Which features exist
| Option | Default | What it does |
|---|---|---|
create | off | Create the database if it is not there. Ignored for :memory:, which always creates. |
read_only | off | Open without the ability to write. Takes a shared lock, so several readers can share a database nobody is writing. |
enable_vectors | off | Create vector storage and the HNSW index if the database has none. A database that has one opens with it without this. |
enable_fts | on | Turn on full-text search (Zig API only). |
enable_wal | on | Write-ahead logging. See below before turning this off. |
enable_adjacency_cache | off | Keep an in-memory map of which nodes connect to which. Queries and the C API's edge calls do not read it, so today it costs memory and a little work on each edge write and speeds up nothing reached through the bindings. |
A database created without vector support has no vector storage. Opening it later with vectors enabled creates the vector storage then, so you can start adding vectors to an existing database. The new index's configuration is written to the file during that open.
Memory and caching
| Option | Default | What it does |
|---|---|---|
cache_size_mb | 100 MB (C API and bindings); 64 MB (CLI) | How much memory to hold pages in. |
enable_query_cache | on | Cache parsed queries so repeating one does not re-parse it (Zig API only). |
query_cache_size | 128 | How many parsed queries to keep (Zig API only). |
The C API and every binding default cache_size_mb to 100, and the CLI to 64
(--cache-size). Set it when you know better — a machine with little memory, or a
working set you have actually measured. A bulk load gains most from a large cache;
see Bulk loading.
Only the Zig API can leave the size unset (buffer_pool_size = 0). The cache then
sizes itself from the features you turned on: 16 MB for the graph, plus 12 MB each
for full-text and vector search, so about 40 MB with both.
The environment variable LATTICE_BUFFER_POOL_MB sets the size wherever the program
leaves it unset: buffer_pool_size = 0 in Zig, cache_size_mb = 0 in C, no cache
size in a binding, no --cache-size in the CLI. A size the program sets wins over
the variable, as with LATTICE_SYNC_MODE and LATTICE_FULL_FSYNC. The bindings
and the C API leave it unset by default, so the variable is useful for trying a
value without changing code; without it they use 100 MB.
In-memory databases cap the cache at 64 pages (256 KB at the default page size) whatever you ask for, because a cache miss against memory is a copy rather than a trip to a disk. See Storage Modes.
The size is the cache's resting size, not a hard ceiling. Changed pages are never evicted to make room; they stay until the next flush writes them all together, and the cache grows past its size if it has to hold them. The database flushes early when half the cache holds changes, so this only shows during a single large transaction or a long recovery.
Safety
| Option | Default | What it does |
|---|---|---|
lock | on | Take a lock on the file so two processes cannot tread on each other. |
A database can only be open in one process at a time. Opening takes a lock: a read-write handle takes it exclusively and a read-only handle shares it, so opening returns an error rather than waiting.
Turn lock off only where locking does not work, such as some network
filesystems. It does not make concurrent access safe; it removes the thing that
was going to tell you it was not. Go phrases this as DisableLock because a Go
bool cannot tell an omitted field from a deliberate false, and locking has to
stay on when the caller says nothing.
The changefeed
| Option | Default | What it does |
|---|---|---|
changefeed_retention | the file's policy; all for a new file | How much of the changefeed (__lattice_changes) to keep: all, last:<N>, age:<duration> or off. Recorded in the file; a value given when opening for writing replaces the file's. Python changefeed_retention, TypeScript changefeedRetention, Go ChangefeedRetention, Java changefeedRetention, C lattice_open_options_v5.changefeed_retention, CLI --changefeed. LATTICE_CHANGEFEED_RETENTION sets it for a new database. |
Every committed change is recorded as an event, and by default every event is kept, so the changefeed grows with the number of changes ever made. See The Changefeed for the policies, what each costs and when to use which.
Durability
enable_wal = false means only that nothing is logged. Transactions, rollback and
all-or-nothing queries work the same without the log; what you give up is that a
commit survives a crash only once its pages have been flushed to the file: at
close, when half the page cache holds changes, or on sync() in Zig. See
Running without the log for exactly
what a crash leaves and what it saves.
| Option | Default | What it does |
|---|---|---|
enable_wal | on | Write-ahead logging: a commit survives a crash as soon as it returns. Off, commits survive from the next flush. |
sync_mode | .full | Whether a commit waits for its log record to reach the disk. .normal survives a killed process but can lose the latest commits to a power cut. When the program leaves it unset, LATTICE_SYNC_MODE applies. |
full_fsync | off | On macOS, sync with F_FULLFSYNC so commits survive power loss, at several milliseconds per sync. When the program leaves it unset, LATTICE_FULL_FSYNC applies. |
auto_checkpoint | every 1000 log frames, truncating | How often the log is folded back into the database file. An open option in Zig; elsewhere lattice_set_auto_checkpoint, each binding's set_auto_checkpoint/setAutoCheckpoint/SetAutoCheckpoint, --auto-checkpoint or LATTICE_AUTO_CHECKPOINT_FRAMES. |
Durability and the Log explains each of these and what survives what.
The same options, per language
db = latticedb.Database("graph.lattice", create=True, cache_size_mb=64)
db.open()
const db = new Database('graph.lattice', { create: true, cacheSizeMb: 64 });
db, err := latticedb.Open("graph.lattice", latticedb.OpenOptions{
Create: true,
CacheSizeMB: 64,
})
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
options.create = true;
options.cache_size_mb = 64;
lattice_database* db;
lattice_open_v5("graph.lattice", &options, &db);
The C API grows a new options struct rather than changing the old one, so a
program compiled against an earlier version keeps working. Always start from the
matching _DEFAULT macro rather than zeroing the struct yourself: a zeroed
struct asks for no locking, which is the opposite of what you want.
Where to go next
- Storage Modes — a file, memory, or a block of bytes
- Durability and the Log — what survives what
- Performance Tuning — once it works and you want it faster
Storage Modes
A database can live in three places, and the choice is made by what you pass as the path.
| You want | Open |
|---|---|
| A database on disk | a path: graph.lattice |
| A database that never touches the disk | :memory: |
| A database you already have as bytes | deserialize(blob) |
Everything else behaves identically. The query language, transactions, the write-ahead log, indexes, and serialization all work the same way, because the engine reaches its storage through an interface and only the implementation changes. That sameness is deliberate and worth relying on.
A file
db = latticedb.Database("graph.lattice", create=True)
db.open() # or use it as a context manager: with latticedb.Database(...) as db:
The normal case. One file holds everything: nodes, edges, properties, indexes, and
vectors. Beside it, while the database is open, are the write-ahead log
(-wal) and, when it is open for writing, the flush journal (-journal); see
Durability and the Log.
Do not copy the file while the database is open. The log holds committed
changes that are not in the main file yet, so copying only the main file gives you
a database that opens and then fails on query, and copying both catches them at
different instants. Use backup, or stop the process first. See
Backup and Replication.
Memory
db = latticedb.Database(":memory:")
db.open()
const db = new Database(':memory:');
db, err := latticedb.Open(":memory:", latticedb.OpenOptions{})
lattice exec :memory: --query="CREATE (n:Note {t: 'scratch'}) RETURN n"
Nothing is written to disk and nothing survives closing the handle. Useful for a scratch database, for tests, for a read-only filesystem, and for anywhere writing somebody's data to local disk would be awkward to explain.
Opening :memory: implies creating it, since there is never a previous in-memory
database to find.
Three differences from a file-backed database, all deliberate:
- It disappears when closed. If you want to keep it,
serializeit first. - Nothing locks it. No other process can reach it, so there is nothing to
exclude.
--no-lockmeans nothing here. - The page cache is small and fixed. A cache exists to keep pages off a disk, and a miss against memory is a copy from one part of RAM to another. Measured on a fourteen megabyte database, a 256 KB cache matched a 32 MB one for speed. So peak memory stays close to the size of the database: about 360 KB for a hundred kilobyte database, against the 100 MB cache a file-backed one opened through a binding reserves by default.
The write-ahead log stays on unless you turn it off, as a second file inside the same memory. Turning it off saves its allocations and nothing else changes: transactions work without it, and there was nothing durable to lose. See In-Memory Databases.
Bytes
blob = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
db = latticedb.deserialize(blob)
db.query("CREATE (n:Note {text: 'found something'})")
s3.put_object(Bucket=bucket, Key=key, Body=db.serialize(), IfMatch=etag)
serialize hands back the whole database as bytes, and deserialize opens one
from them. The result runs in memory, so this is the memory mode with a starting
point.
This is what makes it practical to keep a database per case, per tenant, or per document in object storage. It is cheap because a database here is one file, so serializing it is reading that file — there is no container format to maintain.
The bytes are a database file. Write them anywhere and they open, which means you can always inspect one by hand.
Loading without a second copy
By default the bytes are copied. Tell deserialize not to and it points at your
buffer instead, which halves what loading costs:
db = latticedb.deserialize(blob, copy=False)
Each page becomes a copy of its own the first time something writes to it, so reading a database and editing a little of it keeps one copy of nearly all of it. Your buffer is never modified, and the database holds a reference to it for as long as it is open.
Go and Java do not offer this, and that is a language rule rather than a gap in those bindings. Go's own documentation says C code may not keep a pointer into the Go heap after a call returns, and pinning a Java array for the lifetime of a database would hold up the collector for exactly that long.
Two workers, one blob
The failure this pattern invites is not in the database. If two workers read the
same object, change it, and write it back, the second silently erases the first.
That is what IfMatch is doing above: every major provider supports a conditional
write, and the write fails instead of destroying the other worker's changes.
Where to go next
- Opening a Database — the rest of the options
- Backup and Replication — keeping a copy somewhere else
- Portable Databases — how this works underneath, and why
In-Memory Databases
Pass :memory: as the path and the database has no files behind it at all.
db = latticedb.Database(":memory:")
db.open() # or: with latticedb.Database(":memory:") as db:
const db = new Database(':memory:');
db, err := latticedb.Open(":memory:", latticedb.OpenOptions{})
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
lattice_database* db;
lattice_open_v5(":memory:", &options, &db);
lattice exec :memory: --query="CREATE (n:Note {t: 'scratch'}) RETURN n"
Nothing is written to disk and nothing survives closing the handle. You do not
need to pass create: there is never a previous in-memory database to find, so
opening one always makes it.
When you want this
- Trying something out. The fastest way to run a query against a real database with nothing to clean up afterwards.
- Tests. No temporary directories, no files left behind by a failed run, and no chance of two tests sharing a database by accident.
- A database per request. Pull one out of object storage, work on it, hand the bytes back, and never write somebody's data to local disk. See Storage Modes.
- A read-only filesystem, or anywhere a local file would be awkward to explain.
It is a real database
Everything works: transactions, the write-ahead log, indexes, vector search, full-text search, and serialization. The query language does not change, and neither does anything you write against it.
That is not a coincidence. The engine reaches its storage through an interface, and this swaps the implementation rather than adding a second path through the engine. If something works against a file it works here.
import latticedb
with latticedb.Database(":memory:") as db:
with db.write() as txn:
alice = txn.create_node(labels=["Person"], properties={"name": "Alice"})
bob = txn.create_node(labels=["Person"], properties={"name": "Bob"})
txn.create_edge(alice.id, bob.id, "KNOWS")
txn.commit()
rows = db.query("MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.name, b.name")
Three things that differ
It disappears when you close it. If you want to keep it, serialize it first:
blob = db.serialize() # bytes you can write anywhere
db2 = latticedb.deserialize(blob) # and open again later
Nothing locks it. A file-backed database refuses a second process, because two
writers would corrupt it. No other process can reach memory this one owns, so
there is nothing to exclude and every lock succeeds. --no-lock means nothing
here.
The page cache is small and fixed. A cache exists to keep pages off a disk, and a miss against memory is a copy from one part of RAM to another. Measured on a fourteen megabyte database, a 256 KB cache matched a 32 MB one for speed, so an in-memory database caps its cache at 64 pages (256 KB at the default page size), whatever cache size you ask for, and stays close to the size of the data:
| Database | Held in memory |
|---|---|
| 100 KB | about 360 KB |
| 7 MB | about 7.7 MB |
| 18 MB | about 18.7 MB |
A file-backed database opened through the C API or a binding reserves its whole configured cache, 100 MB by default, which is why holding many small in-memory databases at once is practical.
Two in-memory databases are two databases
Each has its own storage, so a shared path name means nothing:
a = latticedb.Database(":memory:")
b = latticedb.Database(":memory:") # a completely separate database
a.open()
b.open()
There is no way to share one between handles, and no equivalent of SQLite's shared cache. If two parts of your program need the same in-memory database, pass the same handle.
The write-ahead log
The log is on unless you turn it off, as for a file. It lives in the same memory as the database and is bounded by automatic checkpointing, so it costs a few megabytes at most.
Turning it off (enable_wal = false) loses an in-memory database nothing it
could keep, since a process holding the only copy loses everything when it dies
anyway. Transactions, rollback and all-or-nothing queries work the same without
it; see Running without the log.
Where to go next
- Storage Modes — files, memory, and bytes side by side
- Opening a Database — the rest of the options
- Backup and Replication — keeping many small databases in object storage
- Portable Databases — how this works underneath, and why it was built this way
Durability and the Log
Every change is written to a log before it reaches the database file. This page is about what that buys you, the settings that control it, and what happens if you turn it off.
For what a transaction guarantees, see Transactions and Durability. For how the log is structured, see Write-Ahead Log.
What committing means
- The change is written to the log.
- The commit record is flushed to disk (in the default sync mode).
- Only then is the change applied in memory and the commit reported as successful.
The database file itself is updated later, in a flush that writes every changed
page at once: at a checkpoint, at close, on an explicit sync(), or early when half
the page cache holds changes. A crash before that loses nothing: the log is replayed
on the next open and the change comes back.
This is why a commit is fast even though it is durable. Appending to a log is one sequential write; updating the database file properly means several scattered ones, and those are batched.
If a commit fails after its commit record may have reached the disk (the flush to
disk itself fails, or applying the change fails), the outcome cannot be taken back.
The handle marks itself failed: it refuses further transactions, sync() and
checkpoints, and writes nothing more to the database file. Close it and open the
database again; recovery replays the log and gives exactly the state it describes.
Files next to the database
| File | What it is |
|---|---|
<db> | The database |
<db>-wal | The write-ahead log. Emptied to a 4 KB header by truncating checkpoints, including the one at a clean close after writes |
<db>-journal | The flush journal. Present while the database is open read-write, empty between flushes, deleted at a clean close |
The journal holds a copy of the pages a flush is writing, written and synced before any of them goes into the database file. If the process or the machine dies part way through the flush, the next open finishes it from the journal, so the database file is always one whole image, never half of one flush and half of another. Leave the journal alone: a journal left after a crash is what the next open needs. A read-only open finishes the flush in memory, without writing; see Opening read-only after a crash.
In-memory databases have neither a journal nor files of their own.
Sync mode
Most of the time a small write transaction takes is the flush of its commit record
to disk. sync_mode decides whether a commit waits for it.
| Setting | Default | What it does |
|---|---|---|
sync_mode | .full | .full flushes the log to disk on every commit. .normal hands the commit record to the operating system and returns. |
With .normal, a transaction that has returned survives the process being killed,
and reaches the disk at the next checkpoint, sync() or flush. A power cut or an
operating-system crash can lose the most recent commits. They are lost from the end
only, the database stays consistent, and everything up to the last sync survives.
What survives what states this exactly.
Set it when you open the database:
| API | Setting |
|---|---|
| Zig | DatabaseConfig.sync_mode = .normal |
| C | lattice_open_options_v5.sync_mode = LATTICE_SYNC_MODE_NORMAL |
| Python | Database(..., sync_mode="normal") |
| TypeScript | new Database(path, { syncMode: 'normal' }) |
| Go | OpenOptions{SyncMode: latticedb.SyncModeNormal} |
| Java | OpenOptions.defaults().syncMode(SyncMode.NORMAL) |
A program that does not set it gets the LATTICE_SYNC_MODE environment variable if
that is set, and .full otherwise. A value the program sets wins over the
environment. The CLI has no flag for it, so there the variable is the way to set it:
LATTICE_SYNC_MODE=normal # or full; case does not matter, other values are ignored
Full fsync on macOS
On macOS, fsync returns once the drive has the data, possibly only in the drive's
own cache. A commit there survives a process or operating-system crash but not
necessarily a power cut, and the ordering the flush journal relies on is not assured
either.
| Setting | Default | What it does |
|---|---|---|
full_fsync | off | On macOS, every sync uses fcntl(F_FULLFSYNC), which asks the drive to flush its cache. No effect on other platforms, where fsync already asks for that. |
It is off by default because it makes every sync, and so every commit in the
default sync mode, several milliseconds slower. Turn it on if the database must
survive power loss on a Mac: full_fsync = true in Zig,
LATTICE_FULL_FSYNC_ON in the C API's lattice_open_options_v5.full_fsync,
full_fsync=True in Python, fullFsync: true in TypeScript,
FullFsync: latticedb.FullFsyncOn in Go, .fullFsync(true) in Java. As with
sync_mode, a program that leaves it unset gets the environment variable, and the
CLI is set only through it:
LATTICE_FULL_FSYNC=1 # or true; 0 or false turns it off; other values are ignored
Environment variables
The engine reads these when a database is opened, whatever API opened it. Each applies only when the program did not set the option itself.
| Variable | Values | Default | Effect |
|---|---|---|---|
LATTICE_SYNC_MODE | full, normal | unset (full) | Whether a commit waits for the disk; see Sync mode |
LATTICE_FULL_FSYNC | 1/true, 0/false | unset (off) | F_FULLFSYNC on macOS; see Full fsync on macOS |
LATTICE_BUFFER_POOL_MB | a positive integer | unset | Page cache size where the program sets none (an explicit size wins); see Opening a Database |
LATTICE_AUTO_CHECKPOINT_FRAMES | a non-negative integer | unset (1000) | Log frames a commit waits for before checkpointing, 0 for none, in the C API, the bindings and the CLI; see Checkpointing |
Running without the log
enable_wal = false means one thing: nothing is logged. Everything else works as it
does with a log. Transactions begin, commit and roll back; a writing query outside
a transaction gets one of its own and is all or nothing; one writer at a time;
readers keep their snapshot; property indexes, full-text search, vectors, streams
and the changefeed are updated at commit and untouched by a rollback. There is no
-wal file.
What you give up is durability between flushes. A commit changes pages in memory,
and they reach the file only when they are flushed: at close, at the end of a
commit once half the page cache holds changes, or, in the Zig API, on sync().
A flush never happens in the middle of applying a transaction, and each flush
goes through the journal, so the file always holds a whole number of
transactions.
| Event | What a database without a log keeps |
|---|---|
| Process killed, or the machine loses power | The transactions up to some point at or after the last close, or Zig sync(), that returned. Never part of one. Commits after that point may be lost, from the end only. |
| A commit fails while it is being applied (the disk is full, say) | The handle marks itself failed and writes nothing more. Reopened, the database holds the state of the last flush: that commit and every one since are lost. |
| Clean close | Everything. |
After anything you could not redo, call sync() in Zig. The C API and the
bindings have no call that flushes without closing (checkpoint does nothing
without a log), so there close the database, and open it again to go on. The
power-loss case assumes the same of the storage as
What survives what does.
Two costs come with it. A transaction's changed pages stay in memory until the whole
transaction has been applied, so one very large transaction can hold the page cache
above its configured size until it commits. And in the Zig API, a write passed a
null transaction is applied as it is made, with or without a log, and is never
logged; without a log that makes no difference to what survives, but it is not part
of any transaction, so it does not appear in the changefeed.
Bulk loading
A load you can run again from its source does not need the log: if it is interrupted, delete the file and start over. For such a load:
- open with
enable_wal = false; - set
changefeed_retentiontooffif nothing will read the load's changes from the changefeed (the policy is kept in the file; open withallafterwards to record changes from then on); - give it a page cache about twice the size the file will reach;
- write in transactions of some thousands of rows, then close (or, in Zig,
sync()).
The cache matters more than the log. A flush writes each changed page twice, once to the journal and once in place, and happens whenever half the cache holds changes. With a small cache and writes spread over the whole graph, the same pages are changed and written again flush after flush; once half the cache holds what the load changes, each page is written about twice in all.
Loading 1,000,000 nodes and 2,000,000 relationships between random pairs of them, through the Zig API in transactions of 10,000 (release build, a busy macOS machine, two runs each; the Zig API's default cache here is 28 MB, the bindings' 100 MB):
| Log | Changefeed | Cache | Time | Written to disk | File |
|---|---|---|---|---|---|
on, normal sync | all | default | 75–76 s | 66 GB | 540 MB |
| off | all | default | 39–41 s | 33 GB | 540 MB |
| off | off | default | 36–38 s | 33 GB | 378 MB |
on, normal sync | all | 256 MB | 27–29 s | 20 GB | 540 MB |
| off | all | 256 MB | 21–23 s | 13 GB | 540 MB |
on, normal sync | all | 1 GB | 22–25 s | 13 GB | 540 MB |
on, normal sync | off | 1 GB | 16–17 s | 10 GB | 378 MB |
| off | all | 1 GB | 13–15 s | 2.1 GB | 540 MB |
| off | off | 1 GB | 9–10 s | 1.1 GB | 378 MB |
Peak memory was the cache plus 25 to 80 MB. With the log off, the
changefeed off and a 1 GB cache, transactions cost no more than the same load
written directly with a null transaction (10–11 s), and they still roll back.
The published figures for this load are measured through the C API on a quiet
machine, where the default cache is 100 MB and the default sync mode full:
34.4 s with the defaults and 7.9 s with the last row's settings. See
Benchmarks.
Checkpointing
The log grows as you write. A checkpoint folds it back into the database file and resets it, which is what stops it growing forever.
This happens on its own, after a commit, once the log holds enough frames. Each write transaction adds at least one frame, so with the defaults that is at most every thousand write transactions; single-node commits reach it about once in a few hundred. Open readers do not hold it back. It is skipped only while an open transaction already has records in the log (one whose commit failed part way and has not been rolled back yet), and the next commit tries again.
The automatic checkpoint runs inside the commit that triggers it, not in the background, so that one commit takes longer. Of 20,000 single-node commits through the C API with the default settings (see Benchmarks), the median took 44 µs and the 99.9th percentile 1.4 ms, which is where the commits that ran a checkpoint, and the disk's own stalls, show; the slowest single commit ranged from 2 ms to over 200 ms from run to run, as it did in 0.16.0. If a pause of that size matters to you, set a larger or smaller interval, or turn the automatic checkpoint off and run checkpoints at moments you choose. A larger interval means fewer pauses, each longer, a longer log on disk and more to replay after a crash; a smaller one means shorter pauses, more often.
auto_checkpoint decides when. Zig sets it in DatabaseConfig, or on an open
database with Database.setAutoCheckpoint; C with
lattice_set_auto_checkpoint(db, max_wal_frames, min_interval_ms); the bindings
with set_auto_checkpoint (Python), setAutoCheckpoint (TypeScript, Java) and
SetAutoCheckpoint (Go); the CLI with --auto-checkpoint=<frames>. Where none of
those is used, the C API, the bindings and the CLI take the frame count from
LATTICE_AUTO_CHECKPOINT_FRAMES if it is set:
| Setting | Default | What it does |
|---|---|---|
max_wal_frames | 1000 | Frames written before a checkpoint is considered. |
min_interval_ns | 0 | Shortest gap between two checkpoints. |
mode | truncate | Only truncate resets the log, so it is the only mode that bounds its size. |
A frame count of 0 turns the checkpoints inside commits off, which is worth doing if
you want to choose the moment rather than have it land mid-request; the database
still checkpoints at open and close. From Zig, opening with auto_checkpoint set to
null also turns off the checkpoints at open and close described below.
The minimum interval defaults to zero deliberately. Under truncate the frame
threshold already limits the rate, because a checkpoint resets the frame count and
the next one cannot happen until another thousand frames are written. A time gate
on top of that does not prevent thrash; it just lets the log grow without limit
during a burst of writes, which is the thing this is meant to stop.
A checkpoint also runs when a database is opened, after recovery, and when it is closed, through any API or the CLI, if the log holds changes since its last checkpoint. A cleanly closed database therefore leaves no journal and nothing in the log to replay. A log that ends at a checkpoint is left as it is, which matters for replication: see Backup and Replication.
Checkpointing by hand
lattice checkpoint social.lattice
You mostly do not need this. It is worth running before copying a database file,
so the copy is complete on its own, and on a database that has been open a very
long time under heavy writes if you would rather pick the moment. A program
checkpoints its open database with lattice_checkpoint(db, mode, &stats) in C,
checkpoint() in Python, TypeScript and Java, Checkpoint in Go, or
Database.checkpoint in Zig.
This is not compact. Checkpointing shrinks the log, not the database file.
What survives what
The guarantee after a power cut, assuming the storage honours fsync (and
F_FULLFSYNC on macOS when full_fsync is on) and that a completed sync is not
later undone or damaged by the device:
sync_mode = .full(the default). A transaction whose commit call has returned survives. A transaction whose commit had not returned is either wholly there or wholly absent. After recovery the database holds exactly the transactions committed up to some point at or after the last acknowledged one, with every index consistent with the graph.sync_mode = .normal. The log is handed to the operating system at commit, and synced at checkpoints, onsync(), when a full cache forces a flush, and at close. After a power cut the database holds exactly the transactions up to some point no earlier than the last log sync: a whole number of transactions, none applied in part. Commits acknowledged after the last log sync may be lost. A process kill without a power cut loses nothing acknowledged.- Both modes. A crash during recovery, a second power cut included, changes
nothing: the next recovery reaches the same state. A log damaged where it had
already been synced refuses to open (
InvalidDatabase,LATTICE_ERROR_CORRUPTIONin the C API) rather than silently dropping the commits in it. The one exception is the newest sync batch: damage there that no later frame vouches for cannot be told apart from a write the power cut tore, and is cut off as a torn tail. See Write-Ahead Log for how the log tells them apart.
These are checked by a power-loss simulation in the crash suite, which cuts the power at every sync point of a random workload; see Running Tests.
| Event | What happens |
|---|---|
| Process crashes or is killed | Every commit that returned is there on the next open, in either sync mode. A commit that was running is either all there or not at all. |
Machine loses power, sync_mode = .full, Linux | Every commit that returned is there, as above. |
Machine loses power, sync_mode = .full, macOS | The same only with full_fsync on. Without it, nothing is guaranteed. |
Machine loses power, sync_mode = .normal | Commits since the last log sync may be lost, from the end only. |
| Database file is copied while open | Broken. The log holds committed changes the file does not have. Use backup. |
The -wal or -journal file is deleted after a crash | Committed changes not yet in the file are gone, and an interrupted flush cannot be finished. Leave both in place. |
| An in-memory database's process exits | Everything is gone. That is what in-memory means. |
The copy row is the one that catches people, and it fails silently at copy time — you find out at restore. Backup and Replication covers the tools that do it correctly.
Opening read-only after a crash
A read-only open recovers a crashed database in memory. When the log holds frames or the journal holds a flush, the open reads the files without writing to them, finishes the flush and replays the log exactly as a read-write open would, and keeps every page that recovery changes in memory. The handle then shows every committed transaction, and nothing on disk changes; the next read-write open recovers the files itself. A database with an empty log and no journal opens read-only as it always did, with nothing extra in memory.
The memory this takes is bounded at 64 MB plus four times the size of the log and
the journal. A recovery that would need more fails the open with BufferPoolFull
(LATTICE_ERROR_FULL in the C API); open the database read-write once to recover
it on disk. A log damaged in its synced part refuses a read-only open as it refuses
a read-write one.
The CLI's read-only commands (count, info, labels, export and the rest) open
this way. lattice check reads the database file's pages, not the log, and
finishes an interrupted flush from the journal in memory before it checks them, so
it checks the file as the journal leaves it, without changing it.
Where to go next
- Transactions and Durability — what a transaction guarantees and the one-writer rule
- Backup and Replication — keeping a copy that is actually usable
- Write-Ahead Log — the format and the recovery path
Building a RAG System
This guide walks through building a Retrieval-Augmented Generation (RAG) system with LatticeDB. We'll chunk documents, generate embeddings, store them with graph relationships, and query using vector search combined with graph traversal.
Architecture
A typical RAG system with LatticeDB:
- Ingest — Split documents into chunks, generate embeddings, store in the graph
- Link — Create edges between chunks, documents, authors, topics
- Retrieve — Vector search finds relevant chunks, graph traversal gathers context
- Generate — Pass retrieved context to an LLM
Step 1: Set Up the Database
from latticedb import Database
from latticedb.embedding import hash_embed
db = Database(
"rag.db",
create=True,
enable_vectors=True,
vector_dimensions=128, # Match your embedding model's output
)
db.open()
# Declare the full-text index once, before loading text into Chunk.text
db.create_node_fts_index("Chunk", "text")
For production, use a real embedding model via the HTTP client:
from latticedb.embedding import EmbeddingClient
# The endpoint is the full URL the client POSTs to
client = EmbeddingClient(
"http://localhost:11434/api/embeddings",
model="nomic-embed-text",
)
Step 2: Ingest Documents
Split documents into chunks and store them with graph relationships:
def ingest_document(db, title, author_name, chunks):
with db.write() as txn:
# Create or find the author
doc = txn.create_node(
labels=["Document"],
properties={"title": title},
)
author = txn.create_node(
labels=["Person"],
properties={"name": author_name},
)
txn.create_edge(doc.id, author.id, "AUTHORED_BY")
# Create chunks with embeddings
prev_chunk = None
for i, text in enumerate(chunks):
chunk = txn.create_node(
labels=["Chunk"],
properties={"text": text, "position": i},
)
# Store embedding
embedding = hash_embed(text, dimensions=128)
txn.set_vector(chunk.id, "embedding", embedding)
# Link chunk to document
txn.create_edge(chunk.id, doc.id, "PART_OF")
# Link sequential chunks
if prev_chunk is not None:
txn.create_edge(prev_chunk.id, chunk.id, "NEXT")
prev_chunk = chunk
txn.commit()
return doc
doc = ingest_document(
db,
"Attention Is All You Need",
"Vaswani",
[
"The transformer architecture uses self-attention.",
"Self-attention relates every position in a sequence to every other.",
"Multi-head attention runs several attention functions in parallel.",
],
)
Step 3: Add Topic Links
Enrich the graph with topic relationships:
with db.write() as txn:
ml_topic = txn.create_node(
labels=["Topic"],
properties={"name": "Machine Learning"},
)
# Link documents to topics
txn.create_edge(doc.id, ml_topic.id, "ABOUT")
txn.commit()
Step 4: Query — Vector Search + Graph Context
The key advantage of LatticeDB: retrieve by similarity, then traverse the graph for additional context.
def retrieve_context(db, query_text, k=5):
"""Retrieve relevant chunks with their surrounding context."""
query_vec = hash_embed(query_text, dimensions=128)
# Find similar chunks and traverse to their documents and authors
results = db.query("""
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query < 0.5
RETURN chunk.text, doc.title, author.name
ORDER BY chunk.embedding <=> $query
LIMIT $k
""", parameters={"query": query_vec, "k": k})
return results
Retrieve with Neighboring Chunks
Get surrounding chunks for more context:
query_vec = hash_embed("How does self-attention work?", dimensions=128)
results = db.query("""
MATCH (prev:Chunk)-[:NEXT]->(chunk:Chunk)-[:PART_OF]->(doc:Document)
WHERE chunk.embedding <=> $query < 0.5
RETURN prev.text, chunk.text, doc.title
ORDER BY chunk.embedding <=> $query
LIMIT 5
""", parameters={"query": query_vec})
The path can also be written in two MATCH clauses that share chunk; a node
variable bound in one MATCH stands for the same node in the next.
Combine Vector and Full-Text Search
results = db.query("""
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)
WHERE chunk.embedding <=> $query < 0.5
AND chunk.text @@ $keywords
RETURN chunk.text, doc.title
ORDER BY chunk.embedding <=> $query
LIMIT 10
""", parameters={
"query": query_vec,
"keywords": "transformer attention",
})
Step 5: Pass to LLM
context = retrieve_context(db, "How does self-attention work?")
# Build prompt with retrieved context
chunks = [f"[{r['doc.title']}] {r['chunk.text']}" for r in context]
prompt = f"""Answer the question based on the following context:
{chr(10).join(chunks)}
Question: How does self-attention work?"""
# Pass to your LLM of choice
# response = llm.generate(prompt)
Batch Loading
For large datasets, batch_insert_vectors creates a node and stores its vector
for every row in one call:
import numpy as np
all_chunks = ["first chunk of text", "second chunk of text"] # your chunk texts
with db.write() as txn:
# Insert every chunk at once
vectors = np.array([hash_embed(text, 128) for text in all_chunks], dtype=np.float32)
node_ids = txn.batch_insert_vectors("Chunk", vectors)
# Set properties and create edges afterward
for node_id, text in zip(node_ids, all_chunks):
txn.set_property(node_id, "text", text)
txn.commit()
Performance Tips
- Use
batch_insert_vectors()for bulk loading — it saves one binding call per node; each vector is still inserted into the HNSW index individually - Set
ef_searchbased on your recall requirements: the default, 64, measured about 98% recall@10 at 100K vectors and 93–96% at 1M; 128 brought 1M to about 98% (see Benchmarks) - End a retrieval query as above, with
ORDER BYthe same<=>distance as theWHEREand aLIMIT: the search then stops once it has enough rows, rather than finding every chunk under the threshold and sorting them. To return the distance, write it in theRETURNthe same way (chunk.embedding <=> $query AS dist) and the measured value is reused - Use
cache_size_mbto control memory usage; once the file outgrows the cache (about 100K 128-d vectors at the default 100 MB), vector inserts and searches slow down several times over, so size it to the file for large indexes - Declare a full-text index only over properties you actually search; each one costs write time
- Use parameters (
$name) so the query text stays the same and its parsed form is reused from the query cache
Knowledge Graph Modeling
This guide covers data modeling patterns for knowledge graphs in LatticeDB.
Basic Patterns
Entities and Relationships
Model real-world entities as nodes and their relationships as edges:
with db.write() as txn:
alice = txn.create_node(labels=["Person"], properties={"name": "Alice"})
company = txn.create_node(labels=["Company"], properties={"name": "Acme Corp"})
txn.create_edge(alice.id, company.id, "WORKS_AT")
txn.commit()
Labels as Types
Use labels to categorize nodes. A node can have multiple labels:
txn.create_node(labels=["Person", "Employee", "Manager"], properties={"name": "Alice"})
Query by label:
MATCH (m:Manager) RETURN m.name
Document Graph
A common pattern for document management:
Document -[:AUTHORED_BY]-> Person
Document -[:ABOUT]-> Topic
Chunk -[:PART_OF]-> Document
Chunk -[:NEXT]-> Chunk
with db.write() as txn:
doc = txn.create_node(labels=["Document"], properties={"title": "Paper Title"})
author = txn.create_node(labels=["Person"], properties={"name": "Alice"})
topic = txn.create_node(labels=["Topic"], properties={"name": "Machine Learning"})
txn.create_edge(doc.id, author.id, "AUTHORED_BY")
txn.create_edge(doc.id, topic.id, "ABOUT")
# Create a chain of chunks
chunk_texts = ["First passage...", "Second passage...", "Third passage..."]
chunks = []
for i, text in enumerate(chunk_texts):
chunk = txn.create_node(labels=["Chunk"], properties={"text": text, "position": i})
txn.create_edge(chunk.id, doc.id, "PART_OF")
if chunks:
txn.create_edge(chunks[-1].id, chunk.id, "NEXT")
chunks.append(chunk)
txn.commit()
Multi-Hop Queries
Finding Collaborators
// Direct collaborators
MATCH (a:Person {name: "Alice"})-[:COLLABORATES_WITH]->(b:Person)
RETURN b.name
// Collaborators of collaborators
MATCH (a:Person {name: "Alice"})-[:COLLABORATES_WITH*2]->(c:Person)
RETURN DISTINCT c.name
Path Queries
// How are two people connected?
MATCH (a:Person {name: "Alice"})-[*1..4]->(b:Person {name: "Dave"})
RETURN a.name, b.name
Aggregating Over Relationships
// Authors with the most documents about ML
MATCH (p:Person)<-[:AUTHORED_BY]-(d:Document)-[:ABOUT]->(t:Topic {name: "Machine Learning"})
RETURN p.name, count(d) AS papers
ORDER BY papers DESC
LIMIT 10
Social Network
Person -[:KNOWS]-> Person
Person -[:FOLLOWS]-> Person
Person -[:POSTED]-> Post
Post -[:TAGGED]-> Topic
// Find people who share Alice's interests
MATCH (me:Person {name: "Alice"})-[:FOLLOWS]->(topic:Topic)<-[:FOLLOWS]-(other:Person)
RETURN other.name, collect(topic.name) AS shared_interests
Naming a variable again, in a second comma-separated pattern or a later MATCH,
means the same node, so "friends of Alice who also share her interests" is one
query:
MATCH (me:Person {name: "Alice"})-[:KNOWS]->(friend:Person),
(me)-[:FOLLOWS]->(topic:Topic)<-[:FOLLOWS]-(friend)
RETURN friend.name, collect(topic.name) AS shared_interests
Modeling Tips
- Use descriptive edge types.
AUTHORED_BYis more useful thanRELATED_TO. - Keep properties simple. Store complex data as separate nodes with edges rather than large property values.
- Use labels for querying. Labels enable efficient scans via the label index.
- Model for your queries. Think about what traversals you need and structure edges accordingly.
- Use MERGE for idempotent imports. When loading data from multiple sources,
MERGEprevents duplicate nodes.
Working with Embeddings
LatticeDB supports storing and searching vector embeddings on nodes. This guide covers the embedding options and how to use them.
Overview
To use embeddings:
- Enable vector storage when creating the database
- Generate embeddings (built-in hash or external service)
- Attach embeddings to nodes
- Search by similarity
Enabling Vector Storage
from latticedb import Database
db = Database(
"mydb.db",
create=True,
enable_vectors=True,
vector_dimensions=128, # Must match your embedding dimensions
vector_metric="cosine", # or "euclidean" or "dot_product"; fixed once created
)
db.open()
const db = new Database("mydb.db", {
create: true,
enableVectors: true,
vectorDimensions: 128,
});
await db.open();
The vector index is created with the database, and its configuration (dimensions,
metric, vector_m, vector_ef_construction) is stored in the file. Later opens
need no vector options: Database("mydb.db") opens the index as it was created,
also after a crash. An option you do pass must match the file, or the open fails
with a configuration-mismatch error (LatticeConfigMismatchError in Python). The
TypeScript options are vectorMetric, vectorM and vectorEfConstruction; the
CLI's are lattice create --vector-metric=cosine|euclidean|dot_product --vector-m=<n> --vector-ef-construction=<n>.
The metric decides what a distance means, and smaller is always nearer: cosine distance (1 minus cosine similarity, the default and the usual choice for text embeddings), Euclidean (L2) distance, or the negated dot product. It cannot be changed once the index exists; to change it, export the database and import it into one created with the new metric. See Distance Metric.
A node holds one vector, and Cypher reads it as n.embedding. set_vector takes
a key argument, which must be "embedding" (an empty key also works); any other
key is rejected with an unsupported-operation error rather than stored under that
name. Setting a vector on a node that already has one replaces it.
Every component must be a finite number: a vector containing NaN or infinity is rejected with an invalid-argument error, both when stored and when used as a search query. Under the cosine metric the database keeps only the normalised (unit-length) copy of a vector, so a committed vector reads back normalised. Under the Euclidean and dot-product metrics vectors are kept as given.
Hash Embeddings (Built-in)
hash_embed generates deterministic embeddings from text without an external service. It uses feature hashing to map text tokens to a fixed-dimension vector.
When to use: Testing, prototyping, or when keyword-level similarity is sufficient.
Python:
from latticedb.embedding import hash_embed
vec = hash_embed("hello world", dimensions=128)
# Returns a numpy array of shape (128,)
TypeScript:
import { hashEmbed } from "@hajewski/latticedb/embedding";
const vec = hashEmbed("hello world", 128);
// Returns a Float32Array of length 128
HTTP Embedding Client
For production-quality semantic embeddings, use the HTTP client to connect to an embedding service.
The endpoint is the full URL the client POSTs to; nothing is appended to it. Give
Ollama's /api/embeddings path or OpenAI's /v1/embeddings path, not the
server's base URL: given http://localhost:11434 alone, the client POSTs to /
on that server, which does not serve embeddings, and embed fails. The client
copies the endpoint, model and API key when it is created.
The timeout setting (timeout_ms in Python and C, timeoutMs in TypeScript and
Java, TimeoutMS in Go; 30 seconds by default, or when set to 0) is how long the
client waits for the server to start answering. A request that gets no response in that time fails with an I/O
error. Connecting, and reading the rest of a response that has begun, are not
bounded by it, and it is not applied on Windows.
Ollama
from latticedb.embedding import EmbeddingClient
with EmbeddingClient("http://localhost:11434/api/embeddings") as client:
vec = client.embed("hello world")
import { EmbeddingClient } from "@hajewski/latticedb/embedding";
const client = new EmbeddingClient({
endpoint: "http://localhost:11434/api/embeddings",
});
const vec = client.embed("hello world");
client.close();
OpenAI
from latticedb.embedding import EmbeddingClient, EmbeddingApiFormat
with EmbeddingClient(
"https://api.openai.com/v1/embeddings",
model="text-embedding-3-small",
api_format=EmbeddingApiFormat.OPENAI,
api_key="sk-...",
) as client:
vec = client.embed("hello world")
import { EmbeddingClient, EmbeddingApiFormat } from "@hajewski/latticedb/embedding";
const client = new EmbeddingClient({
endpoint: "https://api.openai.com/v1/embeddings",
model: "text-embedding-3-small",
apiFormat: EmbeddingApiFormat.OpenAI,
apiKey: "sk-...",
});
const vec = client.embed("hello world");
client.close();
Storing Embeddings
Attach a vector to a node within a write transaction:
from latticedb.embedding import hash_embed
with db.write() as txn:
node = txn.create_node(labels=["Chunk"], properties={"text": "some text"})
embedding = hash_embed("some text", dimensions=128)
txn.set_vector(node.id, "embedding", embedding)
txn.commit()
Searching
Programmatic API
query_vec = hash_embed("search query", dimensions=128)
results = db.vector_search(query_vec, k=10, ef_search=64)
for r in results:
print(f"Node {r.node_id}: distance={r.distance:.4f}")
Cypher
MATCH (n:Chunk)
WHERE n.embedding <=> $query < 0.5
RETURN n.text
ORDER BY n.embedding <=> $query
LIMIT 10
In Cypher, <=> in WHERE searches among the nodes your pattern matches: a
threshold query returns every Chunk within the distance, however many there are
and whatever other nodes are nearer, and a LIMIT stops the search once it has
enough, also when an ORDER BY on the same distance comes between them. For the
nearest k over the whole database, use vector_search. See
Vector Search in Cypher.
Batch Insert
For bulk loading, batch_insert_vectors creates a node and stores its vector for
every row in one call. It saves one binding call per node; each vector still goes
into the HNSW index individually:
import numpy as np
with db.write() as txn:
vectors = np.random.rand(10000, 128).astype(np.float32)
node_ids = txn.batch_insert_vectors("Document", vectors)
txn.commit()
Choosing Dimensions
The vector_dimensions parameter is set when the database is created, is stored in the file, and must match the embedding model output:
| Model | Dimensions |
|---|---|
hash_embed (built-in) | Configurable (default 128) |
text-embedding-3-small (OpenAI) | 1536 |
text-embedding-3-large (OpenAI) | 3072 |
nomic-embed-text (Ollama) | 768 |
mxbai-embed-large (Ollama) | 1024 |
Higher dimensions capture more semantic nuance but use more memory and slow down search.
Full-Text Search
LatticeDB includes a BM25-scored inverted index for full-text search. This guide covers indexing, searching, and fuzzy matching.
How It Works
LatticeDB's full-text search uses:
- Tokenization — text is split into words: runs of letters, digits, combining
marks and
_, in any script. Spaces, punctuation, symbols and emoji separate words, and so do bytes that are not valid UTF-8. Chinese (Han) characters and hiragana are a word each, because those scripts do not put spaces between words. Each word is lowercased (Latin, Greek, Cyrillic and Armenian letters) and its accents are folded, so "Café", "cafe" and "CAFÉ" are one term and "Straße" is stored as "strasse". Single ASCII characters, words longer than 64 bytes and English stop words ("the", "and", …) are dropped. A query goes through the same steps, so"Müller"and"muller"find the same documents. - No stemming — "run" does not find "running". The engine has an English stemmer, but the C API, the bindings and Cypher cannot turn it on.
- Inverted index — maps terms to the nodes containing them
- BM25 scoring — ranks results by relevance considering term frequency, document frequency, and document length
Indexes built by 0.16.0 or earlier
The tokenizer above applies to indexes that are new, or empty, in this release.
An index that already held documents keeps the tokenizer it was built with,
because its stored terms came from it: only ASCII letters, digits and _ are
word characters, so "Müller" was stored as "ller" (and matches "Zöller"), "café"
as "caf", and Cyrillic or CJK text produced no terms at all. Accents are not
folded in such an index. Searches against it keep working as they did.
Each index records how it analyses text when its first document goes in, and an old index has no record. It switches to the new tokenizer only when every document has left it. There is no reindex command; to rebuild an old index with the new tokenizer, drop it and declare it again, which reads the property from every node afresh:
db.drop_node_fts_index("Document", "text")
db.create_node_fts_index("Document", "text")
Opening a database whose log has to be replayed after a crash also rebuilds every full-text index, and a rebuilt index takes the new tokenizer.
With the changefeed on, 0.16.0 cannot open a database this release has written to at all: see Opening with 0.16.0. With the changefeed off, going back to 0.16.0 works for a database whose full-text indexes do not store word positions (indexes 0.16.0 built, and indexes this release has only declared), but 0.16.0 splits non-ASCII words its old way, so it will not find words with non-ASCII letters that this release indexed. ASCII text is unaffected. Once an index that stores positions (every index this release fills) holds a document, the file asks for this release or later whatever the changefeed setting, and 0.16.0 refuses to open it: 0.16.0 would append entries without their positions to pages whose entries carry them, and damage the index.
Declaring an Index
An index covers one label and one property, and the property is where the text lives. Declare it once; writing that property keeps the index current, the same way a property index stays current.
Declaring an index reads the property from every node already carrying the label, so adding one to a database full of documents makes them searchable immediately.
If you are coming from an earlier version, see Migrating to Per-Property FTS.
db.create_node_fts_index("Document", "text")
with db.write() as txn:
node = txn.create_node(labels=["Document"], properties={
"title": "My Doc",
"text": "The quick brown fox jumps over the lazy dog",
})
txn.commit()
await db.createNodeFtsIndex("Document", "text");
await db.write(async (txn) => {
const node = await txn.createNode({
labels: ["Document"],
properties: {
title: "My Doc",
text: "The quick brown fox jumps over the lazy dog",
},
});
});
Searching
Programmatic API
results = db.fts_search("Document", "text", "quick fox", limit=10)
for r in results:
print(f"Node {r.node_id}: score={r.score:.4f}")
const results = await db.ftsSearch("Document", "text", "quick fox", { limit: 10 });
for (const r of results) {
console.log(`Node ${r.nodeId}: score=${r.score.toFixed(4)}`);
}
Cypher
MATCH (d:Document)
WHERE d.text @@ "quick fox"
RETURN d.title
@@ searches the index declared for that label and property — here
Document.text. The variable needs a label in the pattern, and if no index is
declared for the label and property you name, the query fails with "No full-text
index is declared for Document.title" rather than returning nothing.
score(d) returns the BM25 score the search gave d, the same number
fts_search reports, so a query can rank by it or return it:
MATCH (d:Document)
WHERE d.text @@ "quick fox"
RETURN d.title, score(d) AS score
ORDER BY score DESC
LIMIT 10
It is null for a node no @@ search scored. See
Reading the score.
A query with several words matches documents containing every word, so a word no
document contains gives no results: "apple zebra" finds nothing if no document
has "zebra". Every match is scored, and the best limit are returned.
Query syntax
The same syntax works in @@, fts_search and fts_search_fuzzy:
| Query | Matches |
|---|---|
quick fox | both words |
quick OR fox | either; OR must be in capitals. a b OR c is (a b) OR c |
fox -dog | "fox" and not "dog"; -"lazy dog" excludes a phrase |
"quick brown" | the words next to each other, in that order |
data* | any word starting with "data" (at least two characters before the *) |
databse~, databse~1 | words within two edits, or one (~0: exactly; more than two counts as two); words under four characters match exactly |
\-fox, fox\*, fox\~, \" | a backslash makes the next character literal; inside quotes nothing is an operator |
Words go through the same tokenizer as the indexed text, so punctuation separates
words (well-known asks for "well" and "known"), and stop words ask for nothing. A query
made only of exclusions (-dog) is an error rather than "everything except dog":
in Cypher write NOT d.text @@ "dog". There are no parentheses.
A Cypher string reads a backslash as the start of an escape, so to pass one
through to the search write it twice: d.text @@ '\\-fox' searches for the
word "fox" written -fox, where '\-fox' arrives as -fox, an exclusion.
Phrases need word positions, which indexes created in 0.17.0 or later store; they cost a few percent more space (about 1% at 100,000 documents). An index created earlier has none, and a phrase query against it is an error rather than a search for the words in any order ("Full-text query '"quick brown"' has a phrase, and the index on Document.text stores no word positions to match one"); drop and re-create the index to store them.
Releases before 0.17.0 treated quotes, -, * and ~ as punctuation and OR as
a stop word, so fox -quick asked for both words and cats OR dogs for both.
Fuzzy Search
Fuzzy search tolerates typos using Levenshtein edit distance:
# Finds "machine learning" despite typos
results = db.fts_search_fuzzy("Document", "text", "machin lerning", limit=10)
Controlling Sensitivity
results = db.fts_search_fuzzy(
"Document",
"text",
"machne",
limit=10,
max_distance=2, # Max edit distance (default: 2)
min_term_length=4, # Min term length for fuzzy matching (default: 4)
)
const results = await db.ftsSearchFuzzy("Document", "text", "machne", {
limit: 10,
maxDistance: 2,
minTermLength: 4,
});
- max_distance — maximum Levenshtein edit distance. Higher values find more matches but may include irrelevant results.
- min_term_length — minimum term length to apply fuzzy matching. Shorter terms are matched exactly.
Unlike plain search, fuzzy search matches a document that contains any of the query words or a near spelling of one. Each query word scores a document by its best-matching spelling in that document, and the words' scores add up, so a document matching more of the query ranks higher. A spelling further from the query word keeps less of its score: with a maximum of two edits, one edit keeps 89% and two edits 56%.
Combining with Vector Search
Use both search modes in a single Cypher query for hybrid retrieval:
MATCH (chunk:Chunk)
WHERE chunk.embedding <=> $query < 0.5
AND chunk.text @@ "neural networks"
RETURN chunk.text
ORDER BY chunk.embedding <=> $query
LIMIT 10
Performance
Top-10 BM25 searches through the C API, on synthetic 50-word documents (0.17.0, Apple M5; Benchmarks has the method):
| Documents | One word: p50 / p99 | Two words: p50 / p99 |
|---|---|---|
| 10,000 | 8.5 us / 103 us | 9.0 us / 70 us |
| 100,000 | 104 us / 1.2 ms | 78 us / 0.70 ms |
Ranking reads every posting of the query's words, so a search costs in proportion to how many documents contain them; the p99 is the most common words.
Write the query so it can use the index
A @@ predicate reads the index directly when it is the whole WHERE clause or a
branch of an AND. The query never looks at documents the index did not name, so
a selective search costs about the same on eight thousand documents as on five
hundred:
MATCH (d:Document) WHERE d.body @@ "sourdough" RETURN d.title
MATCH (d:Document) WHERE d.body @@ "sourdough" AND d.year > 2020 RETURN d.title
Under an OR it cannot. The other branch may match documents the index never
names, so the query has to look at every node carrying the label:
MATCH (d:Document) WHERE d.body @@ "sourdough" OR d.year > 2020 RETURN d.title
That is correct, just more work. Two @@ predicates joined by OR on the same
variable are fine — those are planned as one pass over both indexes:
MATCH (d:Document) WHERE d.title @@ "sourdough" OR d.body @@ "sourdough" RETURN d.title
If an OR against a non-text condition is slow on a large label, the usual fix is
to split it with UNION, so each side can use the index that suits it:
MATCH (d:Document) WHERE d.body @@ "sourdough" RETURN d.title AS title
UNION
MATCH (d:Document) WHERE d.year > 2020 RETURN d.title AS title
Asking for the best few
When @@ is the whole WHERE and the RETURN has a LIMIT, with no ORDER BY
or with ORDER BY score(d) DESC, the search keeps only the best SKIP + LIMIT
matches as it scores them instead of producing every match and sorting it:
MATCH (d:Document) WHERE d.text @@ "quick fox"
RETURN d.title, score(d) AS s ORDER BY s DESC LIMIT 10
With a word every one of 50,000 documents contains, LIMIT 10 this way takes
about 6 ms, where sorting every match took about 19 ms. Another ORDER BY,
DISTINCT, an aggregation, or another condition beside the @@ brings back the
full sort; the answer is the same either way.
Rare terms cost less than common ones
Scoring reads the posting list for each term, so a term appearing in most documents costs proportionally more than one appearing in a handful. That is inherent to the index rather than something to tune around, and it is why a search for a distinctive word is far quicker than one for a word your whole corpus shares.
Migrating to Per-Property Full-Text Search
Version 0.15.0 changes how full-text search works. This page is what you need to do about it.
What changed
Before, a node had one indexed document. You handed text to fts_index(), and
@@ searched that text whatever property you named on the left of it. So
d.title @@ "bread" and d.body @@ "bread" returned exactly the same rows, and
so did d.nonexistent @@ "bread".
Now an index covers one label and one property, you declare it once, and writing
that property keeps it current. d.title @@ "bread" searches titles.
The straightforward case
If the text you indexed is already stored in a property — the common case, and what the syntax always implied — declare an index over that property and delete the indexing call.
Before:
with db.write() as txn:
doc = txn.create_node(labels=["Document"], properties={"text": body})
txn.fts_index(doc.id, body)
txn.commit()
results = db.fts_search("bread")
After:
db.create_node_fts_index("Document", "text")
with db.write() as txn:
doc = txn.create_node(labels=["Document"], properties={"text": body})
txn.commit()
results = db.fts_search("Document", "text", "bread")
Declaring the index reads the property from every node already carrying the label, so an existing database is searchable as soon as you declare it. You do not need to rewrite your data.
The case that needs work first
If you indexed text that is not stored in any property, the database cannot rebuild it. It never held that text anywhere else, so there is nothing to read it back from.
This is more common than it sounds. Anything that assembled a searchable string from several fields falls into it:
# The old way: this string existed only inside the index
searchable = f"{title} {body} {' '.join(tags)}"
txn.fts_index(node.id, searchable)
Store the assembled text in a property, then declare an index over it:
db.create_node_fts_index("Document", "search_text")
with db.write() as txn:
txn.set_property(node.id, "search_text", f"{title} {body} {' '.join(tags)}")
txn.commit()
You have to backfill that property for existing rows, because only you know how the string was built. Read each node, assemble the text the way you used to, and write it; declaring the index afterwards picks it all up.
The upside is that the searchable text is now visible in the database. You can read it, correct it, and rebuild the index from it — none of which was possible when it lived only inside the index.
Relationship properties
Relationships work the same way, with the type standing in for the label:
db.create_edge_fts_index("REVIEWED", "note")
MATCH (a:Person)-[x:REVIEWED]->(p:Paper)
WHERE x.note @@ "thorough"
RETURN p.title
This is new rather than changed: there was no way to search relationship text before, because the old index held one document per node and relationships had no place in it. Nothing to migrate — but if you worked around the gap by copying relationship text onto one of its endpoints, you can stop.
The pattern has to name the type, for the reason a node pattern has to name a
label. A single @@ searches nodes or relationships, not both, so
d.title @@ "x" OR x.note @@ "x" is answered row by row rather than as one
index scan. It returns the right rows either way.
Searching several properties at once
OR searches each index and returns the union, scoring each document by its best
side:
MATCH (d:Document)
WHERE d.title @@ "bread" OR d.body @@ "bread"
RETURN d.title
That is usually what people wanted from the old merged document. If you need one combined score rather than a union, use the assembled-property approach above.
Errors you will see
"No full-text index is declared for Document.title." You searched a property with no index. Declare one. This is an error rather than an empty result because no rows is indistinguishable from a search that legitimately found nothing, which is how a typo in a property name goes unnoticed for months.
"d.title @@ ... needs a label to say which full-text index it means." Your
pattern was MATCH (d) with no label. Two labels can each declare an index on
title, so the property alone does not say which you mean. Write MATCH (d:Document).
A node passed through WITH keeps its label, even under a new name, so
MATCH (d:Document) WITH d AS x WHERE x.title @@ 'graph' RETURN x.title works.
API changes by language
Every search now takes the label and property first.
| Language | Removed | Use instead |
|---|---|---|
| Python | txn.fts_index(id, text) | db.create_node_fts_index(label, prop) |
| Python | db.fts_search(q) | db.fts_search(label, prop, q) |
| TypeScript | txn.ftsIndex(id, text) | db.createNodeFtsIndex(label, prop) |
| TypeScript | db.ftsSearch(q) | db.ftsSearch(label, prop, q) |
| Go | tx.FTSIndex(id, text) | db.CreateNodeFTSIndex(label, prop) |
| Go | db.FTSSearch(q, opts) | db.FTSSearch(label, prop, q, opts) |
| Java | txn.ftsIndex(id, text) | db.createNodeFtsIndex(label, prop) |
| Java | db.ftsSearch(q, opts) | db.ftsSearch(label, prop, q, opts) |
| C | lattice_fts_index(...) | lattice_node_fts_index_create(db, label, prop) |
| C | lattice_fts_search(db, q, ...) | lattice_fts_search(db, label, prop, q, ...) |
Every language also gained the relationship equivalent of the declaration call —
create_edge_fts_index, createEdgeFtsIndex, CreateEdgeFTSIndex, and
lattice_edge_fts_index_create — along with drop and has forms of both.
The fuzzy variants changed the same way.
Two fixes that came with it
A search with no LIMIT now returns every match. It used to stop at a hundred
rows, silently, whether or not you asked for a limit — and the same predicate
inside an OR returned all of them, so the answer depended on where you wrote it.
Fuzzy search inside a transaction is now actually fuzzy. It accepted
max_distance and min_term_length, discarded both, and ran an exact search.
Since 0.17.0 that includes text your transaction has written but not committed:
it is matched with the same edit distances.
Only string properties are indexed
A number, a list, or a missing property contributes nothing. Turning 42 into
"42" so a text search could match it would be a different feature with
different rules, and doing half of it quietly would make results hard to explain.
Durable Streams and Graph Changefeeds
LatticeDB includes durable named streams for append-only event records and a
built-in graph changefeed exposed as the reserved __lattice_changes stream.
Streams use the same transaction and WAL path as graph writes, so records become
visible only after commit.
Stream Model
- Stream names auto-create on first publish.
- Sequence numbers are per stream, start at
1, and read in ascending order. - Records contain
sequence,kind, and a typed payload. - Reads are cursor-based and do not automatically acknowledge records.
- Consumer offsets are explicit durable values.
trim_stream/trimStreamdeletes records through a sequence.
Streams are local durable logs, not a distributed task queue. They do not provide leases, retries, dead-letter queues, or cross-process notifications.
Python
with db.write() as txn:
txn.publish_stream("jobs", {"id": 1}, kind="job.queued")
txn.commit()
records = db.read_stream("jobs", after_sequence=0, limit=100)
TypeScript
await db.write(async (txn) => {
await txn.publishStream("jobs", { id: 1 }, "job.queued");
});
const records = await db.readStream("jobs", { afterSequence: 0n, limit: 100 });
Graph Changefeed
The reserved __lattice_changes stream records semantic graph mutations from
committed transactions.
Changefeed event kinds include:
node.insertnode.deletenode.label_addnode.label_removenode.property_setnode.property_removeedge.insertedge.deleteedge.property_setedge.property_remove
Payload maps include stable keys such as entity, op, node_id, edge_id,
source_id, target_id, type, label, key, old_value, and new_value.
For very large property changes, old_value or new_value may be a summary map
with __lattice_value_omitted, type, and encoded_bytes.
Python exposes Database.changes(...); TypeScript exposes db.changes(...).
Every event is kept by default. A retention policy (all, last:<N>,
age:<duration> or off) bounds how much of the changefeed the file holds.
The Changefeed covers what it is for, what it costs, the
policies and when to choose each, how to configure them in every language, and
its stored format.
The Changefeed
Every write transaction that changes the graph leaves a record of what it
changed: a node created, a label added, a property set from one value to
another, an edge removed. Those records are the changefeed, a stream named
__lattice_changes that lives inside the database file. This page covers what
the changefeed holds, what it is for, what it costs, how to decide how much of
it to keep, how to configure that in each language, and the format it is stored
in.
What it does
When a transaction commits, LatticeDB compares every node and edge the transaction touched with how it was before, and writes one event per elementary change:
| Event kind | Written when | Payload keys |
|---|---|---|
node.insert / node.delete | a node is created or deleted | entity, op, node_id |
node.label_add / node.label_remove | a label is added or removed | ... label |
node.property_set / node.property_remove | a property gets a value or loses one | ... key, old_value, new_value |
edge.insert / edge.delete | an edge is created or deleted | entity, op, edge_id, source_id, target_id, type |
edge.property_set / edge.property_remove | an edge property changes | ... key, old_value, new_value |
The events are written in the same transaction as the change, so they appear exactly when it commits and never when it rolls back, and a crash can never leave a change without its event or an event without its change. Each event has a sequence number: they start at 1, rise by one per event, a transaction's events are consecutive, and a number is never reused, not even after old events are dropped.
A property change records both the old and the new value, in full, whatever
their size, as long as the event stays within the 64 MiB limit on one record.
When it would not, the old value and then if need be the new one is replaced in
the event by a summary map
({__lattice_value_omitted: true, type, encoded_bytes}). A 40 MB string is
recorded whole; replacing one 40 MB string with another records the new value
and a summary of the old.
Vectors are not part of the changefeed: setting or replacing a node's vector writes no event.
What a transaction's events say, and in what order
A transaction's events describe its net effect: LatticeDB compares the
state each node and edge had before the transaction with the state it has
after, not the individual calls that got it there. So a property set three
times in one transaction is one property_set event, with the value before
the transaction as old_value and the last value as new_value; a node
created and deleted in the same transaction leaves no events; and a label
added and removed again leaves none.
The events of one transaction come in this order:
- the deletion of every edge the transaction deletes;
- every node that exists after the transaction: for a new node, its
node.insert, then anode.label_addper label, then anode.property_setper property; for a node that existed before, its label removals, label additions, property removals and property sets; - every edge that exists after the transaction, in the same way: for a new
edge its
edge.insertand then its properties, for an existing one its property removals and property sets; - the deletion of every node the transaction deletes.
Within each group, nodes and edges come in ascending id order, which for the nodes and edges a transaction creates is the order it created them in. A consumer that applies events in sequence order can therefore rely on these:
- an edge is created after both of its nodes exist;
- every label or property change comes after its node's or edge's creation;
- an edge is deleted before either of its nodes, and a node's deletion is the last event that names it, so a store that refuses to delete a node that still has relationships (as LatticeDB does) can apply the feed as it comes;
- a property appears at most once per transaction, carrying the change from before the transaction to after it.
What the order does not say is the order in which the transaction's
statements ran: a transaction that set a.x and then created b reads the
same as one that did it the other way round. 0.16.0 put events in a different
order: all nodes, then all edges, each in an order that depended on how a hash
map happened to lay them out, and a node's deletion before the deletion of its
edges.
Why it is there
LatticeDB is built to sit underneath tools that edit structured knowledge: ontology editors, knowledge-graph curation tools, applications whose users change a model and expect to see what changed and take it back. Those tools need the history of the graph, and the history is hard to reconstruct after the fact. The changefeed records it at the one place that sees every change, in the same transaction as the change.
What it is used for:
- Audit. Who changed this class's name, and from what? The event carries the old value and the new one, and the transaction's commit time.
- Undo. Because each property event keeps the old value, reversing a change is writing that value back.
- Keeping something else in step. A search index, a cache, a second database, a UI that shows live edits: read the events after the last one you handled, apply them, remember how far you got.
- Reviewing a session. Everything that happened between two points is a range of sequence numbers.
Reading the changefeed and undoing the last change, in Python:
import latticedb
with latticedb.Database("ontology.lattice", create=True) as db:
db.query("CREATE (:Class {name: 'Person'})")
db.query("MATCH (c:Class {name: 'Person'}) SET c.name = 'Human'")
for change in db.changes(after_sequence=0, limit=100):
print(change.sequence, change.kind, change.payload)
# Undo: put the old value of the last property change back.
last = db.changes(after_sequence=0, limit=100)[-1]
if last.kind == "node.property_set":
p = last.payload
with db.write() as txn:
txn.set_property(p["node_id"], p["key"], p["old_value"])
txn.commit()
1 node.insert {'entity': 'node', 'op': 'insert', 'node_id': 1}
2 node.label_add {'entity': 'node', 'op': 'label_add', 'node_id': 1, 'label': 'Class'}
3 node.property_set {'entity': 'node', 'op': 'property_set', 'node_id': 1, 'key': 'name', 'old_value': None, 'new_value': 'Person'}
4 node.property_set {'entity': 'node', 'op': 'property_set', 'node_id': 1, 'key': 'name', 'old_value': 'Person', 'new_value': 'Human'}
The undo is itself a change, so it appears as event 5.
A consumer that keeps something in step, in TypeScript. It stores its position as a consumer offset, in the same transaction as any other bookkeeping, so a restart picks up where it stopped:
import { Database, LatticeChangesTrimmedError } from '@hajewski/latticedb';
const db = new Database('ontology.lattice', { create: true });
await db.open();
let after = (await db.getStreamOffset('__lattice_changes', 'indexer')) ?? 0n;
try {
const changes = await db.changes({ afterSequence: after, limit: 100, timeoutMs: 1000 });
for (const change of changes) {
// ... update the search index from change.kind and change.payload ...
after = change.sequence;
}
} catch (err) {
if (err instanceof LatticeChangesTrimmedError) {
// Events after `after` were dropped by retention: rebuild from the graph,
// then continue from the oldest event still held (afterSequence 0n).
} else {
throw err;
}
}
await db.write(async (txn) => {
txn.setStreamOffset('__lattice_changes', 'indexer', after);
});
await db.close();
changes() with timeoutMs waits for the next commit in the same process when
there is nothing new, so a loop around it reacts to writes without polling.
What it costs
Every change writes an event, so the changefeed grows with the number of changes ever made, not with the size of the graph. A database that is edited for years holds years of events. This release stores them in a compact binary form (described below); the numbers are from loading 200,000 nodes, each with one label and two properties (four events per node), in transactions of 1,000 nodes, on an Apple-silicon laptop:
| 0.16.0 format | this release, all | last:10000 | off | |
|---|---|---|---|---|
| File size | 256.4 MB | 35.7 MB | 18.1 MB | 16.7 MB |
| Bytes per node | 1,282 | 178.5 | 90.6 | 83.5 |
| Of which changefeed | 238.0 MB (93%) | 19.0 MB (53%) | 0.25 MB | none |
| Bytes per event: key and value | 143 | 17.4 | 17.8 | |
| Bytes per event: on disk, pages included | 297 | 23.8 | 25.0 | |
| Loading the 200,000 nodes | 2.8 s | 1.0 s | 1.5 s | 0.6 s |
| One 20,000-node transaction, per node | 19–38 µs | 4.7–5.4 µs | 8.1–8.6 µs | 2.5–3.1 µs |
| A one-node transaction, commit included | 79–84 µs | 62–70 µs | 62–69 µs | 60–66 µs |
| Reopening after a crash with 999 small transactions in the log | 12–15 ms | 6.3–7.9 ms | 6.4–8.0 ms | 4.9–6.1 ms |
(MB here is 1,000,000 bytes.) So with the default of keeping everything, events are about half the file and a large part of the work of a big write; small transactions are dominated by the commit's sync to disk, and the changefeed adds little to them. A typical event takes 3 to 5 bytes of key and 4 to 20 bytes of value: a label event is 4 bytes, a node creation 8 (the first event of a transaction carries its commit time), a property change 4 plus the size of its two values.
last:10000 costs time while it trims: the large-transaction row is slower
than all because each checkpoint deletes the events that fell out of the
window.
Retention policies
How much of the changefeed to keep is a retention policy, recorded in the database file. There are four.
all (the default)
Keep every event, forever. Nothing is ever dropped unless you change the policy. This is the default because history is the raw material for audit and undo: a tool that has thrown history away cannot get it back, while one that kept it can always decide to drop it later.
last:<N>
Keep the newest N events; drop older ones. N counts events, not transactions, so the oldest transaction still held may have lost its first events. The file stays bounded however long the database lives: N events take roughly N × 25 bytes on disk.
age:<duration>
Keep the events of transactions committed within the duration; drop older
ones. The duration is a whole number with a unit: ms, s, m, h or d
(age:500ms, age:90s, age:30m, age:12h, age:7d). Whole transactions
go together. The age is measured against the system clock at the time of each
commit and of each trim, so a clock set far forward or back keeps events
longer or drops them sooner than intended. Events written by 0.16.0 carry no
commit time; they go only once a later, dated event is old enough to go.
off
Write no events at all, and drop the ones there are. Reading the changefeed
returns an error that says it is off (LATTICE_ERROR_UNSUPPORTED).
Sequence numbers do not move while it is off. Turning it back on skips one
sequence number, so that a reader that stopped before the feed went off is
told it missed changes rather than silently reading past them.
Nothing inside LatticeDB reads the changefeed, so off breaks nothing but
your own readers: replication ships the log rather than events, backups copy
the files, and your own durable streams are separate and keep working.
off is also what keeps a file open to 0.16.0, if it is set when the file is
created and the file has nothing else 0.16.0 cannot read (see
Opening with 0.16.0). Turning it off later does not.
Choosing a policy
| Setting | Policy | Why |
|---|---|---|
| An editor with undo, an audit trail, a curated knowledge graph | all | The history is the product. Size grows with edits, not with the graph: at about 25 bytes an event, a million changes take about 25 MB. |
| Undo or review over a recent window only | age:30d (or whatever the window is) | Bounded by time, which matches how people think about "recent". |
| A consumer that keeps a search index, cache or other store in step | last:<N> with N well above what it can fall behind by, or age: longer than it can be down | It needs only what it has not yet handled. If it falls further behind it is told so and can rebuild. |
| No one reads the changefeed: a cache, a derived dataset, a test fixture | off | Smallest file and fastest writes. |
| Loading a large dataset into a new database | off for the load, then all (or your policy) | The load's events describe "everything was created", which the graph itself already says. Switch the policy when the load is done; history starts from there. |
| Embedded on a device with little storage | last:<N> or age: | A firm bound on the file. |
Some things to weigh:
- A policy only ever drops. Changing
offtoalldoes not bring events back; changinglast:1000toallkeeps what is left of the last 1,000 and everything after. - Dropping is not instant. Old events go at checkpoints, a bounded number each time (4,096 plus the number written since the last one), so a stricter policy on a large changefeed takes several checkpoints to take effect and never stalls one. Call trim to apply it in full at once.
- Freed space is reused, not returned. Pages freed by dropping events are
reused by later writes; the file does not shrink.
lattice compactgives back only free pages at the end of the file. - A reader behind the window is told. It gets an error, not a gap.
Configuring it
The policy is written as text in every language and on the command line:
all, off, last:<N> or age:<duration>.
Python
db = latticedb.Database("ontology.lattice", create=True, changefeed_retention="age:30d")
db.open()
status = db.changefeed_status()
# ChangefeedStatus(retention='age:30d', oldest_sequence=1, last_sequence=1204)
removed = db.trim_changefeed()
A malformed policy raises ValueError before anything is opened. A reader
whose events were dropped gets LatticeChangesTrimmedError, a subclass of
LatticeNotFoundError.
TypeScript
const db = new Database('ontology.lattice', { create: true, changefeedRetention: 'last:100000' });
await db.open();
const status = await db.changefeedStatus();
// { retention: 'last:100000', oldestSequence: 1n, lastSequence: 1204n }
const removed = await db.trimChangefeed();
changefeedRetention is typed (ChangefeedRetention); a malformed value is a
TypeError at open. Dropped events surface as LatticeChangesTrimmedError.
Go
db, err := latticedb.Open("ontology.lattice", latticedb.OpenOptions{
Create: true,
ChangefeedRetention: "age:7d",
})
status, err := db.ChangefeedStatus() // Retention, OldestSequence (0 if none), LastSequence
removed, err := db.TrimChangefeed()
if _, err := db.Changes(after, 100, 0); errors.Is(err, latticedb.ErrChangesTrimmed) {
// rebuild, then read from 0
}
Java
try (Database db = Database.open("ontology.lattice",
OpenOptions.defaults().create(true).changefeedRetention("last:100000"))) {
ChangefeedStatus status = db.changefeedStatus(); // retention(), oldestSequence(), lastSequence()
long removed = db.trimChangefeed();
}
A reader whose events were dropped gets ChangesTrimmedException (error code
NOT_FOUND).
C
The policy is two fields of lattice_open_options_v5:
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
options.create = true;
options.changefeed_retention = LATTICE_CHANGEFEED_RETENTION_AGE;
options.changefeed_retention_value = 7ull * 24 * 60 * 60 * 1000; /* ms */
lattice_database* db;
lattice_open_v5("ontology.lattice", &options, &db);
uint8_t mode;
uint64_t value, oldest, last;
lattice_changefeed_status(db, &mode, &value, &oldest, &last);
uint64_t removed;
lattice_changefeed_trim(db, &removed);
changefeed_retention takes LATTICE_CHANGEFEED_RETENTION_DEFAULT (0, keep
the file's policy), _ALL, _LAST (value: events), _AGE (value:
milliseconds) or _OFF. oldest is 0 when the changefeed holds no events.
lattice_stream_read on __lattice_changes returns LATTICE_ERROR_NOT_FOUND
when the events after after_sequence were dropped, and
LATTICE_ERROR_UNSUPPORTED when the feed is off.
Command line
Any command that opens a database for writing takes --changefeed=<policy>,
create included. lattice changefeed shows the policy and what is held, and
sets and trims it:
$ lattice changefeed ontology.lattice
Changefeed of ontology.lattice
Retention: all
Events held: 5
Bytes: 105
Sequences: 1..5
$ lattice changefeed ontology.lattice --changefeed=last:2 --trim
Changefeed of ontology.lattice
Retention: last:2
Events held: 2
Bytes: 68
Sequences: 4..5
Trimmed: 3 events
--format=json and --format=csv give the same fields. lattice info shows
the policy and range on one line (Changefeed: keep last:2, events 4..5).
Events still in the 0.16.0 format are counted separately
(Events held: 1200 (800 in the 0.16 format)).
lattice info and lattice check also say whether 0.16.0 can open the file
(Min reader: v4, so 0.16.0 cannot open it (changefeed events)).
Environment
LATTICE_CHANGEFEED_RETENTION=<policy> sets the policy of a database when it
is created and no option names one. It never changes an existing database,
which keeps a stray environment variable from discarding history. A value that
is not a policy is ignored without an error, and the new database keeps every
event.
Which setting wins
- A policy passed when opening for writing replaces the one in the file, and is recorded at once.
- Otherwise the file's policy stands. A read-only open never changes it, whatever it is given.
- A new database with no policy given takes
LATTICE_CHANGEFEED_RETENTION. - Otherwise
all.
Opening with a new policy drops nothing by itself; the drop happens at the next checkpoint or trim. Note that opening a database whose log still holds transactions (after a crash, or a process that did not close) folds that log in with a checkpoint, which is such a point.
Trimming now
trim_changefeed() / trimChangefeed() / TrimChangefeed() /
lattice_changefeed_trim / lattice changefeed --trim apply the policy in
full and make the result durable before returning, and return how many events
were dropped. It is refused while a write transaction is open on the handle
(LATTICE_ERROR_LOCK_TIMEOUT). Under all it drops nothing.
Otherwise, events are dropped at checkpoints: automatically once the log
passes its threshold (1,000 log frames by default), on lattice checkpoint,
and when the database is closed. A database opened without the log has no
checkpoints; its events are dropped when its pages are flushed instead: on
sync() (Zig), at close, and after a commit once half the page cache holds changes.
You can also drop events through a sequence yourself, in a write transaction,
with the stream trim every stream has (txn.trim_stream("__lattice_changes", s),
txn.trimStream(...), lattice_stream_trim), whatever the policy. That is the
way to discard history up to a point you choose, such as one every consumer has
passed, while keeping all for everything after it. A sequence past the last
event drops everything there is and no more: events written afterwards are kept.
Reading at the edge of the window
changes(after_sequence=s) returns the events from s + 1 on.
s = 0always reads from the oldest event held.- If event
s + 1has been dropped, the read fails with the trimmed error (LATTICE_ERROR_NOT_FOUNDunderneath). The reader has missed changes; it should rebuild whatever it maintains from the graph and continue from 0, or fromchangefeed_status().last_sequenceif it rebuilt from a snapshot taken at that point. - A reader that is exactly at the edge (it handled event
oldest - 1) reads on without an error.
The stored format
Events are stored in the database's stream-events B+Tree, next to user streams.
This section is the reference for that encoding, for anyone writing a tool
that reads the file directly. Applications read events through changes() and
never see it: what changes() returns is identical whichever form an event is
stored in.
Conventions: keys are compared bytewise and their numbers are big-endian; varints are unsigned LEB128 (seven bits per byte, low bits first, the high bit set on every byte but the last, at most 10 bytes); engine values are little-endian.
Key
00 n sequence (n bytes, big-endian)
n (1 to 8) is the fewest bytes that hold the sequence, so keys are 3 bytes up
to sequence 255, 4 up to 65,535 and 5 up to 16,777,215, and they sort in
sequence order (a longer number is a larger one). User stream keys begin with
the stream name's length, 1 to 255, so a key beginning with 00 is always the
changefeed's.
Value
| Field | Size | Present |
|---|---|---|
head byte vvv t oooo | 1 | always. vvv = encoding version (1), t = a transaction header follows, oooo = operation |
| commit time | varint, milliseconds since 1970-01-01 UTC | when t is set: the first event of every transaction |
| id | varint | always: the node id, or the edge id for edge operations |
| source id, target id | varint, varint | edge.insert, edge.delete |
| symbol | varint, sometimes followed by a name | label operations (the label), property operations (the key), edge.insert/edge.delete (the edge type) |
| old value, new value | engine value, twice | property operations; a missing value is 00 (null) |
Operations: 1 node.insert, 2 node.delete, 3 node.label_add,
4 node.label_remove, 5 node.property_set, 6 node.property_remove,
7 edge.insert, 8 edge.delete, 9 edge.property_set,
10 edge.property_remove. Head bytes are therefore 21–2a without a
header and 31–3a with one.
Symbol. A varint s. Even: s / 2 is an id in the database's symbol
table, the table that maps label, type and key names to numbers (ids are 16-bit,
user names start at 1000, and an id is never removed or reused). Odd:
(s - 1) / 2 bytes of UTF-8 name follow. This release always writes ids; the
name form is reserved.
Engine value. A type tag, then the value: 00 null; 01 bool (1 byte);
02 int (8 bytes, signed); 03 float (8 bytes, IEEE 754); 04 string
(4-byte length, UTF-8); 05 bytes (4-byte length, bytes); 06 vector (4-byte
count, 4-byte floats); 07 list (4-byte count, values); 08 map (4-byte
count, then per entry a 4-byte key length, the key and a value).
What changes() builds from it. The kind is the operation's name; the
payload is a map with, in order, entity ("node" or "edge"), op
("insert", "delete", "label_add", "label_remove", "property_set",
"property_remove"), node_id or edge_id, then source_id, target_id
and type for edge insert and delete, label for label operations, and
key, old_value, new_value for property operations.
An example
Two transactions, CREATE (:Person {name: 'Ada'}) and then a second person
with a KNOWS edge to the first, store these entries:
key 00 01 01 sequence 1
val 31 version 1, transaction header, op 1 node.insert
cb a8 dc 84 9d 34 commit time 1794500924491 (2026-11-12 16:28:44.491 UTC)
01 node 1
key 00 01 02 sequence 2
val 23 01 d0 0f op 3 label_add, node 1, symbol 2000 = id 1000 ("Person")
key 00 01 03 sequence 3
val 25 01 d2 0f op 5 property_set, node 1, symbol id 1001 ("name")
00 old value: null
04 03 00 00 00 41 64 61 new value: string of 3 bytes, "Ada"
key 00 01 04 sequence 4
val 31 cd a8 dc 84 9d 34 02 node.insert, header (2 ms later), node 2
key 00 01 05 sequence 5
val 23 02 d0 0f label_add, node 2, "Person"
key 00 01 06 sequence 6
val 27 01 01 02 d4 0f op 7 edge.insert, edge 1, from 1 to 2, type id 1002 ("KNOWS")
In the 0.16.0 format the first three of these took 26-byte keys and values of 107 to 177 bytes each.
Other state
The stream-meta B+Tree holds the changefeed's bookkeeping:
| Key | Value |
|---|---|
11 "__lattice_changes" | the last sequence handed out (8 bytes, little-endian) |
00 "changefeed.floor" | every event below this sequence has been dropped (8 bytes, little-endian); missing means 1, nothing dropped |
00 "changefeed.retention" | the policy: mode (1 byte: 1 all, 2 last, 3 age, 4 off), value (8 bytes, little-endian: events or milliseconds); missing means all |
In the log
A transaction's events are written to the write-ahead log as records of payload
type 0x23, each holding up to about 3,800 bytes of events:
23 01 first-sequence(varint) count(varint)
symbol-count(varint) { id(varint) name-length(varint) name }*
{ event-length(varint) event-bytes }*
The event bytes are exactly what is stored in the tree. Each record names the symbols its events use, because the symbol table is not itself logged: after a crash, recovery may give a name a different id than the event carries, and replay rewrites the event to the id the name has now.
Events from 0.16.0
Events written by 0.16.0 (and 0.17.0 development builds before this format)
keep their old form, about 300 bytes each on disk: key 11 "__lattice_changes" followed by the sequence as
8 bytes big-endian, value the kind's length, the kind, a 4-byte payload length
and the payload map as an engine value. Their first value byte is 11 to 20
(the kind's length); a compact value's is 21 to 3a, and the key already
tells them apart. Both forms are read side by side, in sequence order.
Old events are not rewritten: they stay in the old form until the retention
policy drops them (lattice compact does not convert them). To shed them while
keeping everything else, export the graph and import it into a new database;
the new database's changefeed starts with the import, and the old history stays
behind in the old file.
Opening with 0.16.0
0.16.0 does not know the compact form: it would skip compact events without an error and its trim would leave them in place. So the first commit that records a compact event raises the file's minimum reader version to 4 and records why (the header field at offset 224, described in the page manager). The raise is written into the file header in place and synced before the commit is logged or any page is written, so no crash leaves a stored event under a header 0.16.0 accepts. 0.16.0 then refuses the file: an I/O error from its C API and bindings, "Failed to open database: IoError" from its CLI. The version is never lowered, also not when a retention policy later drops every event, since a copy of an event may survive in a log or a backup.
A file this release only reads, and a file created with retention off, keep
version 3 and stay open to 0.16.0 unless something else raised it (a vector
index 0.16.0 cannot describe, an ordered property index, a full-text index
holding documents with word positions). To take a written
file back to 0.16.0, export it to JSON with this release and import it with
0.16.0; the changefeed stays behind.
Compatibility promise
Every form described here stays readable by every later release. A future encoding will use a new version number in the head byte; a reader that meets a version it does not know refuses the record rather than guess at it.
Data Export
Use the CLI to export graph data from a .lattice database file, and lattice import to load it into another.
Basic Usage
lattice export <path-to-db> --file=<output-path>
Examples:
# Full graph as one JSON document
lattice export knowledge.db --file=backup.json
# One JSON object per line (stream-friendly)
lattice export knowledge.db --file=backup.jsonl
# Graphviz DOT (for visualization tools)
lattice export knowledge.db --file=graph.dot
JSON, JSONL and CSV exports can be read back with lattice import. DOT is for
looking at, not for importing.
An export that fails removes the file it was writing, so a file that exists is complete.
CSV Export
CSV export writes two files (nodes and edges), using the --file value as a base name:
lattice export knowledge.db --file=backup.csv
This generates:
backup_nodes.csv, with_id,_labels(separated by;), a column per property, and_vectorwhen the export includes vectorsbackup_edges.csv, with_source,_target,_typeand a column per property
Property columns are named <key>:json and hold each value in the JSON
encoding described below, so every type reads back as itself. An empty cell
means the node or edge does not have that property. Fields are quoted as RFC
4180 describes when they need it:
_id,_labels,age:json,name:json
1,"Person",29,"""Carol"""
2,"Person",35,"""Dan"""
To import the pair, give lattice import the same --file value; it reads both
files and connects the edges to the nodes through the _id column:
lattice import copy.db --file=backup.csv
A label that CSV cannot hold (empty, containing ;, or with leading or trailing
spaces) makes a CSV export fail; use JSON for such a graph.
Choosing What to Export
Use --labels to export only nodes with selected labels (comma-separated). Edges
between exported nodes are included.
lattice export knowledge.db --file=people.json --labels=Person
lattice export knowledge.db --file=content.dot --labels=Document,Chunk
Use --query to export what a Cypher query returns: every node and
relationship in its rows (including inside lists and maps), plus the endpoints
of each relationship, so the file imports on its own.
lattice export knowledge.db --file=knows.json --query="MATCH (a:Person)-[k:KNOWS]->(b:Person) RETURN k"
The query must return nodes or relationships themselves. One whose rows hold only other values is refused:
Error: Export failed: the query returned no nodes or relationships to export. Return them, for example MATCH (n:Person) RETURN n.
--labels and --query cannot be used together. lattice dump accepts both
options too.
Vectors
When the database has a vector index, exports include each node's vector, and
JSON exports and dumps record the index: its dimensions, metric, m and
ef_construction. No vector options are needed, because the database file records
its index:
lattice export embeddings.db --file=docs.json
{"version":2,"vector_dimensions":3,"vector_metric":"cosine","vector_m":16,"vector_ef_construction":200,"nodes":[{"id":"1","labels":["Doc"],"properties":{"title":"cafe"},"vector":[0.6,0.8,0.0]}],"edges":[]}
Under the cosine metric a vector is stored normalised, so the exported vector is
the unit-length one: a node given [3, 4, 0] exports as [0.6,0.8,0.0]. Under
the euclidean and dot_product metrics vectors are stored as given and export as
[3.0,4.0,0.0]. Readers that do not know the metric and HNSW fields, 0.16.0 among
them, skip them, so the format version stays 2. JSONL, CSV and DOT exports have no
header and carry none of these settings.
A database last written by 0.16.0 whose dimensions cannot be read from its vector
pages is the one case where an export leaves vectors out, with a warning, unless
it is given --enable-vector --vector-dims=<n>.
Importing a file that holds vectors needs a target database with a vector index of
the same dimensions; a database without one can be given one by the import itself,
with --enable-vector. A JSON import then builds the index from the file's
header, with its dimensions, metric, m and ef_construction, so a database
rebuilt from an export searches as the original did; --vector-dims=<n> overrides
the dimensions, and a JSONL or CSV import, or a JSON file without a header, needs
it. A target that already has an index keeps its own settings: the file's are not
imposed on it. A JSON import checks the dimensions before writing
anything (here copy.db was created with four dimensions); JSONL and CSV
imports fail at the first node whose vector does not fit:
Error: Import failed: the vectors in docs.json do not have the 4 dimensions copy.db was opened with.
The JSON Format
JSON exports start with "version": 2. Values are written so their type
survives the round trip. Strings, integers, booleans, null, lists and maps are
plain JSON; floats always have a decimal point or an exponent (2.0, not 2).
The types JSON has no notation for are written as an object with one $ key:
| Value | Written as |
|---|---|
| Bytes | {"$bytes": "3q2+7w=="} (base64) |
| A vector-valued property | {"$vector": [1.5, 2.5]} |
| NaN, infinity | {"$float": "NaN"}, {"$float": "Infinity"}, {"$float": "-Infinity"} |
A map whose only key starts with $ | {"$map": {"$ref": "x"}} |
A node's own embedding is the separate "vector" field, not a property.
JSONL uses the same encoding, one node or edge per line with a "kind" field,
and no version or dimensions line.
Files written by 0.16.0 and earlier
A JSON file with no "version" field is read as the old format, so exports
from earlier releases still import, with one difference: a string is always
imported as a string. Earlier releases exported bytes as hex strings, which
cannot be told apart from a string like "cafe", so bytes in an old export come
back as strings. A numeric array in an old file is still read as a vector
property, as it was then. A file with a version newer than this release knows
is refused rather than misread.
What Is Not Exported
Exports hold nodes, labels, properties, edges and, when asked for, vectors. They do not hold full-text or property index definitions, or anything else about how the database was configured, and every node gets a new ID when an export is imported.
To copy a whole database, use lattice backup (see
Backup and Replication) or serialize() from a
binding.
Choosing a Format
.json: single structured snapshot of the graph, for interchange..jsonl: one record per line, for pipelines..csv: tabular extraction for spreadsheets and BI tooling..dot: graph visualization with Graphviz-compatible tooling..ttl,.nt: RDF in Turtle or N-Triples, for RDF tools and ontology editors; see RDF: Turtle and N-Triples.
RDF: Turtle and N-Triples
lattice import reads RDF in Turtle and N-Triples, and lattice export writes
a graph back out in either. A vocabulary or a data set that lives in RDF can be
loaded into a database, queried with Cypher, full-text and vector search, and
written back as RDF for the tools that expect it.
This is interchange, not a triple store. The data becomes a property graph:
nodes with labels and properties, connected by edges. There is no SPARQL, no
inference (rdfs:subClassOf is an edge you can follow, not a rule that is
applied), and no named graphs.
A Worked Example
animals.ttl:
@prefix ex: <https://example.org/animals/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
ex:Animal a rdfs:Class ; rdfs:label "Animal"@en, "Tier"@de .
ex:Mammal a rdfs:Class ; rdfs:subClassOf ex:Animal ;
rdfs:label "Mammal"@en, "Säugetier"@de .
ex:Cat a rdfs:Class ; rdfs:subClassOf ex:Mammal ;
rdfs:label "Cat"@en, "Katze"@de ;
skos:definition "A small domesticated carnivorous mammal."@en .
ex:tom a ex:Cat ; rdfs:label "Tom"@en ; ex:age 3 ;
ex:chases ex:jerry {| ex:since 1940 |} .
ex:jerry rdfs:label "Jerry"@en .
Import it, declaring full-text indexes on two of its properties:
lattice create animals.lattice
lattice import animals.lattice --file=animals.ttl --rdf-fts=rdfs_label,skos_definition
Importing animals.ttl (turtle) into animals.lattice...
Import complete
Triples read: 18 (8 statements, 0.0s, 7604 triples/s)
Nodes created: 5
Edges created: 3
Property values: 10 on nodes, 1 on edges
Labels added: 4
rdf:type as: labels (2 distinct classes; labels up to 1000 with the existing labels)
Names created: 9 (0 numbered to stay distinct), prefixes stored: 3
Declared the property index Resource(iri)
Full-text indexes declared: 2
Every IRI is now a node labelled Resource with an iri property, and each
predicate a name made of its prefix and local part. The superclasses of Cat,
by following rdfs:subClassOf edges any number of steps:
lattice exec animals.lattice --query="MATCH (c:Resource {iri: 'https://example.org/animals/Cat'})-[:rdfs_subClassOf*1..]->(super) RETURN super.rdfs_label AS class, super.rdfs_label_de AS german"
┌──────────┬─────────────┐
│ class │ german │
├──────────┼─────────────┤
│ "Mammal" │ "Säugetier" │
│ "Animal" │ "Tier" │
└──────────┴─────────────┘
rdf:type became a label, and the RDF-star annotation an edge property:
lattice exec animals.lattice --query="MATCH (n:ex_Cat)-[r:ex_chases]->(m) RETURN n.rdfs_label AS cat, m.rdfs_label AS mouse, r.ex_since AS since, n.ex_age AS age"
┌───────┬─────────┬───────┬─────┐
│ cat │ mouse │ since │ age │
├───────┼─────────┼───────┼─────┤
│ "Tom" │ "Jerry" │ 1940 │ 3 │
└───────┴─────────┴───────┴─────┘
Full-text search over the definitions, and a count by type:
lattice exec animals.lattice --query="MATCH (n:Resource) WHERE n.skos_definition @@ 'carnivorous' RETURN n.iri"
lattice exec animals.lattice --query="MATCH (n:rdfs_Class) RETURN count(n) AS classes"
┌───────────────────────────────────┐
│ n.iri │
├───────────────────────────────────┤
│ "https://example.org/animals/Cat" │
└───────────────────────────────────┘
┌─────────┐
│ classes │
├─────────┤
│ 3 │
└─────────┘
And back out as Turtle:
lattice export animals.lattice --file=animals_out.ttl
@prefix : <urn:lattice:> .
@prefix ex: <https://example.org/animals/> .
@prefix lattice: <https://latticedb.org/ns#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
ex:Animal
a rdfs:Class ;
rdfs:label "Animal"@en, "Tier"@de .
ex:Mammal
a rdfs:Class ;
rdfs:label "Mammal"@en, "Säugetier"@de ;
rdfs:subClassOf ex:Animal .
ex:Cat
a rdfs:Class ;
rdfs:label "Cat"@en, "Katze"@de ;
skos:definition "A small domesticated carnivorous mammal."@en ;
rdfs:subClassOf ex:Mammal .
ex:tom
a ex:Cat ;
rdfs:label "Tom"@en ;
ex:age 3 ;
ex:chases ex:jerry {| ex:since 1940 |} .
ex:jerry
rdfs:label "Jerry"@en .
The file is the same RDF graph as the one imported, in a different order.
Choosing the Syntax
The file extension chooses: .ttl and .turtle are Turtle, .nt and
.ntriples N-Triples. For another extension, say which with
--format=turtle or --format=ntriples. Both syntaxes are read as RDF 1.1
says, and pass the W3C Turtle and N-Triples test suites; Turtle-star and
N-Triples-star (<< s p o >> and {| ... |}) are read too.
How RDF Becomes a Graph
| RDF | In the graph |
|---|---|
| An IRI | A node labelled Resource with the IRI in its iri property |
| A blank node | A node with no label and no iri |
s rdf:type C | The label for C on s (or an edge, see below) |
s p "literal" | A property of s named for p |
s p o, o an IRI or blank node | An edge of the type named for p from s to o |
s p ( "a" "b" ) | A list property named for p, with _list added |
s p o {| q v |}, << s p o >> q v | A property q of the edge s p o |
Import declares the property index Resource(iri) if the database does not
have it, and finds every IRI through it, so a second file imported into the same
database adds to the nodes the first one made. Blank nodes are local to their
file: _:b1 in two files is two nodes.
Names
Labels, edge types and property names are written <prefix>_<local>:
rdfs:label is rdfs_label, skos:prefLabel is skos_prefLabel, and a name
in the namespace of the empty prefix is just its local part. Characters Cypher
cannot have in a name become _, a name that starts with a digit gets a _ in
front, and a name is cut at 200 bytes. Two IRIs never share a name: when one
would, the second gets _2, and the import reports how many it numbered.
The prefix is the one the database already has for the namespace, else the
file's own, else a well-known one (rdf, rdfs, owl, xsd, skos, dc,
dcterms, foaf, schema, prov, sh, dcat, org and a few more), else
ns1, ns2, and so on. One namespace has one prefix in a database: the first
one it was given.
Import keeps the table of names and prefixes in the database, as nodes labelled
_RdfName and _RdfNamespace, and export reads it to turn names back into
IRIs. These nodes are visible to Cypher and to the JSON and CSV exports; leave
them in place for as long as you want to export the graph as RDF.
Values
| Literal | Stored as |
|---|---|
xsd:integer and its subtypes (int, long, nonNegativeInteger, ...) | Integer. One that does not fit in 64 bits fails its statement |
xsd:double, xsd:float | Float |
xsd:decimal | Float when the float is exactly the decimal written, else the text (--rdf-decimal=string: always the text) |
xsd:boolean | Boolean |
A plain or xsd:string literal, "text"@tag | String |
xsd:base64Binary | Bytes |
rdf:JSON holding an object | Map |
"[0.1, 0.2]"^^lattice:vector (https://latticedb.org/ns#vector) | The node's vector (needs --enable-vector) |
Any other datatype (xsd:date, xsd:anyURI, your own) | The text; the datatype is remembered for export |
Each property remembers the datatype of the first value it gets of each kind
(integer, float, string, bytes). A later value of the same kind with a
different datatype is kept as a map, such as
{"@value": "plain", "@type": "http://www.w3.org/2001/XMLSchema#string"},
so that nothing is lost; the import counts these.
Languages
Strings in one language, English unless --rdf-lang says otherwise, go to the
property itself (rdfs_label), so one full-text index covers them. Each other
language gets a property of its own, its tag added in lower case with - as _:
rdfs_label_de, rdfs_label_en_gb. Untagged strings go to the property too,
unless it already holds tagged ones; then they go to <name>_plain, and tagged
strings arriving at a property that holds untagged ones go to <name>_en.
Loading several vocabularies into one database often mixes the two:
lattice exec vocab.lattice --query="MATCH (c:rdfs_Class) RETURN coalesce(c.rdfs_label, c.rdfs_label_plain) AS label LIMIT 3"
┌──────────────────┐
│ label │
├──────────────────┤
│ "Label Property" │
│ "Person" │
│ "Agent" │
└──────────────────┘
Here SKOS, imported first, gave rdfs:label English strings, and FOAF's and
schema.org's untagged labels went to rdfs_label_plain.
Repeated Values, Collections and Blank Nodes
A subject with several values for one predicate gets a list property, in file order, each value once: RDF is a set of triples. Several IRI objects are several edges; a triple that is already there is not added again.
A collection of literals, ( "a" "b" ), is a list property named <name>_list
and is written back as a collection. A collection with IRIs or blank nodes in
it is stored as RDF spells it, a chain of blank nodes with rdf_first and
rdf_rest edges ending at rdf:nil.
Types as Labels or Edges
--rdf-types=labels makes each rdf:type a label, and --rdf-types=edges an
edge rdf_type to the class's node. The default, auto, reads the file once
before importing and uses labels unless the classes it names and the labels the
database already has come to more than 1,000; the import says which it chose.
A class that is a blank node is always an edge.
Statements About Triples
An annotation ({| ... |}) or a statement about a quoted triple
(<< s p o >> q v .) becomes a property of the edge s p o, which is created
if the file does not assert it. A literal value is stored as a property value
would be; an IRI value as the map {"@id": "<iri>"}. Refused, with a message
naming the triple: a quoted triple whose object is a literal (a property cannot
have properties), a quoted triple as an object, and a quoted triple inside
another.
Errors and Atomicity
A record is one statement: one N-Triples line, or one Turtle statement up to
its . (a subject with all its predicates). Statements are committed in
batches: a batch ends with the statement that brings it to --batch-size
triples (default 1000), so a statement is never split between two
transactions. A statement that cannot be stored
fails the import, naming the triple and why; batches committed before it are
kept:
Error: Import failed at line 4, column 29: <http://example.org/b> <http://example.org/count> "123456789012345678901234567890"^^<http://www.w3.org/2001/XMLSchema#integer>: 123456789012345678901234567890 does not fit in a 64-bit integer
Nothing was imported. Use --on-error=skip to import the statements that are valid.
With --on-error=skip, each statement is committed on its own, a failing one
is left out whole, with every other triple of that statement, and each is
listed. A syntax error in Turtle always stops the import, because after it
there is no telling where the next statement starts; with --rdf-types=auto
the whole file is read before anything is written, so a syntax error stops it
with nothing imported. In N-Triples, --on-error=skip goes on at the next line.
Importing a file again adds nothing that is already there, except its blank nodes, which are new nodes each time.
Exporting
lattice export animals.lattice --file=animals.ttl
lattice export animals.lattice --file=animals.nt
Turtle writes each node once, with its types, properties and edges grouped
under it (; between predicates, , between objects), and abbreviates IRIs
with the prefixes the database has. N-Triples writes one triple per line and is
the one to use for very large graphs and line-based tools. --labels and
--query choose what to export as for the other formats (see
Data Export); with --labels, each node's outgoing edges
are written whether or not the node at the other end was chosen.
Nodes and names that came from RDF get their IRIs back. For a graph built in LatticeDB:
- A label, edge type or property name that is not in the table is written
under a base,
urn:lattice:unless--basegives another, and the base is declared as the empty prefix, so:Personand:nameread back asPersonandname. - A node without an IRI is a blank node,
_:n<id>. With--base, it is the IRI<base>node/<id>instead, which other tools can refer to. - Bytes are
xsd:base64Binary, mapsrdf:JSON, and a list one triple per element. Vectors are written when the database is opened with--enable-vectorand its dimensions, as"[...]"^^lattice:vector;--rdf-vectors=omitleaves them out. - Edge properties are RDF-star annotations.
--rdf-edge-properties=reifywrites anrdf:Statementfor each edge that has properties instead, for tools that do not read RDF-star, and--rdf-edge-properties=dropleaves them out and says how many values it left out.
lattice export social.lattice --file=social.ttl --base=https://example.org/social/
What Comes Back Changed
Turtle to a database and back gives the same RDF graph, compared as RDF compares graphs (blank nodes matched up, numbers by value), except for:
- the way numbers and booleans are written:
+01comes back as1,1E3as1.0e3,"1"^^xsd:booleanastrue; - a prefix, when the database already had another prefix for that namespace;
- statements about a triple the file did not assert: import asserts it;
- a collection with an IRI or blank node in it, which comes back as the
rdf:first/rdf:resttriples it stands for rather than as( ... ); - comments, order and layout.
A database to Turtle and back gives the same labels, properties and edges, except for:
- node IDs, and the
_RdfNameand_RdfNamespacenodes the import adds; - two edges of one type between the same two nodes, which are one triple in RDF and come back as one edge;
- a list of one element, which comes back as a single value, an empty list, which does not come back, and repeated elements of a list, which come back once;
- a list inside a list, which comes back as
rdf:JSONtext; - vectors, which come back normalised to unit length under the cosine metric, as with every export;
- with
--base, nodes come back labelledResourcewith aniri; - with
--rdf-edge-properties=reify, edge properties come back asrdf:Statementnodes, not as properties of the edge.
Other RDF Formats
RDF/XML, JSON-LD, TriG and N-Quads are not read or written. RDF/XML and JSON-LD convert to Turtle or N-Triples in one step with rapper or Apache Jena's riot:
rapper -i rdfxml -o ntriples ontology.rdf > ontology.nt
riot --output=turtle data.jsonld > data.ttl
TriG and N-Quads carry named graphs, which have no place in the mapping: it would take a graph name on every node and edge, as a property or a label, and an export that groups by it. Converting to N-Triples drops the graph names.
SPARQL, inference (RDFS, OWL) and SHACL validation are not part of LatticeDB. Query the graph with Cypher, and validate or reason with an RDF tool on the export.
Performance
Import and export stream: memory does not grow with the file. On a release build, on a busy machine, with a graph of 100,000 people, each with a type, four literal properties and five edges (1,000,000 triples):
| Time | Peak memory | |
|---|---|---|
| Import, N-Triples (107 MB) | 23.7 s, 42,000 triples/s | 46 MB |
| Import, Turtle (19 MB) | 23.8 s, 42,000 triples/s | 46 MB |
| Import, the same graph as CSV (100,000 nodes, 500,000 edges) | 11.2 s | 61 MB |
| Export, Turtle | 1.7 s | 45 MB |
| Export, N-Triples | 1.3 s | 45 MB |
Parsing alone takes 0.7 s for the N-Triples file and 0.2 s for the Turtle one, in 2 MB of memory; the rest of an import is the database writing and committing. CSV is faster for the same graph because one CSV row sets all of a node's properties at once, where RDF has a triple for each.
Transactions and Durability
LatticeDB provides ACID transactions with snapshot isolation.
Transaction Model
- Read transactions see a consistent snapshot of the database. As many as you like can run at once.
- Write transactions change the database. Only one can be open at a time — see One writer at a time below, because this one has a sharp edge.
- Snapshot isolation — each transaction sees the database as it was the moment it began. Changes made by other transactions that have not committed yet are invisible to it.
Using Transactions
Python
# Read transaction
with db.read() as txn:
node = txn.get_node(node_id)
edges = txn.get_outgoing_edges(node_id)
# Transaction automatically completes when context exits
# Write transaction
with db.write() as txn:
node = txn.create_node(labels=["Person"], properties={"name": "Alice"})
txn.commit()
# If commit() is not called, the transaction is rolled back
TypeScript
// Read transaction
await db.read(async (txn) => {
const node = await txn.getNode(nodeId);
const edges = await txn.getOutgoingEdges(nodeId);
});
// Write transaction
await db.write(async (txn) => {
const node = await txn.createNode({
labels: ["Person"],
properties: { name: "Alice" },
});
// Transaction auto-commits on success, rolls back on error
});
C
// Begin a read transaction
lattice_txn* txn;
lattice_begin(db, LATTICE_TXN_READ_ONLY, &txn);
// ... read operations ...
lattice_commit(txn);
// Begin a write transaction
lattice_begin(db, LATTICE_TXN_READ_WRITE, &txn);
// ... write operations ...
lattice_commit(txn); // or lattice_rollback(txn);
Queries and Transactions
db.query() automatically creates the appropriate transaction:
- Read queries (
MATCH ... RETURN) use a read transaction - Write queries (
CREATE,SET,DELETE) use a write transaction
# Implicit read transaction
results = db.query("MATCH (n:Person) RETURN n.name")
# Implicit write transaction
db.query("CREATE (n:Person {name: 'Alice'})")
Durability
LatticeDB uses a write-ahead log (WAL) for crash recovery:
- Changes are written to the WAL before being applied to data pages
- Commit means the WAL record is on disk (a fast sequential write)
- Data pages are written later, all together: at checkpoints, at close, on
sync() - On crash, the WAL is replayed to recover committed transactions
A commit that has returned survives the process crashing. Surviving a power cut as
well depends on the settings: the default sync mode waits for the disk on every
commit, sync_mode normal does not, and on macOS the disk's own cache is flushed
only with full_fsync on. Both are open options in every API, and the
LATTICE_SYNC_MODE and LATTICE_FULL_FSYNC environment variables apply when a
program does not set them. A transaction is never applied in part, after a crash or
a power cut. See Durability and the Log.
A database opened without the log (enable_wal = false) has the same
transactions: they commit and roll back, and a writing query is all or nothing.
What changes is durability: a commit survives a crash only once a flush has
written it to the file. See
Running without the log.
Concurrency
- Readers never block writers
- Writers never block readers
- As many readers as you like can run at the same time
- Only one write transaction can be open at a time
This makes LatticeDB a good fit for read-heavy work, which is what most RAG and search applications look like.
One writer at a time
A database handle allows exactly one open write transaction. If you try to begin a second one while the first is still open, you do not wait in a queue — the call fails immediately.
This changed in 0.10.0. Before that, overlapping writers were resolved later, at commit time. Now the second one is refused up front, which turns a subtle race into an obvious error you can see and handle.
Read transactions are unaffected. You can open as many as you want, and they can happily run alongside the writer.
What the error looks like
| Language | What you get |
|---|---|
| C | LATTICE_ERROR_LOCK_TIMEOUT (-8) returned from lattice_begin |
| Python | LatticeLockTimeoutError raised |
| TypeScript | LatticeError thrown, with .code === -8 |
| Go | ErrorLockTimeout on the returned error's Code |
The name says "lock timeout", which is a slightly misleading inheritance from the error code it shares. Nothing is timing out. It means: somebody else is already writing.
Writing code that respects it
The fix is almost always to finish one write before starting the next, rather than to retry. If two parts of your program both want to write, give them the same handle and let them take turns:
# This fails: the second write() begins while the first is still open
with db.write() as txn_a:
txn_a.create_node(labels=["Person"], properties={"name": "Alice"})
with db.write() as txn_b: # raises LatticeLockTimeoutError
txn_b.create_node(labels=["Person"], properties={"name": "Bob"})
txn_a.commit()
# This works: one transaction at a time
with db.write() as txn:
txn.create_node(labels=["Person"], properties={"name": "Alice"})
txn.create_node(labels=["Person"], properties={"name": "Bob"})
txn.commit()
Batching writes into one transaction like this is also faster, because the durability work that makes a commit safe happens once instead of twice.
If your program writes from several threads or tasks, put the writes behind something that serialises them — a lock, a queue, a single writer task — rather than catching the error and retrying in a loop. Retrying works, but it burns effort re-attempting something you already know will fail until the other writer finishes.
Running a query picks its own mode
You do not have to decide this yourself for ordinary queries. db.query() looks
at what the query does and opens the transaction it needs: a read-only one for
MATCH and friends, a read-write one for CREATE, SET, DELETE, MERGE,
and REMOVE.
That means a read never takes the writer slot, so reads keep running alongside
an open write transaction, while a write through query() still has to wait its
turn like any other writer.
db.query("MATCH (p:Person) RETURN p.name") # read-only, runs alongside a writer
db.query("CREATE (p:Person {name: 'Ada'})") # needs the writer slot
Explicit transactions are still there when you want several statements to
succeed or fail together, which a single query() call cannot express.
Schema changes count as writes
Creating or dropping a property index is also refused while a write transaction is open, with the same error. Do schema work when no transaction is in flight:
db.create_node_property_index("Person", "email") # no open write transaction
Physical compaction is stricter still: lattice compact refuses to run while any
transaction is open, read or write.
One process at a time
Everything above is about transactions inside one process. There is a second, coarser rule underneath it: a database can only be open in one process at a time.
Opening a database takes a lock on the file. A read-write handle takes it exclusively, and a read-only handle shares it, so:
- A second process trying to write is refused.
- A reader is refused while a writer holds the database.
- Any number of readers can share a database that nobody is writing.
You will see this as an error at the moment you open it, rather than as damage discovered later:
Error: social.lattice is open in another process. Close it first, or pass
--no-lock if you are certain nothing is writing to it.
| Language | What you get |
|---|---|
| C | LATTICE_ERROR_DATABASE_LOCKED (-16) returned from lattice_open_v5 (and the older open functions) |
| Python | LatticeDatabaseLockedError raised |
| TypeScript | LatticeError thrown, with .code === -16 |
| Go | ErrorDatabaseLocked on the returned error's Code |
| Zig | DatabaseError.DatabaseLocked from Database.open |
Note that this is a different error from the one above. LATTICE_ERROR_LOCK_TIMEOUT
means somebody in your process is already writing; LATTICE_ERROR_DATABASE_LOCKED
means the database belongs to a different process entirely.
Why readers are excluded too
It would be convenient to let another process read while yours writes, and it would also be wrong. A reader in another process cannot see the writer's buffered pages or the commits it has not yet folded into the file. What it would read is a version of the file that a checkpoint may be rewriting underneath it, which can produce a structurally inconsistent view rather than merely an out-of-date one.
After a crash, when no writer holds the database, a read-only open does see every committed transaction: it replays the log in memory, without writing to the files. See Durability and the Log.
The lock does not create that restriction. It reports it.
Turning it off
Every language can turn the lock off, for filesystems where locking does not work — some network filesystems, notably — and where the alternative is not being able to open the database at all:
db = latticedb.Database("social.lattice", lock=False)
const db = new Database('social.lattice', { lock: false });
db, err := latticedb.Open("social.lattice", latticedb.OpenOptions{DisableLock: true})
lattice count social.lattice --no-lock
Go phrases it as a negative because a Go bool cannot tell an omitted field from a
deliberate false, and locking has to stay on when the caller says nothing. The
same reasoning already governs DisableWAL there.
Turning the lock off does not make concurrent access safe. It removes the thing that was going to tell you it was not.
Backup and Replication
A database on one disk is one disk failure away from gone. This guide covers the three things LatticeDB gives you to prevent that: taking a copy, keeping a copy continuously up to date, and getting a database back from one.
If you have used Litestream with SQLite, the shape here will be familiar. The goal is the same: one machine, one writer, a few minutes of tolerable downtime, and no desire to lose the last hour of work when the disk dies.
The rule that comes first
Do not back up a database by copying the file while it is open.
This is the mistake that costs people their data, and it costs them quietly. The write-ahead log holds committed changes that are not in the main file yet, so:
- Copying only the main file gives you a database that opens and then fails when you query it.
- Copying both files catches them at two different instants and gives you a pair that fails on open.
Neither announces itself at copy time. You find out when you need the backup, which is the worst possible moment. Use one of the commands below, or stop the process first.
Taking one copy
backup copies a running database to another file:
lattice backup social.lattice --file=/backups/social-2026-08-25.lattice
From Zig code, the same thing is a method on the database. The C API and the
language bindings do not expose backup or replication; from Python, TypeScript,
Go or Java, use the lattice command while nothing else has the database open.
const stats = try db.backup("/backups/social-2026-08-25.lattice");
Pending writes are folded into the file before the copy starts, so what you get is a complete database on its own. It needs no log beside it, and you can open it directly.
Two things to know. The copy captures the database as of the moment it starts, so writes that land while it runs are not included. And it refuses to run while a transaction is open, because a copy taken while writes land underneath it is torn in ways no later check would catch.
This is the right tool for a nightly snapshot. It is the wrong tool for "I do not want to lose the last hour", because an hour is exactly how much you lose.
Keeping a copy up to date
replicate ships changes into a directory. The first pass copies the whole
database; later passes copy the write-ahead log frames written since, when the
log still holds them (see Generations):
lattice replicate social.lattice --to=/mnt/backup/social
Run it on a timer, from cron or a scheduler, and the destination trails your database by roughly that interval. A pass with nothing to ship is normal, says so, and exits successfully, so this does not fill your logs with things that look like failures.
--follow keeps the command running and replicating on an interval:
lattice replicate social.lattice --to=/mnt/backup/social --follow --interval=30
Each pass opens the database, which takes its file lock, and closes it again,
so other processes can use the database between passes. A pass that finds the
database open in another process is skipped until the next interval, and a
process that tries to open the database during the moment a pass is running is
refused and can retry. A database your application keeps open the whole time
cannot be followed this way; call replicateTo from the application.
Why later passes are cheap
Every change is written to the write-ahead log before it reaches the database file. Replication copies frames out of that log, so a pass has to move only what was actually written, not the whole database again. That holds while the log still has those frames, which is the case for an application that keeps the database open and replicates through its own handle (below).
Generations
Every so often LatticeDB folds pending changes into the database file and starts the log over. By default this happens once the log reaches a thousand frames, and when a database that has been written to closes.
When the log starts over, frame numbering restarts from zero. Frame 40 before the reset and frame 40 after it are completely different changes, so replication cannot simply keep counting. Instead it starts a generation: a fresh full snapshot, followed by the changes that came after it.
A process that writes and then closes the database therefore leaves a reset log
behind, and the next pass starts a new generation. When your writers are
separate short-lived processes, such as lattice exec or a script, each pass
after a change is a full snapshot, and a pass with nothing changed ships
nothing. Frames are shipped incrementally only when the process doing the
writing also does the replicating.
You will see this in the destination:
/mnt/backup/social/manifest.json
/mnt/backup/social/gen-0000000001/snapshot.lattice
/mnt/backup/social/gen-0000000001/frames/0000000012-0000000016.frames
/mnt/backup/social/gen-0000000002/snapshot.lattice
(The frames/ files come from passes made through replicateTo; passes made
by the command against a closed database add only gen- snapshots.)
Older generations are kept rather than cleaned up, because restoring to a moment
inside one still needs its frames. If you want to reclaim the space, deleting a
whole gen- directory costs you the ability to restore to any moment inside it
and nothing else.
Replicating a database your application is using
lattice replicate opens the database, and a database can only be open in one
process at a time. Point it at a database your application has open and it will
refuse to start, rather than corrupt anything:
Error: social.lattice is open in another process. Close it first, or pass
--no-lock if you are certain nothing is writing to it.
That makes the command right for a database nothing else is using. For the case
people most often want, which is replicating while an application runs, a Zig
application can call replicateTo on the handle it already has (the C API and
the language bindings do not offer it):
// Somewhere on a timer inside your application.
const stats = try db.replicateTo("/mnt/backup/social");
This lives on the database rather than in a separate process for a concrete reason. A generation opens with a snapshot, a snapshot has to be taken with no writes in flight, and only the handle that owns the database can arrange that. Reading the log from another process is perfectly safe; taking the snapshot is not.
Do not reach for --no-lock to work around this. It exists for filesystems where
locking does not work, and it does not make two processes safe — it only removes
the thing that was going to tell you they were not.
Getting a database back
restore turns a replication directory back into a database:
lattice restore /mnt/backup/social --output=recovered.lattice
Restored /mnt/backup/social to recovered.lattice
Generation: 1
Segments: 2
Frames replayed: 20
Bytes written: 73728
Restored to: 2026-08-25T22:44:18Z
Duration: 468 ms
It copies the snapshot, replays the changes shipped after it, and folds the result into a single file. What you get back is a database you can open, copy, or move, with nothing beside it that has to be kept together with it.
Restore will not write over an existing file unless you pass --force, because
the thing most likely to be sitting at the output path is a database somebody
still wants.
Going back to an earlier moment
lattice restore /mnt/backup/social --output=recovered.lattice --at="2026-08-25T14:00:00Z"
Times are read as UTC, so a restore means the same thing wherever you run it. A bare date works too and means midnight.
What you get is the state as of the last replication pass at or before the moment you asked for, not the state at that exact instant. If you replicate every thirty seconds, you can rewind to within thirty seconds. That is why the output reports the moment it actually restored to instead of repeating the one you asked for: those two are rarely the same, and the difference is the thing you need to know.
Why restore reuses recovery
Restore does not have its own replay logic. It rebuilds a log from what was shipped and then opens the database, which replays it exactly the way recovery replays a log after a crash.
That is deliberate. Replaying log records is subtle, and a second implementation would drift away from the real one over time. If recovery has a bug, restore should have the same bug rather than a different one.
Choosing a strategy
| What you want | What to use |
|---|---|
| A copy before an upgrade or a risky migration | lattice backup |
| A nightly snapshot | lattice backup from cron |
| To lose no more than a few seconds of work | replicateTo on a timer in your application (Zig only) |
| To keep restore points of a database written by separate processes | lattice replicate on a timer |
| To undo a bad migration or a bad delete | lattice restore --at=... |
| Many small databases kept in a bucket | serialize and deserialize |
| A database that never touches the disk | open :memory: |
What this is not
This is backup and restore. It is not high availability, and it is not clustering. There is no failover, no leader election, and no second writer. A restored database is a database you open yourself, on purpose, after deciding that you need it.
Replicating to object storage such as S3 is not supported yet. The destination layout was designed with it in mind — whole files, written once, named rather than modified, with a manifest listing them — so a directory you replicate to today can be copied to a bucket by any tool you already trust.
Keeping many small databases in object storage
Everything above assumes one database you want to protect. There is a different shape of problem that comes up just as often: not one big graph, but many small ones — a database per case, per tenant, per document — living in S3 or Azure Blob Storage, pulled down when you need one and pushed back when you are done.
That works because a database here is a single file. Serializing one is reading that file, and there is no container format to invent:
blob = s3.get_object(Bucket=bucket, Key=key)["Body"].read()
db = latticedb.deserialize(blob)
db.query("CREATE (n:Note {text: 'found something'})")
s3.put_object(Bucket=bucket, Key=key, Body=db.serialize(), IfMatch=etag)
The same pair exists in every binding: serialize() on the database returns
bytes, and deserialize (a package-level function in Python and TypeScript,
latticedb.Deserialize in Go, Database.deserialize in Java,
lattice_serialize and lattice_deserialize in C) opens a database from them.
Pending writes are folded in before the bytes are handed over, so what you upload is a complete database that needs no log beside it. You can write those bytes to a file and open it directly if you ever want to look at one by hand.
The engine does no networking here, on purpose. Your application already has a storage client, credentials, and a retry policy somebody chose deliberately. A database that reimplemented all of that would be doing a worse job of something you already have, and it would have to hold your cloud credentials to do it.
Never touching the disk
Pass :memory: as the path and the database has no files behind it at all:
db = latticedb.Database(":memory:")
db.open()
const db = new Database(':memory:');
await db.open();
db, err := latticedb.Open(":memory:", latticedb.OpenOptions{})
lattice exec :memory: --query="CREATE (n:Note {t: 'scratch'})"
deserialize uses this too, so a database pulled out of a bucket never becomes a
file on the way in. That matters if you are running one of these per request, on
a read-only filesystem, or anywhere writing a temporary copy of somebody's data
to local disk would be awkward to explain.
An in-memory database behaves like any other. It has transactions, it has a write-ahead log, and you can serialize it back out. The only differences are that it disappears when you close it and that nothing locks it, since there is no second process that could reach it.
It is also cheaper than you might expect for small databases. The page cache is capped at 64 pages (256 KB at the default page size) whatever cache size you ask for, because a miss against memory is only a copy. A hundred-kilobyte database costs a few hundred kilobytes in memory, rather than the 100 MB cache a file-backed one opened through the C API or a binding reserves by default. If you are keeping many small databases open at once, that difference is most of what you pay. See In-Memory Databases for measurements.
Loading without a second copy
By default deserialize copies your bytes, so the database exists twice while it
loads. Tell it not to and it points at your buffer instead:
db = latticedb.deserialize(blob, copy=False)
const db = deserialize(blob, {}, false);
Each page becomes a copy of its own the first time something writes to it, so a database you read and edit lightly keeps one copy of nearly all of itself. Your buffer is never modified, and the database holds a reference to it for as long as it is open, so there is nothing for you to keep alive by hand.
Go and Java do not offer this. That is not an oversight in those bindings: Go's rules say C code may not keep a pointer into the Go heap after a call returns, and pinning a Java array for the lifetime of a database would hold up the garbage collector for exactly that long. Both copy instead, which is correct and costs one duplicate at load.
Two workers, one blob
This pattern has a failure mode worth planning for, and it is not in the database. If two workers read the same object, change it, and write it back, the second one silently erases the first. Nothing reports an error, and nothing looks wrong until somebody notices missing data.
That is what IfMatch is doing in the example above. Every major provider
supports some form of conditional write keyed on an entity tag or generation
number, and the write fails instead of destroying the other worker's changes.
What to do when it fails — retry, merge, queue — is a decision only your
application can make.
Related reading
- Transactions and Durability for what "committed" means
- The
latticeCommand for every option these commands take
Property Indexes
By default, finding a node by one of its properties means looking at every node with that label and checking. That is fine for a few thousand nodes and slow for a few million. A property index gives LatticeDB a direct route from a value to the nodes that hold it.
You create one for a specific label and property, such as every Person node's
email. From then on, looking up a person by email goes straight to the answer
instead of scanning.
Creating one
Indexes belong to the database, not to a transaction, so you create them on the database handle:
db.create_node_property_index("Person", "email")
await db.createNodePropertyIndex("Person", "email");
err := db.CreateNodePropertyIndex("Person", "email")
lattice_node_property_index_create(db, "Person", "email");
Creating an index scans the nodes that already exist so that the ones already in the database are included. On a large database that takes a moment, and it is work you only pay once.
Edges work the same way, using the edge type where a node would use its label:
db.create_edge_property_index("REVIEWED", "year")
Looking things up
Once the index exists, ask for nodes by value:
with db.read() as txn:
ids = txn.find_nodes_by_label_property("Person", "email", "[email protected]", limit=10)
# ids -> [1]
name = txn.get_property(ids[0], "name")
# name -> "Alice"
You get node IDs back rather than whole nodes, which keeps the lookup cheap when
you only need to know what matched. Read the properties you actually want with
get_property.
The same call in the other languages:
const ids = await txn.findNodesByLabelProperty("Person", "email", "[email protected]", 10);
ids, err := tx.FindNodesByLabelProperty("Person", "email", "[email protected]", 10)
lattice_nodes_find_by_label_property(
txn, "Person", "email", &value, /* limit */ 10, &node_ids, &count);
Edges use find_edges_by_type_property, findEdgesByTypeProperty,
FindEdgesByTypeProperty, or lattice_edges_find_by_type_property:
with db.read() as txn:
edge_ids = txn.find_edges_by_type_property("REVIEWED", "year", 2024, limit=10)
Every lookup is limited
Every lookup takes a limit, and it has to be greater than zero. Go, Java and C require it; Python and TypeScript default it to 100, so leaving it out returns at most 100 IDs:
txn.find_nodes_by_label_property("Person", "email", "[email protected]", limit=0)
# ValueError: limit must be positive
This is deliberate. An unbounded lookup on a common value could return a very large list. Pass a larger limit when a value can match more than 100 records.
Asking for an index that does not exist
If you look up a property with no index behind it, the call fails rather than quietly scanning instead:
with db.read() as txn:
txn.find_nodes_by_label_property("Person", "email", "[email protected]", limit=10)
# LatticeUnsupportedError: Unsupported operation or value type
This one surprises people, so it is worth saying plainly why it works this way. A lookup that silently fell back to a full scan would still return the right answer, so nothing would look broken. You would simply get scan performance while believing you had index performance, and you would find out under load. Failing tells you immediately.
The same happens after you drop an index. Nothing else changes, but that lookup stops working:
db.drop_node_property_index("Person", "email")
Creating an index that already exists is also an error, LatticeAlreadyExistsError,
rather than a silent no-op.
Cypher uses your indexes automatically
You do not have to change your queries. When the planner sees a query it can answer through an index, it uses it. Both of these forms qualify:
MATCH (p:Person {email: "[email protected]"}) RETURN p.name
MATCH (p:Person) WHERE p.email = "[email protected]" RETURN p.name
Writing the comparison the other way round works too, so WHERE "[email protected]" = p.email
is recognised just the same.
An AND still qualifies, because every row has to satisfy both sides. The
planner uses the index for the part it can and checks the rest normally:
MATCH (p:Person)
WHERE p.email = "[email protected]" AND p.team = "platform"
RETURN p.name
An OR does not qualify, and this is the interesting case. A row only has to
satisfy one side, so narrowing to either branch would throw away rows that match
the other. The query still returns the correct answer; it just gets there by
scanning:
MATCH (p:Person)
WHERE p.email = "[email protected]" OR p.email = "[email protected]"
RETURN p.name
The rule of thumb is that an index can help when a condition must be true, and cannot when it is only one of several ways to match.
Ranges, prefixes and sorting
An index keeps its values in order, so it also answers comparisons and prefixes.
With an index on Person(age) and one on Person(name):
MATCH (p:Person) WHERE p.age >= 30 AND p.age < 40 RETURN p.name, p.age
┌─────────┬───────┐
│ p.name │ p.age │
├─────────┼───────┤
│ "Alice" │ 34 │
│ "Carol" │ 38 │
└─────────┴───────┘
MATCH (p:Person) WHERE p.name STARTS WITH 'Al' RETURN p.name
┌─────────┐
│ p.name │
├─────────┤
│ "Alan" │
│ "Alice" │
└─────────┘
<, <=, > and >=, written either way round, and STARTS WITH qualify.
Several comparisons on one property joined by AND become one range. The
comparisons the index answers are not checked again row by row, except where
the index cannot decide on its own: a string bound longer than 128 bytes.
An equality on an indexed property is preferred to a range; without statistics,
a range on an indexed property is always read through the index, which measured
no slower than a scan even when the range holds every node.
A query that sorts by an indexed property and stops after a few rows reads the index in order and stops as soon as it has them, rather than sorting every node:
MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age LIMIT 3
┌─────────┬───────┐
│ p.name │ p.age │
├─────────┼───────┤
│ "Bob" │ 29 │
│ "Alice" │ 34 │
│ "Carol" │ 38 │
└─────────┴───────┘
Descending works the same way, and the index puts nodes without the property
where ORDER BY puts nulls, last ascending and first descending:
MATCH (p:Person) RETURN p.name, p.age ORDER BY p.age DESC LIMIT 3
┌─────────┬───────┐
│ p.name │ p.age │
├─────────┼───────┤
│ "Dan" │ null │
│ "Alan" │ 41 │
│ "Carol" │ 38 │
└─────────┴───────┘
That applies to a single MATCH pattern, with or without a WHERE, whose
RETURN does not aggregate or use DISTINCT, sorted first by the property,
either way, with a LIMIT. Rows with equal values come in the same order as
without the index. A WHERE with a vector or full-text search keeps the
ordinary sort, since the search returns its rows nearest or best first.
On 200,000 :Person nodes (a release build, median of seven runs):
| query | without an index | with one |
|---|---|---|
WHERE p.age > 97 (4,000 rows) | 48 ms | 1.4 ms |
WHERE p.score >= 500 AND p.score < 505 (978 rows) | 54 ms | 0.3 ms |
WHERE p.name STARTS WITH 'Jo' (293 rows) | 48 ms | 0.10 ms |
ORDER BY p.score LIMIT 10 | 46 ms | 0.01 ms |
ORDER BY p.score DESC LIMIT 10 | 46 ms | 0.01 ms |
WHERE p.age >= 50 RETURN count(p) (half the nodes) | 49 ms | 3.4 ms |
WHERE p.age >= 0 (every node) | 114 ms | 88 ms |
A relationship type's index answers the same comparisons, and equality, for a
pattern that starts from the relationship: a single relationship type, with
nothing known about the node it starts from. With an index on KNOWS(since):
MATCH (a)-[r:KNOWS]->(b) WHERE r.since >= 2020 RETURN a.name, b.name, r.since ORDER BY r.since
┌─────────┬─────────┬─────────┐
│ a.name │ b.name │ r.since │
├─────────┼─────────┼─────────┤
│ "Alice" │ "Carol" │ 2021 │
│ "Bob" │ "Alan" │ 2023 │
└─────────┴─────────┴─────────┘
An inline map, -[r:KNOWS {since: 2021}]->, works the same way. Reading a
relationship through the index costs about four times what walking every
relationship costs per relationship, so when the range holds a fifth of them or
more, the query walks them instead. On 1,000,000 :KNOWS relationships with
w spread over 0 to 9,999:
| query | without an index | with one |
|---|---|---|
WHERE r.w = 1234 (115 rows) | 177 ms | 0.09 ms |
WHERE r.w > 9990 (944 rows) | 176 ms | 0.7 ms |
WHERE r.w >= 100 AND r.w < 200 (about 10,000 rows) | 224 ms | 9.5 ms |
WHERE r.name STARTS WITH 'Jo' (1,447 rows) | 183 ms | 1.2 ms |
WHERE r.w >= 5000 (half, walked) | 280 ms | 280 ms |
Values of different types are kept in the order ORDER BY puts them in, and
integers and floats compare by exact value, as in the rest of Cypher: 3 and
3.0 are one value, and 9007199254740993 is greater than
9007199254740992.0.
Keeping up with changes
You do not have to maintain anything. Once an index exists, it is updated by ordinary writes, whether those go through a transaction or directly:
with db.write() as txn:
txn.create_node(labels=["Person"], properties={"name": "Dan", "email": "[email protected]"})
txn.commit()
with db.read() as txn:
txn.find_nodes_by_label_property("Person", "email", "[email protected]", limit=10)
# -> [4]
Indexes are stored in the database file, so they survive closing and reopening, and they are rebuilt during recovery if the process stops unexpectedly. Creating or dropping an index is written to the file before the call returns, so a crash right after it cannot undo it.
Creating an index needs the database to itself
Creating or dropping an index is refused while a write transaction is open:
with db.write() as txn:
txn.create_node(labels=["Person"], properties={"name": "Erin"})
db.create_node_property_index("Person", "name")
# LatticeLockTimeoutError: Lock timeout
Do index work when nothing else is in flight, usually at startup or during a migration rather than in the middle of request handling. This is the same one-writer rule that applies to transactions; see One writer at a time.
Choosing what to index
An index costs you something. It uses space in the file, it makes creation slower the first time because of the initial scan, and it adds a little work to every write that touches the indexed property, and to every node created with the label but without the property, which the index holds too so that it can sort them. That is a good trade for a lookup your application does constantly, and a bad one for a property you query once a month.
Some things worth knowing before you add one:
- Index for lookups you actually perform. An index on a property nothing looks up is pure cost.
- Indexes answer equality, ranges and prefixes (on relationships, for a
pattern that starts from the relationship type), not text inside a longer
string (
CONTAINS,ENDS WITH). For finding words in text, you want full-text search instead. - High-variety properties benefit most. An index on
email, where almost every value is unique, narrows millions of nodes to one. An index on a property with three possible values only narrows to a third, which a scan would have managed nearly as fast. - Index the pair, not the property. An index covers one label and property
together. Indexing
emailonPersondoes nothing foremailonCompany.
Indexes and older releases
Creating a property index with this release raises the file's minimum reader version to 4, so LatticeDB 0.16.0 refuses it rather than misreading the index. Dropping the index does not undo the mark. A file without one is not kept out by its indexes, though with the changefeed on, as it is by default, the first commit keeps 0.16.0 out anyway; see Opening with 0.16.0.
An index that 0.16.0 created keeps working for equality, but is not used for
ranges, prefixes or sorting until it is rebuilt. lattice info lists each
index with its encoding: digest is the 0.16.0 one, ordered_dense (a
label's) and ordered (a relationship type's) are this release's. The
encoding column of CALL db.indexes() says the same:
lattice info people.lattice
...
Index: :Person(age) digest
lattice compact --upgrade-indexes rebuilds every index in an older encoding
in place, keeping its label or type and property, and then compacts as usual:
lattice compact people.lattice --upgrade-indexes
Compacted database: people.lattice
Indexes rebuilt: 1
Pages before: 1036
Pages after: 1036
Pages removed: 0
Bytes reclaimed: 0
From Zig, Database.upgradePropertyIndexes() does the same and returns how
many it rebuilt. Either way it reads every node of the label (or relationship
of the type) once, as creating the index does, in one step that a crash
undoes completely, and it marks the file as needing format 4 as creating an
index does.
Where to go next
- Performance Tuning for the other things that affect query speed
- Full-Text Search for matching words inside text
- Working with Embeddings for finding things by similarity rather than equality
Performance Tuning
This guide covers the key parameters for tuning LatticeDB performance.
Cache Size
The cache_size_mb parameter controls how many database pages are cached in memory. Larger caches reduce disk I/O.
db = Database("mydb.db", cache_size_mb=200) # 200 MB cache
db.open()
Guidelines:
- Default is 100 MB in the C API and every binding (64 MB in the CLI), which handles most workloads well
- For large databases (1M+ nodes), increase to 200-500 MB
- For memory-constrained environments, reduce to 50 MB or less
- The cache stores fixed-size pages (4 KB each at the default page size), so 100 MB holds ~25,000 pages
- The
LATTICE_BUFFER_POOL_MBenvironment variable sets the size when the program does not; an explicitcache_size_mbwins over it - In-memory (
:memory:) databases cap the cache at 64 pages whatever you ask for
Vector Search: ef_search
The ef_search parameter controls the accuracy/speed tradeoff for HNSW vector search.
Mean latency and recall@10 over 128-dimensional clustered vectors, measured through the C API with the default 100 MB cache (0.17.0, Apple M5; method and more scales on Benchmarks):
| ef_search | 100,000 vectors | Recall@10 | 1,000,000 vectors | Recall@10 |
|---|---|---|---|---|
| 16 | 55 us | 90.7% | 0.71 ms | 72.5% |
| 32 | 86 us | 96.3% | 1.05 ms | 87.7% |
| 64 (default) | 123 us | 98.3% | 1.54 ms | 95.6% |
| 128 | 180 us | 98.5% | 2.0 ms | 98.4% |
| 256 | 266 us | 98.5% | 2.5 ms | 98.5% |
Guidelines:
- Default is 64: about 98% recall at 100K vectors on this data, about 96% at 1M
- At a million vectors, 128 buys back the last few points of recall for about a third more time
- Below 64, recall falls quickly as the index grows
- Past 128, latency rises and recall does not
- At 1M vectors the cache matters more than
ef_search: see Memory Usage below
# Programmatic API
results = db.vector_search(query_vec, k=10, ef_search=128)
ef_search is the only search setting that can change after the index exists. The
index's m (connections per node, 2 to 32, default 16) and ef_construction (the
candidate list while inserting, 1 to 4096, default 200) are chosen when the database
is created (vector_m and vector_ef_construction in the bindings, --vector-m
and --vector-ef-construction in lattice create) and are fixed afterwards. A
larger m or ef_construction builds a better-connected graph, at the cost of
slower inserts and, for m, more memory.
Batch Insert
When loading large amounts of vector-bearing nodes, batch_insert_vectors creates a node and stores its vector for every row in one call:
import numpy as np
with db.write() as txn:
# Fast: ~248 inserts/sec at 1M scale
vectors = np.random.rand(10000, 128).astype(np.float32)
node_ids = txn.batch_insert_vectors("Document", vectors)
txn.commit()
It saves one binding call per node. It does not amortize HNSW work: each vector is still inserted into the index individually, exactly as set_vector would.
Query Caching
Use parameterized queries so the cache can reuse the parsed query. The cache is keyed by query text and holds the parsed, analysed query (not an execution plan):
# Good: parsed once, reused
for name in names:
db.query("MATCH (n:Person) WHERE n.name = $name RETURN n", parameters={"name": name})
# Bad: every distinct query text is parsed again
for name in names:
db.query(f"MATCH (n:Person) WHERE n.name = '{name}' RETURN n")
Monitor cache effectiveness:
stats = db.cache_stats()
print(f"Hit rate: {stats['hits'] / (stats['hits'] + stats['misses']):.1%}")
Indexing Strategy
Full-Text Search
Declare a full-text index only over properties you actually search. Every declared index is maintained on every write that touches its property, so an index nobody queries is pure cost:
# The text people search
db.create_node_fts_index("Chunk", "text")
# Not metadata, IDs, or timestamps
Then write queries that can use it. A @@ predicate reads the index directly when
it is the whole WHERE or a branch of an AND, and falls back to examining every
node carrying the label when it sits under an OR beside a non-text condition.
See Full-Text Search.
Property Indexes
Declare a property index on what queries filter or sort by. Cypher reads it for
equality, ranges (<, >=, ...), STARTS WITH and ORDER BY ... LIMIT in
either direction, on nodes of a label and on relationships of a type. An index
created by 0.16.0 answers equality only until lattice compact --upgrade-indexes rebuilds it. See Property Indexes.
Labels
Use specific labels for nodes you query frequently. Label scans are fast because they use a dedicated index:
// Fast: scans only Chunk nodes
MATCH (c:Chunk) WHERE c.source = "web" RETURN c
// Slower: scans all nodes
MATCH (n) WHERE n.source = "web" RETURN n
A label narrows a <=> vector search as well: the rows the pattern produces are
the candidates, and the search looks only among them. A small candidate set is
measured node by node, exactly, and a large one is searched through the HNSW
graph with the set as a filter, so a rare label is cheap rather than costly
(about 10 to 20 µs for LIMIT 10 over 100 labelled nodes among 100,000
vectors). To get the nearest k, write the distance in the WHERE and
end with ORDER BY that same distance and LIMIT k: the search then stops once it
has k rows, instead of finding every candidate under the threshold and sorting
them. Write the distance in the RETURN the same way as in the WHERE to reuse
the value the search measured. See Vector Search in Cypher.
Bulk Loading and the Changefeed
Every committed change is also recorded in the changefeed, which by default keeps
every event and can make up most of a file. A database nothing reads the history
of can keep less, or none (changefeed_retention); see
The Changefeed. A load you can rerun from its source can also
run without the log and with a large cache; see
Bulk loading.
Transaction Scope
Keep write transactions short. Only one write transaction can be open at a time, and while one is open, beginning another fails immediately with a lock-timeout error rather than waiting:
# Good: small, focused transactions
for batch in chunks(data, 1000):
with db.write() as txn:
for item in batch:
txn.create_node(labels=["Item"], properties=item)
txn.commit()
# Bad: one giant transaction
with db.write() as txn:
for item in all_data: # millions of items
txn.create_node(labels=["Item"], properties=item)
txn.commit()
Memory Usage
A 128-dimensional vector takes about 1.1 KB of file with its index. What a process holds is bounded by the page cache, plus a few MB:
| Vectors (128-d) | File | Memory, default 100 MB cache | Search p50, default cache | With a larger cache |
|---|---|---|---|---|
| 1,000 | 1.2 MB | 3 MB | 35 us | |
| 10,000 | 11 MB | 13 MB | 66 us | |
| 100,000 | 108 MB | 108 MB | 122 us | 121 us (1 GB cache, 119 MB) |
| 1,000,000 | 1,074 MB | 185 MB | 1.34 ms | 0.21 ms (2 GB cache, 1.1 GB) |
"Memory" is what opening the database and searching added to the process. Once the
file outgrows the cache, searches read pages back from the operating system's file
cache (or the disk) and get several times slower, and inserts slow down far more
(see Benchmarks): building a million
vectors took 75 minutes with the default cache and 18 with a 2 GB one. For a
million vectors, give the cache about the size of the file. Lower vector_dimensions use
less of both, but capture less semantic information.
Cypher Overview
LatticeDB uses the Cypher query language for graph operations. Cypher is a declarative language where you describe patterns to match and operations to perform, rather than specifying how to execute them.
Syntax at a Glance
Nodes are written in parentheses, edges in square brackets:
// Match a pattern
MATCH (person:Person)-[:KNOWS]->(friend:Person)
WHERE person.name = "Alice"
RETURN friend.name
Supported Clauses
| Clause | Purpose |
|---|---|
| MATCH | Find patterns in the graph |
| WHERE | Filter results with conditions |
| RETURN | Specify output columns |
| CREATE | Create nodes and edges |
| SET | Update properties and labels |
| DELETE | Remove nodes and edges |
| REMOVE | Remove properties and labels |
| MERGE | Match or create a pattern |
| WITH | Chain query parts, pipe results |
| UNWIND | Expand lists into rows |
| OPTIONAL MATCH | Match a pattern, or keep the row with nulls when it is absent |
| UNION / UNION ALL | Combine the rows of queries with the same columns |
| FOREACH | Run CREATE, SET, MERGE, DELETE, REMOVE or a nested FOREACH for each element of a list |
| CALL { } | Run a subquery once for each row |
| CALL db.labels() | List the catalog: db.labels(), db.relationshipTypes(), db.propertyKeys(), db.indexes() |
| ORDER BY | Sort results, with NULLS FIRST or NULLS LAST |
| LIMIT | Limit number of results |
| SKIP | Skip first N results |
A query may begin with MATCH, OPTIONAL MATCH, CREATE, MERGE, UNWIND,
WITH, RETURN, CALL or FOREACH; RETURN 1 + 2 on its own returns one row.
Only a RETURN, or a catalog CALL that is the whole query, gives a query
columns: a query without one, such as a bare CREATE, MERGE, SET, DELETE
or FOREACH, returns no columns and no rows. Add a RETURN to get values back.
MATCH (p:Person)
OPTIONAL MATCH (p)-[:MANAGES]->(r:Person)
RETURN p.name AS name, collect(r.name) AS reports
UNION
MATCH (t:Team) RETURN t.name AS name, [] AS reports
MATCH (a:Person {name: "Alice"})
FOREACH (tag IN ["admin", "owner"] | CREATE (a)-[:HAS]->(:Tag {name: tag}))
A CALL of a catalog procedure that is the whole query returns its columns;
inside a larger query it names them with YIELD:
CALL db.labels() YIELD label
RETURN label ORDER BY label
Expressions beyond the basics
| Construct | Example |
|---|---|
CASE | CASE WHEN n.age >= 18 THEN 'adult' ELSE 'minor' END, CASE n.kind WHEN 'a' THEN 1 END |
| Indexing and slicing | list[0], list[-1], list[1..3], map['key'], n[$prop] |
| List comprehension | [x IN list WHERE x > 0 | x * 2] |
| List predicates | all(x IN list WHERE x > 0), any(...), none(...), single(...) |
reduce | reduce(total = 0, x IN list | total + x) |
| Pattern predicate | WHERE (n)-[:KNOWS]->(), WHERE NOT (n)-->() |
EXISTS { }, COUNT { }, COLLECT { } | EXISTS { (n)-[:KNOWS]->(m) WHERE m.age > 30 }, COUNT { (n)--() }, COLLECT { MATCH (n)-->(m) RETURN m.name ORDER BY m.name }; see Subqueries in expressions |
| Pattern comprehension | [(n)-[:KNOWS]->(m) WHERE m.age > 30 | m.name] |
| Named path | MATCH p = (a)-[:KNOWS*]->(b) RETURN length(p), nodes(p), relationships(p) |
| Shortest path | MATCH p = shortestPath((a)-[:KNOWS*]-(b)); see Shortest Paths |
| Label test | n:Person, n:Person:Admin, n:Person|Robot, n:!Admin; r:KNOWS tests a relationship's type; see Label Expressions |
exists() on a property | exists(n.email), the same as n.email IS NOT NULL |
| Map projection | n {.name, .age, friends: size(fs)}, n {.*}; see RETURN |
RETURN *, WITH * | every variable in scope; see RETURN |
| Literals | 0x1F, 0o17, .5, `a name with spaces` |
Not Supported
These parts of Cypher are not implemented. Each fails before the query runs, with an error that names it:
- quantified and parenthesised path patterns, such as
((a)-->(b)){1,3}or(x) ((a)-->(b))+, and quantified relationships such as-[:R]->{1,3}or-[:R]->+; use a variable-length relationship-[:R*1..3]-> &,!and%in a relationship's types, as in-[:!KNOWS]->; useWHERE NOT r:KNOWSWHEREinside a pattern, as in(n WHERE n.age > 30)- writing inside
EXISTS { },COUNT { }orCOLLECT { } CALL { } IN TRANSACTIONS,OPTIONAL CALL, and procedures other than the four catalog procedures aboveLOAD CSV; import files withlattice importor through the API- type predicates (
x IS :: INTEGER) and||for concatenation (use+) - schema and administration statements:
CREATE INDEX,CREATE CONSTRAINT,DROP,SHOW,USE,EXPLAIN,PROFILE,GRANTand the like. Indexes are created through the API. - the GQL clauses
FINISH,FILTER,LETandINSERT, and the legacySTART - temporal and spatial values and the functions on them (
date(),point()) - an integer with a leading zero,
012: openCypher 9 read it as octal and other dialects as decimal, so it is refused with a message giving both; write12, or0o12for octal. Floats may start with zero (01.5).
The limits of shortestPath are listed under
Shortest Paths.
Errors
A query that fails says where and why: the stage that refused it (parse, semantic, plan or execution), a diagnostic code, a message, and the line and column of the part of the query at fault. A plan error has no line and column; its message names the part instead, as in "ORDER BY item 2 aggregates, but the RETURN does not return that aggregate". The CLI prints the place with a marker under that part:
$ lattice exec db.lattice --query="RETURN 1/0"
Error: Execution error (DivisionByZero) at 1:9: Division by zero: 1 / 0
1 | RETURN 1/0
| ^
$ lattice exec db.lattice --query="RETURN 1 LIMIT -1"
Error: Execution error (TypeError) at 1:16: SKIP and LIMIT take a non-negative integer, but this is -1
1 | RETURN 1 LIMIT -1
| ^
$ lattice exec db.lattice --query="RETURN \$nope"
Error: Execution error (ParameterNotFound) at 1:8: Parameter $nope was not given a value
1 | RETURN $nope
| ^^^^^
The bindings carry the same fields on their query error (in Python,
LatticeQueryError with stage, diagnostic_code and location), and the C API
returns them through lattice_query_last_error_*:
from latticedb import LatticeQueryError
try:
db.query("RETURN 1/0")
except LatticeQueryError as e:
print(e, e.code, e.stage, e.diagnostic_code, e.location)
# Division by zero: 1 / 0 -1 execution DivisionByZero {'line': 1, 'column': 9, 'length': 1}
The error code tells what kind of failure it was:
| Failure | Code |
|---|---|
| Parse or semantic error (syntax, unknown function, wrong argument count) | LATTICE_ERROR_INVALID_ARG (-6) |
| Plan or execution error in the query (division by zero, type error, overflow) | LATTICE_ERROR (-1) |
DELETE of a node that still has relationships | LATTICE_ERROR_HAS_RELATIONSHIPS (-17), as from lattice_node_delete |
| A write to a node or relationship that does not exist, or was deleted earlier in the query | LATTICE_ERROR_NOT_FOUND (-4), as from lattice_edge_create |
| The storage underneath failed while the query read or wrote | LATTICE_ERROR_IO (-2) |
| Memory ran out | LATTICE_ERROR_OUT_OF_MEMORY (-13) |
A failure to read stored data fails the query. It is never read as null, so a
WHERE cannot quietly drop a row because a read failed. Null stands only for
what is really absent: a missing property, a deleted node or relationship, a
property name the database has never seen, or a parameter passed as null.
LatticeDB Extensions
LatticeDB extends Cypher with two operators for search:
Vector Distance (<=>)
Find nodes with similar embeddings:
MATCH (chunk:Chunk)
WHERE chunk.embedding <=> $query_vector < 0.5
RETURN chunk.text
ORDER BY chunk.embedding <=> $query_vector
See Vector Search for details.
Full-Text Search (@@)
Search indexed text content:
MATCH (doc:Document)
WHERE doc.content @@ "neural networks"
RETURN doc.title
See Full-Text Search for details.
Expressions
Operators
| Category | Operators |
|---|---|
| Comparison | =, <>, <, <=, >, >= |
| Logical | AND, OR, NOT, XOR |
| Arithmetic | +, -, *, /, %, ^ |
| String | CONTAINS, STARTS WITH, ENDS WITH, =~ (regular expression) |
| List | IN |
| Null | IS NULL, IS NOT NULL |
| Search | <=> (vector distance), @@ (full-text) |
Functions
| Function | Description |
|---|---|
id(node) | Get node ID |
coalesce(a, b, ...) | Return first non-null value |
abs(x) | Absolute value |
size(x) | Length of a list, or characters in a string |
toInteger(x) | Convert to integer |
toFloat(x) | Convert to float |
Function names are not case-sensitive. See Functions for the full list.
Aggregations
| Function | Description |
|---|---|
count(x) | Count non-null values |
count(*) | Count rows |
sum(x) | Sum values |
avg(x) | Average values |
min(x) | Minimum value |
max(x) | Maximum value |
collect(x) | Collect into list |
See Aggregations for details.
Parameters
Use $name syntax to pass values safely:
MATCH (n:Person) WHERE n.name = $name RETURN n
See Parameters for language-specific binding.
MATCH and Patterns
MATCH finds patterns in the graph. It is the primary way to read data.
Node Patterns
Match all nodes:
MATCH (n) RETURN n
Match nodes with a label:
MATCH (p:Person) RETURN p.name
Match nodes with inline property filtering:
MATCH (p:Person {name: "Alice"}) RETURN p
When an explicit index exists for the label/property pair, independent inline equality patterns use it automatically, including parameterized values:
MATCH (p:Person {email: $email}) RETURN p
Create the index through the C, Python, TypeScript, Go or Java database API before
running the query. Equality predicates in the immediately following WHERE
also use an available index:
MATCH (p:Person)
WHERE p.email = $email
RETURN p
The comparison may be reversed or nested within an AND expression. OR
predicates remain scan-backed so the planner cannot discard rows from the
other branch.
The same index answers ranges and prefixes on its property (<, <=, >, >=
and STARTS WITH, several of them joined by AND), and an ORDER BY on it
with a LIMIT, ascending or descending, reads it in order. A relationship
type's index answers equality, ranges and prefixes for a pattern that starts
from the relationship, MATCH (a)-[r:KNOWS]->(b) WHERE r.since >= 2020; see
Property Indexes.
MATCH (n) with no label returns nodes in id order. A pattern that starts from
a relationship type with an unlabelled start node, MATCH (a)-[r:KNOWS]->(b),
walks the relationships of that type and returns its rows in the order they are
stored, not grouped by a. No order is promised for either; add ORDER BY
where order matters.
Label Expressions
(n:A:B) matches nodes with both labels. A label expression says more:
| Expression | Matches nodes |
|---|---|
(n:A|B) | with A or B (also written :A|:B) |
(n:A&B) | with both, as :A:B |
(n:!A) | without A |
(n:%) | with at least one label; (n:!%), with none |
(n:(A|B)&!C) | parentheses group; ! binds tighter than &, and & than | |
The labels joined by & at the top are scanned for as :A:B is; the rest is
checked on each node, so (n:A|B) reads every node. :A:B cannot be mixed with
the other operators; write :A&B|C. CREATE and MERGE take only labels to
give, :A:B or :A&B.
The same expressions test a value in WHERE or RETURN: n:A|B is true when
the node has A or B. On a relationship they test its type, so r:KNOWS is
type(r) = 'KNOWS' and r:A&B is false. A null gives null. Inside a list
comprehension a | ends the condition, so write [x IN list WHERE x:(A|B) | x].
A relationship pattern takes alternative types, -[:KNOWS|LIKES]->, but not
&, ! or %; test the type in a WHERE instead (WHERE NOT r:KNOWS).
Variables
Parentheses bind a matched node to a variable:
MATCH (person:Person)
RETURN person.name, person.age
Variables are used in WHERE, RETURN, SET, and other clauses to reference matched elements.
Edge Patterns
Match edges between nodes:
// Outgoing edge
MATCH (a:Person)-[:KNOWS]->(b:Person)
RETURN a.name, b.name
// Incoming edge
MATCH (a:Person)<-[:KNOWS]-(b:Person)
RETURN a.name, b.name
// Either direction
MATCH (a:Person)-[:KNOWS]-(b:Person)
RETURN a.name, b.name
Edge Variables
Bind edges to variables to access their properties:
MATCH (a)-[r:KNOWS]->(b)
RETURN a.name, r, b.name
Edge Type Filtering
Match specific edge types:
MATCH (a)-[:KNOWS]->(b) RETURN b
MATCH (a)-[:AUTHORED_BY]->(b) RETURN b
List several types with | to match a relationship of any of them:
MATCH (a:Person {name: "Alice"})-[r:KNOWS|LIKES]->(b)
RETURN type(r), b.name
A relationship has one type, so -[:KNOWS:LIKES]-> is a parse error. | is for
MATCH only: CREATE and MERGE need exactly one type.
Multi-Hop Patterns
Chain patterns to traverse multiple hops:
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
RETURN chunk.text, doc.title, author.name
Variable-Length Paths
Match paths of varying length:
// 1 to 3 hops
MATCH (a)-[*1..3]->(b) RETURN b
// Exactly 2 hops
MATCH (a)-[*2]->(b) RETURN b
// 2 or more hops
MATCH (a)-[*2..]->(b) RETURN b
// Any number of hops
MATCH (a)-[*]->(b) RETURN b
See Variable-Length Paths for details.
Multiple MATCH Clauses
Use multiple MATCH clauses to combine patterns:
MATCH (a:Person {name: "Alice"})
MATCH (b:Person {name: "Bob"})
RETURN a, b
A node variable that is already bound can be named again, in a later MATCH, after
WITH, or later in the same pattern, and it stands for the same node. Labels and
properties written at the second mention are checked against that node:
MATCH (a:Person {name: "Alice"})
MATCH (a)-[:KNOWS]->(b)
RETURN b.name
// A cycle back to the starting node
MATCH (a)-[:KNOWS]->(b)-[:KNOWS]->(c)-[:KNOWS]->(a)
RETURN a.name
A relationship variable cannot be matched again: MATCH (a)-[r]->(b) MATCH (c)-[r]->(d) is rejected.
Relationship Uniqueness
Within one MATCH, each relationship is used at most once, as Cypher specifies. A
pattern that walks out over an undirected relationship cannot come straight back
over it, so this does not return Alice as c:
MATCH (a:Person {name: "Alice"})-[:KNOWS]-(b)-[:KNOWS]-(c)
RETURN c.name
The same holds across the comma-separated patterns of one MATCH, and for the
relationships a variable-length hop walks: a later relationship of the same MATCH
cannot use one of them again. Over the two-relationship cycle x->y->x:
MATCH (a:C)-[:R*1..2]->(b)-[:R]->(c)
RETURN a.name, b.name, c.name
// x y x
// y x y
The last hop never reuses a relationship of the path before it, so this returns
two rows, not four. Separate MATCH clauses may reuse a relationship.
WHERE and Filtering
WHERE filters matched patterns based on conditions.
Comparison Operators
MATCH (n:Person) WHERE n.age > 30 RETURN n.name
MATCH (n:Person) WHERE n.age >= 30 RETURN n.name
MATCH (n:Person) WHERE n.age < 30 RETURN n.name
MATCH (n:Person) WHERE n.age <= 30 RETURN n.name
MATCH (n:Person) WHERE n.name = "Alice" RETURN n
MATCH (n:Person) WHERE n.name <> "Alice" RETURN n
An integer and a float compare by their exact values: n.age = 30.0 matches an
age stored as 30, and an integer above 2^53 is not rounded to the nearest float
before it is compared (9007199254740993 > 9007199254740992.0 is true).
NaN is not above, below or equal to anything, itself included: every <, <=,
>, >= and = with a NaN operand is false, and <> is true.
WITH toFloat('NaN') AS x RETURN x > 1, x < 1, x = x, x <> x
┌───────┬───────┬───────┬────────┐
│ x > 1 │ x < 1 │ x = x │ x <> x │
├───────┼───────┼───────┼────────┤
│ false │ false │ false │ true │
└───────┴───────┴───────┴────────┘
ORDER BY still has to place NaN, and puts it after every other number (see
RETURN); a property index keeps it in the same place.
Boolean Logic
Combine conditions with AND, OR, NOT, and XOR:
MATCH (n:Person)
WHERE n.age > 25 AND n.field = "ML"
RETURN n.name
MATCH (n:Person)
WHERE n.field = "ML" OR n.field = "AI"
RETURN n.name
MATCH (n:Person)
WHERE NOT n.field = "Systems"
RETURN n.name
A predicate can be true, false or null: a comparison with a missing property is
null, and NOT, AND and OR follow three-valued logic. WHERE keeps a row only
when the predicate is true, so WHERE n.email <> "[email protected]" skips people with no
email, and so does WHERE NOT n.email = "[email protected]". See
Functions for the full rules.
Null Checks
MATCH (n:Person) WHERE n.email IS NULL RETURN n.name
MATCH (n:Person) WHERE n.email IS NOT NULL RETURN n.name
String Predicates
MATCH (n:Person) WHERE n.name CONTAINS "li" RETURN n
MATCH (n:Person) WHERE n.name STARTS WITH "A" RETURN n
MATCH (n:Person) WHERE n.name ENDS WITH "ce" RETURN n
Regular Expressions
=~ matches a string against a regular expression. The whole string has to match,
so "A.*" finds names starting with "A" and "li" matches only the string "li":
MATCH (n:Person) WHERE n.name =~ "A.*" RETURN n.name
MATCH (n:Person) WHERE n.name =~ "(?i)a.*" RETURN n.name
The supported syntax is a subset of Java's: character classes, \d, \w, \s
and their negations, groups, alternation, *, +, ? and {n,m} (lazy forms are
accepted), the anchors ^, $, \A, \z, \b and \B, and the flags (?i)
and (?s) at the start of the pattern. Matching follows UTF-8 characters, and its
time grows with the length of the text times the size of the pattern, whatever the
pattern, so a pattern taken from a parameter cannot make a query run away.
Backreferences, lookaround and possessive quantifiers fail the query rather than
being misread. A null on either side gives null.
Property Existence
Test whether a property exists by checking for null:
MATCH (n:Person) WHERE n.email IS NOT NULL RETURN n
Inline Property Matching
Properties in the MATCH pattern act as equality filters:
// These are equivalent:
MATCH (n:Person {name: "Alice"}) RETURN n
MATCH (n:Person) WHERE n.name = "Alice" RETURN n
Vector Distance
Filter by vector similarity using <=>:
MATCH (c:Chunk)
WHERE c.embedding <=> $query < 0.5
RETURN c.text
See Vector Search.
Full-Text Search
Filter by text content using @@:
MATCH (d:Document)
WHERE d.content @@ "neural networks"
RETURN d.title
See Full-Text Search.
RETURN and Projections
RETURN specifies which values to include in the query output.
Returning Properties
MATCH (n:Person)
RETURN n.name, n.age
Returning Nodes
Return a node. The value returned is the node's integer ID:
MATCH (n:Person)
RETURN n
Aliases
Use AS to rename output columns:
MATCH (n:Person)
RETURN n.name AS name, n.age AS age
Without AS, a column is named after the text of its expression: n.name,
n.age + 1, coalesce(n.nickname, n.name), count(*).
Two columns cannot have the same name: RETURN n.name, n.name fails with
"Column n.name is returned twice; give one of them another name with AS".
Every Variable: RETURN *
* stands for every variable in scope, each as a column named after it, in
alphabetical order. More items may follow it:
MATCH (a:Person)-[k:KNOWS]->(b)
RETURN *, b.name AS friend
// columns: a, b, k, friend
Variables in scope are those the earlier clauses bound by name: pattern
variables of MATCH, OPTIONAL MATCH, CREATE and MERGE, named paths,
UNWIND ... AS, CALL ... YIELD columns, and what the last WITH passed on.
Anonymous nodes and relationships are not included, nor is a FOREACH variable.
RETURN * with nothing in scope fails with "RETURN * is not allowed when there
are no variables in scope", and * must be the first item.
Expressions
Return computed values:
MATCH (n:Person)
RETURN n.name, n.age + 1
A query can start with RETURN (or WITH), which then runs once:
RETURN 1 + 2
RETURN and WITH take at most 16 items; a query with more fails to plan.
A query without RETURN returns no columns and no rows, whatever it wrote; see
CREATE, SET, DELETE.
Map Projection
variable {...} builds a map from a node, relationship or map:
MATCH (n:Person)-[k:KNOWS]->(f)
RETURN n {.name, .age, friend: f.name, k}
// {name: "Alice", age: 30, friend: "Bob", k: <relationship>}
.keyis the propertykey, null if it is missing;.*is every property;key: expressionis any value;- a variable
xon its own is the entryx: x.
Entries keep the order written, and a later entry replaces an earlier one with
the same key, so n {.*, name: 'anonymous'} overrides one property. A null
subject (from an OPTIONAL MATCH that found nothing) gives null; any other
value that is not a node, relationship or map is an error.
Literals
Return literal values:
MATCH (n:Person)
RETURN n.name, "person" AS type
DISTINCT
Remove duplicate rows:
MATCH (a:Person)-[:KNOWS]->(b:Person)
RETURN DISTINCT b.name
Ordering
Use ORDER BY to sort results:
MATCH (n:Person)
RETURN n.name, n.age
ORDER BY n.age DESC
Sort by multiple columns:
MATCH (n:Person)
RETURN n.name, n.age
ORDER BY n.field, n.age DESC
Null sorts last when ascending and first when descending. Values of different
types sort in a fixed order: maps, nodes, relationships, lists, vectors, bytes,
strings, booleans, numbers, then null. Integers and floats compare by exact value,
and NaN sorts above every other number. Rows with equal keys keep the order they
arrived in. If a sort key cannot be evaluated for some row (ORDER BY n.age / 0),
the query fails.
With a following LIMIT, the sort keeps only the rows it can return, so
ORDER BY ... LIMIT 10 does not hold every row in memory. When the sort is
first by a property that has a property index, ascending or descending, over a
single MATCH pattern whose RETURN neither aggregates nor uses DISTINCT,
the scan reads the index in that order and stops once no later row could be
among the first SKIP + LIMIT, so it does not read every node either. The
rows, ties and nulls included, are the ones the full sort would return.
ORDER BY sees both the variables of the query and the columns the RETURN
names, so an alias can be used inside an expression:
RETURN n.name AS name ORDER BY toUpper(name). After an aggregating RETURN
only the returned columns are left, and expressions over them:
MATCH (p:Person)-[:KNOWS]->(f)
RETURN p, count(f) AS friends
ORDER BY p.name, friends * -1
ORDER BY f.name there fails before the query runs, since f is not returned
and has no single value per group; so does ordering by an aggregate the
RETURN does not return.
Pagination
Use LIMIT and SKIP for pagination:
// First 10 results
MATCH (n:Person) RETURN n.name LIMIT 10
// Skip first 10, return next 10
MATCH (n:Person) RETURN n.name SKIP 10 LIMIT 10
Aggregations in RETURN
Aggregation functions can be used directly in RETURN:
MATCH (doc:Document)-[:AUTHORED_BY]->(p:Person)
RETURN p.name, count(doc) AS papers
ORDER BY papers DESC
See Aggregations for the full list.
CREATE, SET, DELETE
Mutation clauses modify the graph structure.
A query that only writes returns no columns and no rows; the CLI prints "Query
executed". To get back what was written, end it with a RETURN:
CREATE (a:Person {name: "Alice"})-[:KNOWS]->(b:Person {name: "Bob"})
RETURN id(a), id(b)
CREATE
Create a Node
CREATE (n:Person {name: "Alice", age: 30})
Create a node with multiple labels:
CREATE (n:Person:Employee {name: "Alice"})
Create an Edge
Create an edge between existing nodes:
MATCH (a:Person {name: "Alice"}), (b:Person {name: "Bob"})
CREATE (a)-[:KNOWS]->(b)
Create Nodes and Edges Together
CREATE (a:Person {name: "Alice"})-[:KNOWS]->(b:Person {name: "Bob"})
A relationship in CREATE has exactly one type. A variable that is already bound
can be used in CREATE to connect to it, as above, but not given new labels or
properties there (MATCH (n) CREATE (n:Extra) is rejected); use SET.
Both ends of a relationship must exist when it is created. A CREATE that would
connect a node deleted earlier in the same query fails, with the same error code
as a direct relationship create to a missing node, LATTICE_ERROR_NOT_FOUND (-4):
$ lattice exec db.lattice --query="MATCH (a:C {name: 'x'}) DETACH DELETE a CREATE (a)-[:S]->(:C)"
Error: Execution error (NotFound): Cannot complete creating a relationship from node 1 to node 3: a node or relationship it needs does not exist, or was deleted earlier in the query
SET
Set Properties
MATCH (n:Person {name: "Alice"})
SET n.age = 31
Set multiple properties:
MATCH (n:Person {name: "Alice"})
SET n.age = 31, n.city = "NYC"
Set Labels
Add labels to a node:
MATCH (n:Person {name: "Alice"})
SET n:Admin:Verified
Remove a Property via SET
Setting a property to NULL removes it:
MATCH (n:Person {name: "Alice"})
SET n.city = NULL
DELETE
Delete a Node
Delete a node:
MATCH (n:Person {name: "Charlie"})
DELETE n
A node that still has relationships cannot be deleted with plain DELETE: the
query fails and deletes nothing.
$ lattice exec db.lattice --query="MATCH (n:C {name: 'x'}) DELETE n"
Error: Execution error (NodeHasRelationships) at 1:32: Cannot delete node 1 because it still has relationships; delete them first, or use DETACH DELETE
1 | MATCH (n:C {name: 'x'}) DELETE n
| ^
Through the C API and the bindings the query returns the same error code as a
direct node delete, LATTICE_ERROR_HAS_RELATIONSHIPS (-17). Either delete the
relationships in the same statement, which are removed before any node is
checked:
MATCH (n:Person {name: "Dana"})-[r]-()
DELETE r, n
or use DETACH DELETE. DELETE takes nodes and relationships only; deleting a
value such as n.name is rejected, and deleting null does nothing.
DETACH DELETE
Delete a node and all its edges:
MATCH (n:Person {name: "Charlie"})
DETACH DELETE n
REMOVE
Remove a Property
MATCH (n:Person {name: "Alice"})
REMOVE n.city
Remove a Label
MATCH (n:Person {name: "Alice"})
REMOVE n:Verified
MERGE
MERGE matches an existing pattern or creates it if it doesn't exist. It's an idempotent "get or create" operation.
Basic Usage
MERGE (n:Person {name: "Alice"})
RETURN n
If a Person node with name: "Alice" exists, it is returned. Otherwise, one is created.
A node matches when it carries every label in the pattern and has every property
in it equal to the pattern's value, comparing as = does (an integer equals the
float of the same value, and lists and maps compare element by element). Other
labels and properties on the node do not matter. A pattern without a label
considers every node. Only when nothing matches is a node created, with all the
pattern's labels and properties.
A relationship in MERGE compares its properties the same way, so
MERGE (a)-[:R {w: 1}]->(b) finds an existing relationship whose w is 1.0
instead of creating a second one.
When several nodes match, MERGE returns one row for each of them:
MERGE (n:Person {field: "ML"})
RETURN n.name
A pattern property whose value is null fails the query: no node could ever match
it, so the MERGE would create a new node every time it ran.
When an explicit property index covers one of the pattern's labels and properties,
MERGE looks candidates up there instead of reading every node with the label.
MERGE with Properties
MERGE (n:Person {name: "Alice"})
SET n.last_seen = "2024-01-15"
RETURN n
The SET clause runs whether the node was matched or created.
ON CREATE and ON MATCH
To set properties only when the node is created, or only when it already existed:
MERGE (n:Person {name: "Alice"})
ON CREATE SET n.created = "2024-01-15"
ON MATCH SET n.last_seen = "2024-01-15"
RETURN n
ON MATCH applies to every node that matched.
MERGE Edges
MATCH (a:Person {name: "Alice"}), (b:Person {name: "Bob"})
MERGE (a)-[:KNOWS]->(b)
This creates the KNOWS edge only if it doesn't already exist. The relationship
needs exactly one type.
MERGE accepts a single node pattern or a single relationship, as above; longer
patterns are rejected.
Use Cases
MERGE is useful when:
- Importing data that may have duplicates
- Ensuring a relationship exists without creating duplicates
- Building graphs incrementally from multiple data sources
WITH and Chaining
WITH pipes the output of one query part into the next. It acts as a boundary between query segments, allowing you to transform, filter, or aggregate intermediate results.
Basic Chaining
MATCH (p:Person)
WITH p.name AS name, p.age AS age
WHERE age > 30
RETURN name
Aggregation then Filtering
WITH is essential for filtering on aggregated values, since WHERE cannot reference aggregation results directly:
MATCH (doc:Document)-[:AUTHORED_BY]->(p:Person)
WITH p.name AS author, count(doc) AS papers
WHERE papers > 5
RETURN author, papers
ORDER BY papers DESC
Variable Scoping
Variables from before WITH are only available after it if they are explicitly passed through:
MATCH (a:Person)-[:KNOWS]->(b:Person)
WITH a, count(b) AS friend_count
RETURN a.name, friend_count
In this example, b is not available after the WITH clause — only a and friend_count are. Naming b after it fails with "Variable 'b' is not defined".
WITH * passes on every variable in scope, and items after it add more:
MATCH (a:Person)-[:KNOWS]->(b:Person)
WITH *, a.age - b.age AS gap
WHERE gap > 10
RETURN a.name, b.name, gap
Multi-Stage Queries
A MATCH after WITH can continue from a node the WITH passed on:
MATCH (a:Person {name: "Alice"})
WITH a
MATCH (a)-[:KNOWS]->(b)
RETURN a.name, b.name
Chain multiple WITH clauses for complex queries:
MATCH (p:Person)-[:AUTHORED_BY]-(doc:Document)
WITH p, count(doc) AS docs
WITH p, docs WHERE docs > 2
RETURN p.name, docs
Subqueries: CALL { }
CALL { ... } runs a query once for each incoming row. A leading WITH imports
variables from outside (only plain variables, as in WITH a, b); without one,
the query sees none of them. Aggregation, ORDER BY and LIMIT inside apply to
each run on its own, which is what per-row top-k and per-row counts need:
MATCH (t:Team)
CALL {
WITH t
MATCH (p:Player)-[:PLAYS_FOR]->(t)
RETURN p.name AS top ORDER BY p.goals DESC LIMIT 1
}
RETURN t.name, top
Each row the subquery returns extends the incoming row with its columns, so an
incoming row it returns nothing for is dropped (put an OPTIONAL MATCH or an
aggregate inside to keep one). Returned values must be named (AS), and their
names must be new. A variable inside may not reuse the name of one outside that
it did not import. The queries of a UNION inside each import on their own.
A subquery without RETURN runs for its writes, and each incoming row passes on
once:
MATCH (t:Team)
CALL { WITH t CREATE (:Audit {team: t.name}) }
RETURN count(*)
A MATCH inside searches as it would on its own, once for each incoming row:
WHERE d.text @@ 'x' scores its matches, and a bare WHERE d.embedding <=> $q
with a LIMIT gives each row its own nearest:
MATCH (p:Person)
CALL {
WITH p
MATCH (p)-[:WROTE]->(d:Doc) WHERE d.embedding <=> $q
RETURN d.title AS nearest LIMIT 1
}
RETURN p.name, nearest
WITH * WHERE ... is a WITH's WHERE, checked row by row: @@ there
matches without a score, and <=> needs a bound.
CALL { ... } IN TRANSACTIONS is not supported.
Subqueries in expressions: EXISTS, COUNT, COLLECT
EXISTS { ... } is whether a query returns any row, COUNT { ... } how many it
returns, and COLLECT { ... } the list of the one column it returns. Unlike
CALL { }, the query sees every variable around it without importing it, and
what it binds stays inside:
MATCH (p:Person)
WHERE EXISTS { MATCH (p)-[:WROTE]->(d) WITH d WHERE d.year > 2020 RETURN d }
RETURN p.name,
COUNT { MATCH (p)-[:KNOWS]-(f) RETURN f } AS friends,
COLLECT { MATCH (p)-[:WROTE]->(d) RETURN d.title ORDER BY d.year DESC LIMIT 3 } AS recent
The query may use any reading clause, aggregation, ORDER BY, LIMIT and
UNION, and runs once for each row. It cannot write (use CALL { }), and
COLLECT's must end with a RETURN of one column. A variable it binds after a
WITH may not take the name of one outside.
The short form, a pattern and a WHERE with or without MATCH
(EXISTS { (p)-[:WROTE]->(d) WHERE d.year > 2020 }), is planned as a pattern
predicate, and its WHERE is checked row by row: @@ there matches without a
score, and <=> needs a bound. A MATCH in a longer query searches as it would
alone, as in CALL { }.
UNWIND
UNWIND expands a list into individual rows. Each element of the list becomes a separate row in the output.
Basic Usage
UNWIND [1, 2, 3] AS x
RETURN x
Returns three rows: 1, 2, 3.
A null element is a row like any other: UNWIND [1, null] AS v RETURN v returns
1 and null. Unwinding null itself, or an empty list, gives no rows, and a
value that is not a list gives one row. If the expression cannot be evaluated,
for instance because a parameter is missing, the query fails.
Creating Multiple Nodes
Use UNWIND with CREATE to create nodes from a list:
UNWIND ["Alice", "Bob", "Charlie"] AS name
CREATE (n:Person {name: name})
With Parameters
Pass a list as a parameter and unwind it:
UNWIND $names AS name
MATCH (n:Person {name: name})
RETURN n
Combining with MATCH
UNWIND $tags AS tag
MATCH (d:Document)
WHERE d.title CONTAINS tag
RETURN tag, d.title
Aggregations
Aggregation functions compute summary values across groups of rows.
Every aggregate except count(*) skips nulls: count(n.email) counts the people
who have an email, avg divides by the number of non-null values, and collect
leaves nulls out of its list.
Functions
count
Count the number of values:
MATCH (n:Person) RETURN count(n) AS total
count(*) counts rows, nulls included, and its column is named count(*). With
nothing before it, RETURN count(*) returns 1. count(DISTINCT x) counts distinct
non-null values, and its column is named count(DISTINCT x).
Grouping and DISTINCT treat values that = calls equal as one value: 1 and
1.0 fall into one group, and so do 0 and -0.0. Every NaN is one value, though
= never matches it.
Count with grouping:
MATCH (doc:Document)-[:AUTHORED_BY]->(p:Person)
RETURN p.name, count(doc) AS papers
sum
Sum numeric values:
MATCH (o:Order)
RETURN sum(o.amount) AS total_revenue
A sum of integers is an integer, computed exactly; if it does not fit in 64 bits
the query fails. If any value is a float, the sum is a float. The sum of no values
is 0. A value that is not a number fails the query with a type error, for sum
and for avg.
avg
Average numeric values:
MATCH (n:Person)
RETURN avg(n.age) AS average_age
avg always returns a float, and null when there are no values.
min / max
Find minimum or maximum values:
MATCH (n:Person)
RETURN min(n.age) AS youngest, max(n.age) AS oldest
Values of different types are compared the way ORDER BY orders them, so
min over 1, 'a' and true is 'a' and max is 1, and an integer and
a float compare exactly.
collect
Collect values into a list:
MATCH (p:Person)-[:KNOWS]->(f:Person)
RETURN p.name, collect(f.name) AS friends
Grouping
Non-aggregated columns in RETURN define the grouping:
MATCH (doc:Document)-[:AUTHORED_BY]->(p:Person)
RETURN p.name, count(doc) AS papers, collect(doc.title) AS titles
ORDER BY papers DESC
Here p.name is the grouping key, and count(doc) and collect(doc.title) are computed per group.
An aggregate can sit inside a larger expression, and a grouping key can be an
expression: RETURN n.age / 10 AS decade, count(n) + 1, sum(n.x) / count(n),
or an aggregate inside a CASE.
A COUNT { }, EXISTS { }, COLLECT { } or pattern comprehension beside an
aggregate may read the grouping keys: RETURN p, count(f) + COUNT { (p)<--() }
groups by p and counts for each group. A subquery that reads a variable that
is not a grouping key fails before the query runs, as RETURN p.name, count(f) + COUNT { (p)<--() } does, since grouping by p.name leaves no single p.
Aggregates belong in RETURN and WITH. In WHERE, SET, UNWIND,
FOREACH, MATCH properties, SKIP or LIMIT there are no rows to
aggregate, and the query fails before it runs:
collect() aggregates rows, which FOREACH cannot do; aggregate in a WITH first, as in WITH collect(n.v) AS vs
Aggregate in a WITH and use the result:
MATCH (p:Person)
WITH collect(p.name) AS names
FOREACH (name IN names | CREATE (:Tag {name: name}))
Filtering Aggregated Results
Use WITH to filter on aggregated values:
MATCH (p:Person)-[:KNOWS]->(f:Person)
WITH p, count(f) AS friend_count
WHERE friend_count > 5
RETURN p.name, friend_count
Variable-Length Paths
Variable-length path patterns match paths of varying depth in a single query.
Syntax
MATCH (a)-[*min..max]->(b)
*1..3— match paths of length 1 to 3*2— match paths of exactly length 2*2..— match paths of length 2 or more*— match paths of any length (at least 1)
A type, or several separated by |, restricts every hop: -[:KNOWS|LIKES*1..2]->.
Each path is one result. A path uses each relationship at most once, but may pass
through a node more than once, including the one it started from. A node reached
by two different paths is therefore returned twice, which is why the examples
below use DISTINCT where they want each node once.
The relationships of a path also count toward the rest of its MATCH: no other
relationship of the same MATCH, single-hop or variable-length, can use one of them
again. See Relationship Uniqueness.
Examples
Fixed Range
// Friends of friends (exactly 2 hops)
MATCH (a:Person {name: "Alice"})-[:KNOWS*2]->(b:Person)
RETURN b.name
Bounded Range
// Reachable within 1 to 3 hops
MATCH (a:Person {name: "Alice"})-[:KNOWS*1..3]->(b:Person)
RETURN DISTINCT b.name
Open-Ended
// All reachable nodes (2+ hops)
MATCH (a:Person {name: "Alice"})-[*2..]->(b)
RETURN b
Any Length
// All nodes reachable at any depth
MATCH (a:Person {name: "Alice"})-[*]->(b)
RETURN DISTINCT b
The relationships of the path
A variable on a variable-length relationship is the list of the relationships the path went through, in the order it walked them; zero hops give an empty list:
MATCH (a:Person {name: "Alice"})-[r:KNOWS*1..3]->(b:Person)
WHERE all(k IN r WHERE k.since >= 2020)
RETURN b.name, size(r) AS hops, [k IN r | k.since] AS years
The variable is a list, not a relationship: DELETE r and SET r.x = 1 are
errors, while r[0], size(r), comprehensions and quantifiers work on it.
An inline property map holds for every relationship of the path:
-[:KNOWS*1..3 {since: 2020}]-> matches paths whose relationships all have
since = 2020. Paths are walked first and filtered after, so a selective map
on an unbounded pattern still costs as much as the walk without it.
If the far end is a node that is already bound, only paths that end at it are returned.
Shortest Paths
shortestPath finds one shortest path between two nodes, and allShortestPaths
every path of that shortest length:
MATCH (a:Person {name: "Alice"}), (b:Person {name: "Dan"})
MATCH p = shortestPath((a)-[:KNOWS*]-(b))
RETURN length(p), [n IN nodes(p) | n.name] AS route
The pattern inside is one relationship between two nodes, of any direction and
types, with an optional upper bound (*..6) and a lower bound of 0 or 1. The ends
can be bound earlier or matched by the pattern itself, with labels and
properties; a WHERE on the ends filters them. For each pair of ends the search
runs breadth-first from both ends at once and stops at the first length at which
they meet, so it reads the neighbourhoods of the two ends, never every path.
Pairs that are not connected within the bound give no row, or null after
OPTIONAL MATCH. A relationship variable is the list of the path's relationships.
From a node to itself the path has no relationships when the lower bound is 0,
and there is none otherwise.
Not supported, each with an error naming it: a property map on the
relationship, a pattern of more than one relationship, a lower bound above 1,
shortestPath outside MATCH (in CREATE, MERGE, EXISTS { } or as an
expression), and a WHERE right after the MATCH that reads the path or its
relationships, since the search would not look for a longer path that passes.
The relationships of a shortest path are not kept apart from the other
relationships of its MATCH.
Each pair of ends is searched on its own, so ends that match many nodes multiply
the work: give both ends labels and properties, or bind them first. On a graph
of 100,000 nodes and 1,000,000 random directed relationships (ReleaseFast,
macOS), a search between two random nodes, about five hops apart, took a median
of 0.34 ms one way and 0.16 ms undirected; allShortestPaths, 0.19 ms for about
five paths per pair.
Performance
Paths are expanded depth-first, one path at a time. There is no hop limit: an
unbounded * or *n.. ends because a path cannot use more relationships than
exist. The number of paths, though, can grow exponentially with the size of a
densely connected graph, so give unbounded patterns over large, well-connected
graphs an upper bound.
- Short paths (1-3 hops): microseconds
- The cost grows with the number of paths, not the number of reachable nodes
DISTINCTremoves the duplicate rows that several paths to one node produce
On a graph of 10K nodes with 5 outgoing edges each, MATCH (a:Person {uid: $uid})-[:KNOWS*1..5]->(b) RETURN count(b) enumerates about 3,900 paths in 0.47 ms (0.60 ms at 100K nodes), about 0.12 to 0.15 us per path. See Benchmarks for how this was measured.
Vector Search (<=>)
The <=> operator computes the distance between a stored vector embedding and a query vector. It integrates HNSW vector search into Cypher queries.
Basic Usage
MATCH (chunk:Chunk)
WHERE chunk.embedding <=> $query < 0.5
RETURN chunk.text
ORDER BY chunk.embedding <=> $query
LIMIT 10
This finds chunks whose embedding is within distance 0.5 of the query vector, sorted by proximity. The distance is measured with the metric the database was created with; see Distance Metric.
How It Works
n.embedding is the node's vector, the one stored with set_vector. A node has
one vector, and embedding is the only property name that reads it; set_vector
accepts "embedding" (or an empty key) and rejects any other key as unsupported.
Under the cosine metric, once committed, the vector reads back normalised to unit
length, because the index stores only the normalised copy: a stored [3, 4]
returns as [0.6, 0.8]. Under the Euclidean and dot-product metrics vectors are
stored, and read back, as given.
A query vector must have the database's dimensions and finite components. A
vector containing NaN or infinity fails the query, as it fails set_vector.
When the whole WHERE clause is a <=> predicate (n.embedding <=> q < t,
<= t, or n.embedding <=> q on its own), with q a parameter or a list literal
and t a number or a parameter, the planner answers it with the HNSW index. The
rows the MATCH pattern produces are the candidates, and the search looks only
among their nodes:
- With a threshold: every candidate within it.
<excludes a distance of exactlytand<=includes it. A null threshold matches nothing. - Under a
RETURNwith aLIMIT, and noDISTINCTor aggregation in between: theSKIP+LIMITnearest candidate nodes. AnORDER BYin between keeps this bound only when it sorts nearest first by the same distance, written as in theWHERE(ORDER BY n.embedding <=> $q, ascending) or as the alias of aRETURNitem that is that distance, since the search returns its results in that order already. Any otherORDER BYmakes the search find every candidate before sorting. - With neither: the 100 nearest candidate nodes.
So the label narrows the search (MATCH (c:Chunk) returns Chunk nodes even when
other nodes are nearer), and a threshold query returns every match, however many.
When the candidates are few next to the index (fewer than about
sqrt(ef_search × 32 × vectors): some 14,000 of 100,000), each one is measured,
which is exact. A larger set is searched through the HNSW graph with the set as
a filter; that stays approximate, so a candidate within the threshold can
occasionally be missed. Candidates the graph search could not reach are measured
directly when it runs out. When the pattern is a single labelled node,
MATCH (n:Label) WHERE n.embedding <=> ..., the label's index is that filter:
the search reads only as much of the label as it takes to tell that it is
large, so a label holding half of 100,000 nodes answers LIMIT 10 in about
0.5 ms, and one holding 100 of them in 10 to 20 µs.
Any other form is evaluated row by row, exactly, by computing each candidate's
distance: a threshold that is an expression (< 0.25 * 2), or a <=> predicate
combined with others through AND. <=> has the same precedence as the
comparison operators and groups left to right, so write the distance first, or in
parentheses: 0.5 > n.embedding <=> $q compares 0.5 > n.embedding first.
The WHERE of an OPTIONAL MATCH, of the short form of EXISTS { ... } or
COUNT { ... } (a pattern and a WHERE), of a pattern comprehension and of a
WITH is always checked row by row, so a <=> there needs a bound
(WHERE n.embedding <=> $q < 0.5). A bare n.embedding <=> $q there is refused
("A WHERE of only <=> ranks the rows of a MATCH by distance, which OPTIONAL
MATCH cannot do; give it a bound instead"). Each part of a UNION is planned as
a query of its own, so a <=> with a LIMIT there is the search it would be
alone; so is one under a named path (MATCH p = (n:Chunk) WHERE n.embedding <=> $q), and the MATCH of a CALL { } subquery or of a whole query inside
EXISTS, COUNT or COLLECT, which searches once for each incoming row (see
Subqueries).
<=> is also an ordinary expression. Outside such a search, in a RETURN, a
WITH, an ORDER BY or a combined WHERE, it computes the distance between its
two vectors with the database's metric (cosine in a database without a vector
index), and either side can be a property, a parameter or a list literal:
RETURN [1.0, 0.0] <=> [0.0, 2.0] AS d // 1.0 under cosine
For the nearest k across the whole database, whatever the labels, use the
vector_search API (db.vector_search(vector, k=...)). A k larger
than ef_search widens the search to k, so asking for 500 neighbours returns 500
when the database holds that many.
Returning the Distance
Writing the search's own distance in the RETURN, the same way as in the WHERE
(same variable, property, and parameter or literal), returns the distance the search
already measured instead of computing it again:
MATCH (d:Doc)
WHERE d.embedding <=> $q < 3
RETURN d.name, d.embedding <=> $q AS dist
ORDER BY dist
LIMIT 10
The measured distance stays with its node: WITH d carries it on, while under
another name (WITH d AS e) it is computed again. It does not survive an
aggregation.
Distance Metric
Each database's vector index has one metric, chosen when the index is created and
fixed afterwards (lattice create --vector-metric=cosine|euclidean|dot_product, or the
vector_metric open option in the bindings). Search, <=> and the scoring of
vectors not yet committed all use it. Smaller is always nearer.
| Metric | <=> returns | Range | [1, 0] <=> [0, 2] |
|---|---|---|---|
cosine (default) | 1 - cosine similarity | 0 (same direction) to 2 (opposite) | 1.0 |
euclidean | the L2 distance, square root included | 0 and up | 2.236 (√5) |
dot_product | the negated dot product | any number | 0.0 |
Under cosine, vectors are normalised when stored, so their length does not matter.
Under Euclidean and dot product they are stored as given, and their length counts.
With the dot-product metric a distance can be negative, so pick thresholds for the
metric in use: < 0.5 means something different under each.
To change a database's metric, or its m and ef_construction, export it and
import it into a database created with the new settings.
Ordering by Distance
Use ORDER BY to sort results by similarity:
MATCH (n:Document)
WHERE n.embedding <=> $query < 1.0
RETURN n.title
ORDER BY n.embedding <=> $query
LIMIT 10
Combining with Graph Traversal
The real power is combining vector search with graph patterns:
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.embedding <=> $query < 0.5
RETURN doc.title, chunk.text, author.name
ORDER BY chunk.embedding <=> $query
LIMIT 10
This finds similar chunks, then traverses to their documents and authors — all in one query.
Combining with Full-Text Search
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)
WHERE chunk.embedding <=> $query < 0.5
AND doc.content @@ "neural networks"
RETURN doc.title, chunk.text
ORDER BY chunk.embedding <=> $query
Parameter Binding
Pass the query vector as a parameter:
Python:
results = db.query(
"MATCH (n) WHERE n.embedding <=> $q < 0.5 RETURN n",
parameters={"q": query_vector}
)
TypeScript:
const results = await db.query(
"MATCH (n) WHERE n.embedding <=> $q < 0.5 RETURN n",
{ q: new Float32Array([0.1, 0.2, ...]) }
);
Full-Text Search (@@)
The @@ operator runs a BM25-scored full-text search against an index you have
declared over the property holding the text.
MATCH (d:Document)
WHERE d.content @@ "neural networks"
RETURN d.title
That searches the index declared for Document.content, and nothing else.
Declaring an index
A full-text index covers one label and one property. Declaring it reads that property from every node already carrying the label, so an index you add later still finds the documents you wrote earlier.
Python:
db.create_node_fts_index("Document", "content")
TypeScript:
await db.createNodeFtsIndex("Document", "content");
Go:
err := db.CreateNodeFTSIndex("Document", "content")
Java:
db.createNodeFtsIndex("Document", "content");
After that, writing the property is all it takes. Creating a node with the property, changing it, and deleting the node each keep the index current, the same way a property index stays current. There is no separate indexing call.
Only string properties are indexed. A number or a list is not text, and quietly turning one into a string form of itself would make results hard to explain.
The property name means what it says
d.title @@ "..." searches the index declared for Document.title. It does not
search d.content, and it does not search some pooled text belonging to the node.
If no index is declared for the property you named, the query fails and says so:
No full-text index is declared for Document.title. Declare one before searching it.
That is deliberately not an empty result. Returning no rows would make a mistyped property name look exactly like a search that found nothing, which is how such a mistake survives for months.
The pattern also has to carry a label, because two labels can each declare an
index on title and the property alone does not say which you mean:
MATCH (d) WHERE d.title @@ "bread" RETURN d
`d.title @@ ...` needs a label to say which full-text index it means.
Write it in the pattern, as in (d:Label).
Relationships
A relationship property works the same way, with the relationship type standing in for the label:
db.create_edge_fts_index("REVIEWED", "note")
MATCH (a:Person)-[x:REVIEWED]->(p:Paper)
WHERE x.note @@ "thorough"
RETURN p.title
The pattern has to name the type, for the same reason a node pattern has to name
a label — two relationship types can each declare an index on note:
`x.note @@ ...` needs a relationship type to say which full-text index it means.
Write it in the pattern, as in -[x:TYPE]->.
Labels and relationship types share one namespace, so a node index and a
relationship index cannot both use the same name and property: with
(:Review).text declared, declaring [:Review].text fails with "already exists",
and the other way round. Their entries would land on the same storage keys. A
database that declared both before this check existed keeps sharing them, and
dropping either clears both; drop both and declare again the one you keep.
A single @@ predicate searches either nodes or relationships, not both at once.
WHERE d.title @@ "x" OR x.note @@ "x" is not a union of two index scans, because
one scan filters one variable; that query still works, through the row filter,
but it is not planned as a single scan.
Searching several properties
OR searches each index and returns the union:
MATCH (d:Document)
WHERE d.title @@ "bread" OR d.body @@ "bread"
RETURN d.title
A document matching both sides is returned once, scored by whichever side scored it higher. Two properties matching is not evidence that either matched twice as well, so the scores are not added; a document matching both weakly should not outrank one matching a single property strongly.
If you want several fields treated as one document with one merged score, store the combined text in a property and declare an index over that:
doc["search_text"] = f"{title} {body}"
db.create_node_fts_index("Document", "search_text")
That keeps the searchable text visible in the database, where you can read it, rebuild it, and correct it.
How it works
When the planner sees @@, it resolves the label and property to a declared index
and reads the matching entities straight out of it. It does not look at anything
the index did not name, so a search that matches one document out of eight
thousand costs about what it costs out of five hundred.
That holds when @@ is the whole WHERE clause or a branch of an AND. Under an
OR beside a non-text condition it cannot: the other branch may match entities
the index never names, so the query examines every entity carrying the label. The
result is the same; the work is not. See the
performance notes if that matters for
your data.
Results are scored with BM25, which weighs term frequency, inverse document frequency, and document length — which is why a title mentioning a term beats a passing mention buried in a page of text.
A query with no LIMIT returns every match. Writing LIMIT still limits.
score(d) returns the BM25 score the search gave d. When @@ is the whole
WHERE and the RETURN has a LIMIT with no ORDER BY, or with
ORDER BY score(d) DESC, the search keeps only the best SKIP + LIMIT matches
instead of producing every match and sorting them:
MATCH (d:Document) WHERE d.text @@ "neural networks"
RETURN d.title, score(d) AS s ORDER BY s DESC LIMIT 10
Any other ORDER BY, a DISTINCT or aggregating RETURN, a longer pattern or
another condition beside the @@ makes the search find every match first, as
before; the answer is the same either way.
When the WHERE is exactly the search the MATCH already answered from the index
(same variable, index, and query text or parameter), the search runs once; it is not
repeated as a filter over the rows it produced.
Reading the score
score(d) returns the BM25 score of the @@ search that matched d, the same
number the direct search calls return. Higher is better:
MATCH (d:Document)
WHERE d.text @@ 'starter'
RETURN d.title, score(d) AS s
ORDER BY s DESC
For an OR of searches, it is the best score among the searches that matched,
also when the OR stands beside other conditions:
MATCH (d:Document)
WHERE d.year >= 2020 AND (d.title @@ 'sourdough' OR d.body @@ 'sourdough')
RETURN d.title, score(d) AS s
ORDER BY s DESC
score(d) is null when no single search scored d: the query has no @@ on d,
the MATCH searched several indexes and chose between them as it ran, or the
@@ was checked row by row. That is the case for an @@ in the WHERE of a
WITH, of the short form of an EXISTS or COUNT subquery (a pattern and a
WHERE) or a pattern comprehension (which match correctly but give no score),
and of an OPTIONAL MATCH that reaches d through a relationship; an
OPTIONAL MATCH (d:Label) WHERE d.text @@ ... reads the index and scores, and
so does the MATCH of a CALL { } subquery or of a whole query inside
EXISTS, COUNT or COLLECT, once for each incoming row. Each part of a UNION is scored, and bounded by its own
ORDER BY score(d) DESC LIMIT, as it would be alone. It is
carried through WITH d, but not under another name (WITH d AS e) and not
through an aggregation. Its argument must be a variable; score(1) fails with
"score() takes a variable, as in score(d) after WHERE d.text @@ 'query'".
ORDER BY score(d) LIMIT k, ascending, sorts every match and keeps the k
weakest; only ORDER BY score(d) DESC lets the LIMIT bound the search (see
How it works).
String queries
Words written side by side must all match:
// Both "neural" and "networks" must appear
MATCH (d:Document) WHERE d.text @@ "neural networks" RETURN d
Words are split and normalised the same way the indexed text is: words in any
script, lowercased, accents folded, English stop words dropped, and punctuation
inside a word treated as a separator. A word that no document contains means no
rows. OR, -word, "a phrase", word* and word~ are operators; see the
query syntax. The full-text search guide
describes the tokenizer, and what changes for indexes built by 0.16.0.
Using parameters
MATCH (d:Document)
WHERE d.content @@ $search_text
RETURN d.title
Python:
results = db.query(
'MATCH (d:Document) WHERE d.content @@ $q RETURN d.title',
parameters={"q": "machine learning"}
)
TypeScript:
const results = await db.query(
'MATCH (d:Document) WHERE d.content @@ $q RETURN d.title',
{ q: "machine learning" }
);
Combining with graph traversal
MATCH (chunk:Chunk)-[:PART_OF]->(doc:Document)-[:AUTHORED_BY]->(author:Person)
WHERE chunk.text @@ "transformer attention"
RETURN doc.title, author.name
Combining with vector search
MATCH (chunk:Chunk)
WHERE chunk.embedding <=> $query < 0.5
AND chunk.text @@ "transformer"
RETURN chunk.text
ORDER BY chunk.embedding <=> $query
Searching without Cypher
The same indexes are reachable directly, which is useful when you want scores rather than rows.
Python:
results = db.fts_search("Document", "content", "machine learning", limit=10)
# Typo-tolerant
results = db.fts_search_fuzzy("Document", "content", "machin lerning", limit=10)
TypeScript:
const results = await db.ftsSearch("Document", "content", "machine learning", { limit: 10 });
const fuzzy = await db.ftsSearchFuzzy("Document", "content", "machin lerning", { limit: 10 });
Fuzzy search matches documents containing any of the query words, or a near spelling of one, rather than all of them.
Inside a write transaction, @@ and the transaction's search methods see that
transaction's own uncommitted writes. Uncommitted text is matched by the same
query, split and normalised as the index would, fuzzy words included, and scored
with the same BM25 and the index's statistics, so it ranks where it will once
committed, give or take the statistics its own commit changes.
The query syntax (OR, -word, "phrase", word*, word~) is described in the
full-text search guide. It applies
to "some text" @@ "query" on a plain string as well.
Dropping an index
db.drop_node_fts_index("Document", "content")
That removes everything the index stored. The property itself is untouched, so declaring the index again rebuilds it from the text still in the database.
Parameters
Parameters allow you to pass values into queries safely using the $name syntax. This prevents injection attacks, and since the query text stays the same, the parsed query can be reused from the cache.
Syntax
Use $ followed by the parameter name in the query:
MATCH (n:Person) WHERE n.name = $name RETURN n
MATCH (n:Person) WHERE n.age > $min_age RETURN n
Python
# String parameter
result = db.query(
"MATCH (n:Person) WHERE n.name = $name RETURN n",
parameters={"name": "Alice"},
)
# Numeric parameter
result = db.query(
"MATCH (n:Person) WHERE n.age > $min_age RETURN n",
parameters={"min_age": 25},
)
# Vector parameter
from latticedb import hash_embed
result = db.query(
"MATCH (n) WHERE n.embedding <=> $vec < 0.5 RETURN n",
parameters={"vec": hash_embed("query text", dimensions=128)},
)
TypeScript
// String parameter
const result = await db.query(
"MATCH (n:Person) WHERE n.name = $name RETURN n",
{ name: "Alice" }
);
// Numeric parameter
const result = await db.query(
"MATCH (n:Person) WHERE n.age > $min_age RETURN n",
{ min_age: 25 }
);
// Vector parameter
import { hashEmbed } from "@hajewski/latticedb";
const result = await db.query(
"MATCH (n) WHERE n.embedding <=> $vec < 0.5 RETURN n",
{ vec: hashEmbed("query text", 128) }
);
C
lattice_query* query;
lattice_query_prepare(db, "MATCH (n) WHERE n.name = $name RETURN n", &query);
// Bind string parameter
lattice_value val = {
.type = LATTICE_VALUE_STRING,
.data.string_val = { "Alice", 5 }
};
lattice_query_bind(query, "name", &val);
// Bind vector parameter
float vec[128] = { /* ... */ };
lattice_query_bind_vector(query, "embedding", vec, 128);
Supported Parameter Types
| Type | Python | TypeScript | C |
|---|---|---|---|
| String | str | string | LATTICE_VALUE_STRING |
| Integer | int | number | LATTICE_VALUE_INT |
| Float | float | number | LATTICE_VALUE_FLOAT |
| Boolean | bool | boolean | LATTICE_VALUE_BOOL |
| Null | None | null | LATTICE_VALUE_NULL |
| Bytes | bytes | Uint8Array | LATTICE_VALUE_BYTES |
| List | list | Array | LATTICE_VALUE_LIST |
| Map | dict (string keys) | plain object | LATTICE_VALUE_MAP |
| Vector | numpy.ndarray | Float32Array | float* (via lattice_query_bind_vector) |
Query Caching
Queries are cached by their query text. The cache holds the parsed and analysed query, so the same query with different parameter values skips parsing and analysis. Plans are not cached: each execution is planned again, which takes a microsecond or two.
A prepared query (lattice_query_prepare in C, which every binding uses) is parsed once, when it is prepared, and keeps its cache entry for as long as it is open, so executing it does not look the text up again. A query that does not parse still prepares; executing it reports the error.
# These share the same cache entry:
db.query("MATCH (n) WHERE n.name = $name RETURN n", parameters={"name": "Alice"})
db.query("MATCH (n) WHERE n.name = $name RETURN n", parameters={"name": "Bob"})
Functions
LatticeDB supports the following built-in functions in Cypher expressions.
Function names are not case-sensitive: toLower, tolower and TOLOWER are the
same function. Aggregates are covered in Aggregations.
Every function's name and number of arguments are checked before the query runs, so a misspelt name or a wrong argument count fails the same way whether the query would match rows or not:
$ lattice exec db.lattice --query="MATCH (n:Nope) RETURN lenght(n)"
Error: Semantic error (unknown_function) at 1:23: Unknown function 'lenght'
1 | MATCH (n:Nope) RETURN lenght(n)
| ^^^^^^
$ lattice exec db.lattice --query="RETURN toLower('a', 'b')"
Error: Semantic error (wrong_argument_count) at 1:8: toLower takes (string), but was given 2 arguments
An argument of the wrong type is found when the call is evaluated, and fails the query with a message naming what the function takes:
$ lattice exec db.lattice --query="RETURN toLower(1)"
Error: Execution error (TypeError) at 1:8: Type error: toLower(integer) is not defined; toLower takes (string)
id()
Returns the internal ID of a node or relationship:
MATCH (n:Person)
RETURN id(n), n.name
A WHERE right after the MATCH that names the node by id, id(n) = 42,
id(n) = $id or id(n) IN [1, 2, 3] (alone or joined to other conditions
by AND), reads those nodes directly instead of scanning every node or
every node with the label, and expands from there:
MATCH (a:Person)-[:KNOWS]->(b)-[:KNOWS]->(c)
WHERE id(a) = 1
RETURN b.name, c.name
┌─────────┬────────┐
│ b.name │ c.name │
├─────────┼────────┤
│ "Bob" │ "Alan" │
│ "Carol" │ "Alan" │
└─────────┴────────┘
The id must be written as a value, a parameter or a list of them; a
condition such as id(n) = m.ref that depends on another node is checked
row by row.
coalesce()
Returns the first non-null argument:
MATCH (n:Person)
RETURN coalesce(n.nickname, n.name) AS display_name
abs()
Returns the absolute value of a number:
MATCH (n:Person)
RETURN n.name, abs(n.score) AS abs_score
size()
Returns the length of a list, or the number of characters (Unicode code points)
in a string (size('Müller') is 6):
MATCH (p:Person)-[:KNOWS]->(f:Person)
WITH p, collect(f) AS friends
RETURN p.name, size(friends) AS friend_count
toInteger()
Converts a value to an integer:
MATCH (n:Person)
RETURN n.name, toInteger(n.score) AS int_score
A float is truncated toward zero (toInteger(3.9) is 3). A float outside the
64-bit integer range, NaN or an infinity fails the query. A string that is not an
integer gives null.
toFloat()
Converts a value to a float:
MATCH (n:Person)
RETURN n.name, toFloat(n.age) AS float_age
Other functions
| Function | Returns |
|---|---|
toString(x) | x as a string; null for a list or map |
toLower(s) / toUpper(s) | s in lower or upper case (see Strings) |
trim(s) | s without leading and trailing ASCII whitespace |
substring(s, start[, length]) | Part of s, from a zero-based start, both counted in characters; a negative start counts as 0 |
replace(s, search, replacement) | s with every search replaced; an empty search returns s |
split(s, delimiter) | A list of the parts of s; an empty delimiter splits s into characters |
head(list) / last(list) | The first or last element; null for an empty list |
tail(list) | Every element but the first |
range(start, end[, step]) | A list of integers from start to end, inclusive; a step of 0, or more than ten million elements, fails the query |
type(r) | A relationship's type |
labels(n) | A node's labels, as a list |
properties(x) | A node's or relationship's properties, as a map; a map is returned as it is |
exists(x.prop) | Whether the property is present: the same as x.prop IS NOT NULL |
length(p) | The number of relationships in a named path |
nodes(p) / relationships(p) | The nodes or the relationships of a named path, as a list; see Variable-Length Paths |
score(d) | The BM25 score of the full-text search that matched d; see Full-Text Search |
IN tests list membership (n.age IN [30, 40]). =~ matches a regular
expression; see WHERE. Lists and maps compare
by value: [1, 2] = [1, 2] is true.
Strings
size, substring and split work in characters (Unicode code points), not
bytes, so they never cut a character in half. A byte that is not valid UTF-8 counts
as one character.
RETURN size('Müller') // 6
RETURN substring('Ärger', 1, 3) // "rge"
RETURN split('añb', '') // ["a", "ñ", "b"]
RETURN toUpper('müller straße') // "MÜLLER STRAßE"
RETURN toLower('ÄRGER ΣΟΦΙΑ') // "ärger σοφια"
toLower and toUpper use Unicode's simple, one-to-one case mappings for Latin
(including Latin-1, Latin Extended-A, -B and Additional), Greek, Cyrillic,
Armenian and fullwidth ASCII letters; other characters are left as they are. Rules
that need the full mappings or the surrounding text are not applied: ß stays ß
in toUpper (not SS), a final Σ lowercases to σ (not ς), and there is no
Turkish or other language-specific casing. trim removes ASCII whitespace only.
Arithmetic
Numeric operations promote integers to floats when mixed:
RETURN 42 + 3.14 // Returns 45.14 (float)
RETURN 7 / 2 // Returns 3: integer division truncates
RETURN -7 % 2 // Returns -1: % takes the sign of the dividend
RETURN 7.5 % 2 // Returns 1.5
Integer +, -, *, /, unary minus and abs() fail the query when the result
does not fit in a 64-bit integer (9223372036854775807 + 1). Dividing by zero, or
taking % of zero, fails the query for integers and floats alike.
-9223372036854775808 can be written as a literal.
$ lattice exec db.lattice --query="RETURN 9223372036854775807 + 1"
Error: Execution error (IntegerOverflow) at 1:28: Integer overflow: 9223372036854775807 + 1 does not fit in a 64-bit integer
Comparisons between an integer and a float use their exact values, without
rounding the integer to a float first: 9007199254740993 = 9007199254740992.0 is
false and 9007199254740993 > 9007199254740992.0 is true, as ORDER BY already
ordered them. 1 = 1.0 and -0.0 = 0 are true, and DISTINCT and grouping keep
to the same equality: 1 and 1.0 are one value, and so are 0 and -0.0.
Null
A function given a null argument returns null (toString(null), size(null)
and substring(null, 1) are null); coalesce exists to replace nulls. A null in
any argument wins over a wrong type in another, so replace('abc', null, 1) is
null, not a type error. A wrong type is otherwise a type error, except that
toInteger, toFloat and toString return null for a value they cannot
convert.
Null propagates through comparisons, arithmetic and the string operators, and
NOT, AND and OR use three-valued logic; IS NULL and IS NOT NULL are always
true or false. A WHERE keeps a row only when its predicate is true, so
WHERE n.x <> 5 skips nodes that have no x:
RETURN null + 1 // Returns null
RETURN null = null // Returns null
RETURN false AND null // Returns false
RETURN true OR null // Returns true
RETURN NOT null // Returns null
RETURN 2 IN [1, null] // Returns null
C API
The C API is LatticeDB's primary interface. All language bindings (Python, TypeScript, Go, and Java through a JNI bridge) wrap this API. The header file is include/lattice.h.
Overview
The API uses opaque handle types and follows a consistent pattern:
- Functions return
lattice_error(0 = success, negative = error) - Resources are allocated by the library and freed by the caller
- Strings and result sets must be explicitly freed
Types
Handles
typedef struct lattice_database lattice_database;
typedef struct lattice_txn lattice_txn;
typedef struct lattice_query lattice_query;
typedef struct lattice_result lattice_result;
typedef struct lattice_vector_result lattice_vector_result;
typedef struct lattice_fts_result lattice_fts_result;
typedef struct lattice_edge_result lattice_edge_result;
typedef struct lattice_stream_batch lattice_stream_batch;
A handle is an opaque token, not the address of anything: pass it back to the
API, but never dereference or reinterpret it. Each handle gets a token that is
not reused (until a sequence of 2^53 handles wraps on 64-bit targets), so a
handle used after it was freed is rejected rather than reaching whatever the
allocator put in its place. A transaction handle used after commit or rollback
returns LATTICE_ERROR_TXN_ABORTED, also after the database is closed; any other
freed handle returns LATTICE_ERROR_INVALID_ARG.
Every call that reaches a database takes that database's lock, so a database
handle and its transactions can be called from several threads; the calls take
turns. That includes database-level calls such as lattice_vector_search,
lattice_get_nodes_by_label, the stream reads and the query cache calls, and a
handle stays valid for the whole of a call even if another thread commits or
closes it meanwhile. A waiting lattice_stream_read releases the lock while it
waits, so writers can commit what it is waiting for. Only one read-write
transaction can be open at a time (see below).
Enum arguments are checked: a value outside the declared set is rejected with
LATTICE_ERROR_INVALID_ARG (lattice_begin with an unknown mode,
lattice_embedding_client_create with an unknown format, a value of unknown
type), and lattice_error_message returns "Unknown error" for a code it does
not know.
IDs
typedef uint64_t lattice_node_id;
typedef uint64_t lattice_edge_id;
Error Codes
LATTICE_OK // 0 - Success
LATTICE_ERROR // -1 - Generic error
LATTICE_ERROR_IO // -2 - I/O error
LATTICE_ERROR_CORRUPTION // -3 - Data corruption detected
LATTICE_ERROR_NOT_FOUND // -4 - Resource not found
LATTICE_ERROR_ALREADY_EXISTS // -5 - Resource already exists
LATTICE_ERROR_INVALID_ARG // -6 - Invalid argument
LATTICE_ERROR_TXN_ABORTED // -7 - Transaction aborted
LATTICE_ERROR_LOCK_TIMEOUT // -8 - Lock timeout
LATTICE_ERROR_READ_ONLY // -9 - Write attempted on read-only txn
LATTICE_ERROR_FULL // -10 - Database full
LATTICE_ERROR_VERSION_MISMATCH // -11 - Version mismatch
LATTICE_ERROR_CHECKSUM // -12 - Checksum verification failed
LATTICE_ERROR_OUT_OF_MEMORY // -13 - Out of memory
LATTICE_ERROR_UNSUPPORTED // -14 - Unsupported operation or value type
LATTICE_ERROR_VALUE_TOO_LARGE // -15 - Value exceeds engine storage limits
LATTICE_ERROR_DATABASE_LOCKED // -16 - Database is open in another process
LATTICE_ERROR_HAS_RELATIONSHIPS // -17 - Node still has relationships
LATTICE_ERROR_CONFIG_MISMATCH // -18 - Open options contradict the file's vector index
LATTICE_ERROR_NEEDS_NEWER_WRITER // -19 - File may be written only by a newer release
Some codes come from more than one place:
| Code | Returned by |
|---|---|
LATTICE_ERROR_VERSION_MISMATCH | An open, read-only included, of a file or log in a format a newer release wrote |
LATTICE_ERROR_LOCK_TIMEOUT | Also lattice_checkpoint while a transaction already has records in the log |
LATTICE_ERROR_CORRUPTION | An open whose log holds damage in frames that had been synced, or a committed change that cannot be replayed |
LATTICE_ERROR_NOT_FOUND | lattice_edge_create when either end does not exist; a query that creates a relationship to a node deleted earlier in it |
LATTICE_ERROR_FULL | A read-only open whose crash recovery needs more memory than it is allowed (see Read-only opens after a crash) |
LATTICE_ERROR_HAS_RELATIONSHIPS | lattice_node_delete, and a query whose DELETE names a node that still has relationships |
LATTICE_ERROR_CONFIG_MISMATCH | lattice_open* with vector options that contradict the index the file records |
LATTICE_ERROR_NEEDS_NEWER_WRITER | A read-write open of a file whose header says only a newer release may write it; it still opens read-only |
LATTICE_ERROR_IO, LATTICE_ERROR_OUT_OF_MEMORY | Also lattice_query_execute, when the storage or an allocation failed under the query rather than the query itself |
Value Types
typedef enum {
LATTICE_VALUE_NULL = 0,
LATTICE_VALUE_BOOL = 1,
LATTICE_VALUE_INT = 2,
LATTICE_VALUE_FLOAT = 3,
LATTICE_VALUE_STRING = 4,
LATTICE_VALUE_BYTES = 5,
LATTICE_VALUE_VECTOR = 6,
LATTICE_VALUE_LIST = 7,
LATTICE_VALUE_MAP = 8
} lattice_value_type;
Property Value
typedef struct {
lattice_value_type type;
union {
bool bool_val;
int64_t int_val;
double float_val;
struct { const char* ptr; size_t len; } string_val;
struct { const uint8_t* ptr; size_t len; } bytes_val;
struct { const float* ptr; uint32_t dimensions; } vector_val;
} data;
} lattice_value;
Database Operations
Open
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
options.create = true;
options.enable_vector = true;
options.vector_dimensions = 128;
lattice_database* db;
lattice_error err = lattice_open_v5("mydb.ltdb", &options, &db);
lattice_open_v5 is the newest open function; the older ones (lattice_open
through lattice_open_v4, below) still work and behave as it does with the v5
fields left at 0.
Close
lattice_close(db);
Close refuses with LATTICE_ERROR_INVALID_ARG while a transaction or result
handle that depends on the database is still open, and the database stays open
so you can finish them and close again. A lattice_stream_read waiting on the
database in another thread does not hold the close up: it is woken and returns
LATTICE_ERROR_INVALID_ARG before the database is freed. Once close starts, it
always consumes the handle; LATTICE_ERROR_IO reports that the final sync or
checkpoint failed, and the handle must not be used again.
Open Options
typedef struct {
bool create; // Create if not exists
bool read_only; // Open in read-only mode
uint32_t cache_size_mb; // Cache size in MB (default: 100; 0: not set)
uint32_t page_size; // Page size in bytes (default: 4096)
bool enable_vector; // Create a vector index if the database has none
uint16_t vector_dimensions; // Vector dimensions, 1..4096 (default: 128)
} lattice_open_options;
A cache_size_mb set in any options version wins over the
LATTICE_BUFFER_POOL_MB environment variable. 0 means "not set": the
variable's size if it is set, else 100 MB.
Newer Open Options
lattice_open_options cannot grow without breaking every program compiled
against the old size, so newer options come as new structs. Each starts with its
own size, which is how the library knows which version you compiled against.
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
options.create = true;
options.enable_vector = true;
options.vector_dimensions = 1536;
options.vector_metric = LATTICE_VECTOR_METRIC_EUCLIDEAN;
options.sync_mode = LATTICE_SYNC_MODE_NORMAL;
lattice_database* db;
lattice_open_v5("graph.lattice", &options, &db);
Use lattice_open_v2 with lattice_open_options_v2, which adds enable_wal to
the original set. With enable_wal false nothing is logged, and everything else
works as with the log: read-write transactions, rollback, streams and the
changefeed. A commit then reaches the file at the next flush rather than when it
returns; see
Running without the log.
lattice_open_options_v3 adds enable_adjacency_cache, which keeps an
in-memory map of which nodes connect to which. Nothing behind the C API reads
that map, so it speeds up nothing; leave it off.
lattice_open_options_v4 adds lock, which defaults to true and is described
below.
lattice_open_options_v5 adds the durability settings and the vector index's
configuration, described in the next two sections. Each new field is 0 for "not
set", and a value outside its range makes the open return
LATTICE_ERROR_INVALID_ARG.
| Field | Values | When 0 |
|---|---|---|
sync_mode | LATTICE_SYNC_MODE_FULL (1), LATTICE_SYNC_MODE_NORMAL (2) | LATTICE_SYNC_MODE from the environment, else full |
full_fsync | LATTICE_FULL_FSYNC_OFF (1), LATTICE_FULL_FSYNC_ON (2) | LATTICE_FULL_FSYNC from the environment, else off |
vector_metric | LATTICE_VECTOR_METRIC_COSINE (1), _EUCLIDEAN (2), _DOT_PRODUCT (3) | The file's metric, or cosine for a new index |
vector_m | 2..32, HNSW connections per node (layer 0 keeps twice as many) | The file's, or 16 for a new index |
vector_ef_construction | 1..4096, HNSW candidate list size while building | The file's, or 200 for a new index |
changefeed_retention | LATTICE_CHANGEFEED_RETENTION_ALL (1), _LAST (2), _AGE (3), _OFF (4); see the changefeed | The file's policy, or LATTICE_CHANGEFEED_RETENTION from the environment for a new file, else all |
changefeed_retention_value | Events for _LAST, milliseconds for _AGE, at least 1 | Must be set for _LAST and _AGE |
lattice_deserialize and lattice_deserialize_borrowed take the v4 options;
lattice_deserialize_v5 and lattice_deserialize_borrowed_v5 take these, and
check them against the index the bytes record as an open checks a file.
Durability settings
sync_mode chooses when a commit waits for the disk. FULL, the default, syncs
the log on every commit, so a commit that has returned survives a power cut.
NORMAL hands the commit to the operating system and returns: it survives the
process being killed, but a power cut or OS crash can lose the most recent
commits, from the end only, and the database stays consistent. full_fsync, on
macOS only, makes each sync ask the drive to flush its own cache
(F_FULLFSYNC); it makes each commit several milliseconds slower and has no
effect elsewhere. A value set in the options wins over the LATTICE_SYNC_MODE
and LATTICE_FULL_FSYNC environment variables, which apply only to a handle
that leaves the field at 0, as every older open function does. See
Durability and the Log.
Vector index configuration
The database file records its vector index: the dimensions, the metric, m
and ef_construction. A database that has an index opens with it whether or
not enable_vector is set, so reopening needs no vector options at all, also
after a crash. enable_vector means "create an index if the database has none",
and vector_metric, vector_m and vector_ef_construction configure that new
index. Once the index exists they are fixed; to change them, export the data
and import it into a new database.
Any of those three fields that is set, and vector_dimensions when
enable_vector is set, must match what the file records, or the open returns
LATTICE_ERROR_CONFIG_MISMATCH before anything is read. To open a database
whose dimensions you do not know, leave enable_vector off.
The metric decides what a search's distance is, smallest first, and what the
Cypher <=> operator returns:
| Metric | Distance | Vectors are stored |
|---|---|---|
LATTICE_VECTOR_METRIC_COSINE | 1 - cos(a, b), in [0, 2] | scaled to unit length |
LATTICE_VECTOR_METRIC_EUCLIDEAN | sqrt(sum((a - b)^2)) | as given |
LATTICE_VECTOR_METRIC_DOT_PRODUCT | -(a . b), so the largest dot product comes first | as given |
A database written by 0.16.0 records no configuration. Its index is cosine with
m 16 and ef_construction 200, at the dimensions its vector pages carry, and
that configuration is written into the file the first time this release opens
it for writing.
Files written by newer releases
The file header says which releases may read the file and which may write it. A
file that only a newer release may write opens with read_only set; a
read-write open returns LATTICE_ERROR_NEEDS_NEWER_WRITER and writes nothing.
A file whose format this release cannot read at all is refused by every open
with LATTICE_ERROR_VERSION_MISMATCH.
Read-only opens after a crash
A read-only open of a database that was not closed cleanly recovers it in
memory: the journal and log are applied as a read-write open would apply them,
every write that recovery makes is kept in memory, and nothing reaches the
files. The handle sees every committed transaction. The memory is bounded at
64 MB plus four times the size of the log and journal; a recovery that needs
more returns LATTICE_ERROR_FULL, and opening the database read-write once
recovers it on disk. A database with an empty log and no journal opens read-only
exactly as before.
Always initialise from the matching _DEFAULT macro rather than zeroing the
struct yourself, because struct_size has to be set correctly. With lock this
matters more than usual: a zeroed struct asks for no locking, which is the
opposite of what you want.
In-memory databases
lattice_open_options_v4 options = LATTICE_OPEN_OPTIONS_V4_DEFAULT;
lattice_database* db;
lattice_open_v4(":memory:", &options, &db);
Pass :memory: as the path and the database has no files behind it. Nothing is
written to disk and nothing survives closing it, which suits a scratch database, a
test, or one you pulled out of object storage and will hand back as bytes.
It behaves like any other database — transactions, the write-ahead log, and serialization all work. The differences are that it disappears when closed, and that nothing locks it, since no other process can reach it.
Opening :memory: implies creating it, so create does not need to be set: there
is never a previous in-memory database to find.
The file lock
A database can only be open in one process at a time. Opening takes a lock on the
file: a read-write handle takes it exclusively and a read-only handle shares it,
so lattice_open returns LATTICE_ERROR_DATABASE_LOCKED if another process
holds it in a conflicting way. It does not wait.
Note that this is a different error from LATTICE_ERROR_LOCK_TIMEOUT, which
means a second write transaction inside your own process. One is a scheduling
problem you can retry your way out of; the other means the file belongs to
somebody else.
lattice_open_options_v4 options = LATTICE_OPEN_OPTIONS_V4_DEFAULT;
options.lock = false; // only where locking does not work
Turn lock off only on filesystems that do not support locking, such as some
network filesystems, where the alternative is not being able to open the database
at all. It does not make concurrent access safe. It removes the thing that was
going to tell you it was not.
Checkpoints
A commit is durable once it is in the log. A checkpoint writes the pages the log's commits changed into the database file, and can then empty the log. A commit runs one once the log holds 1000 frames (one per page written), and open and close fold whatever the log holds into the file.
lattice_checkpoint_stats stats;
lattice_checkpoint(db, LATTICE_CHECKPOINT_TRUNCATE, &stats); // stats may be NULL
lattice_set_auto_checkpoint(db, 10000, 0); // every 10,000 frames, no minimum gap
lattice_set_auto_checkpoint(db, 0, 0); // commits never checkpoint
LATTICE_CHECKPOINT_PASSIVE gives way if a changed page is in use (then it
writes nothing and reports 0 pages), _FULL writes every changed page, and
_TRUNCATE does that and empties the log; only truncate bounds the log's size.
The stats report pages written, the duration, the log position the file now
holds and whether the log was emptied. A read-only handle gets
LATTICE_ERROR_READ_ONLY.
lattice_set_auto_checkpoint(db, max_wal_frames, min_interval_ms) changes when
that handle's commits checkpoint from then on; 0 frames switches them off and the
log grows until lattice_checkpoint or close. Without it, the
LATTICE_AUTO_CHECKPOINT_FRAMES environment variable sets the frame count. A
larger interval means fewer pauses, each longer, a longer log and more to replay
after a crash; see Checkpointing.
Transaction Operations
// Begin a transaction
lattice_txn* txn;
lattice_begin(db, LATTICE_TXN_READ_WRITE, &txn);
// ... do work ...
// Commit or rollback
lattice_commit(txn);
// or: lattice_rollback(txn);
Transaction modes:
LATTICE_TXN_READ_ONLY— read-only, can run concurrentlyLATTICE_TXN_READ_WRITE— read-write, serialized
Any other mode value is rejected with LATTICE_ERROR_INVALID_ARG.
A successful commit or rollback frees the transaction handle. If
lattice_commit fails for any reason other than the transaction having already
ended (LATTICE_ERROR_TXN_ABORTED), the transaction stays open: retry the commit
or call lattice_rollback. Until you do, it holds the single writer slot, so
later writes fail with LATTICE_ERROR_LOCK_TIMEOUT and lattice_close is
refused.
Node Operations
Create a Node
lattice_node_id node_id;
lattice_node_create(txn, "Person", &node_id);
Set / Get Properties
// Set a string property
lattice_value val = {
.type = LATTICE_VALUE_STRING,
.data.string_val = { "Alice", 5 }
};
lattice_node_set_property(txn, node_id, "name", &val);
// Get a property
lattice_value out;
lattice_node_get_property(txn, node_id, "name", &out);
Check Existence
bool exists;
lattice_node_exists(txn, node_id, &exists);
Delete a Node
lattice_error err = lattice_node_delete(txn, node_id);
if (err == LATTICE_ERROR_HAS_RELATIONSHIPS) {
// The node still has relationships; nothing was deleted.
lattice_node_detach_delete(txn, node_id); // deletes them with it
}
lattice_node_delete refuses a node that still has relationships the
transaction can see, its own uncommitted ones included, with
LATTICE_ERROR_HAS_RELATIONSHIPS, as Cypher's DELETE does: deleting the node
alone would leave edges pointing at nothing. lattice_node_detach_delete
deletes the node and every relationship it has, as DETACH DELETE does, all in
the transaction. Deleting a node that does not exist succeeds and does nothing.
Get Labels
char* labels;
lattice_node_get_labels(txn, node_id, &labels);
// labels is a comma-separated string, e.g. "Person,Employee"
// ...
lattice_free_string(labels);
Set a Vector
float vector[128] = { /* ... */ };
lattice_node_set_vector(txn, node_id, "embedding", vector, 128);
A node holds one vector, which Cypher reads as n.embedding. The key must be
"embedding", "" or NULL; any other key returns LATTICE_ERROR_UNSUPPORTED.
A vector whose length is not the database's dimensions, or with a NaN or
infinite component, returns LATTICE_ERROR_INVALID_ARG.
Explicit Property Indexes
Create property indexes outside an active write transaction. The lookup
functions below find equal values; Cypher also reads the same indexes for
ranges, STARTS WITH and ORDER BY ... LIMIT. Indexed lookup returns
LATTICE_ERROR_UNSUPPORTED if the requested definition does not exist; it never
silently falls back to a scan.
lattice_node_property_index_create(db, "Person", "email");
lattice_value email = {
.type = LATTICE_VALUE_STRING,
.data.string_val = { "[email protected]", 17 }
};
lattice_node_id* ids = NULL;
size_t count = 0;
lattice_nodes_find_by_label_property(
txn, "Person", "email", &email, 10, &ids, &count
);
lattice_free_node_ids(ids, count);
Drop an index with lattice_node_property_index_drop(db, "Person", "email").
Lookups against it start returning LATTICE_ERROR_UNSUPPORTED again once it is
gone.
Edge equivalents are lattice_edge_property_index_create(),
lattice_edge_property_index_drop(), and
lattice_edges_find_by_type_property().
See Property Indexes for when an index is worth adding and which queries the planner can use one for.
Add and Remove Labels
A node's labels can change after it is created:
lattice_node_add_label(txn, node_id, "Employee");
lattice_node_remove_label(txn, node_id, "Candidate");
Find Nodes by Label
Get every node currently carrying a label. An unknown label is not an error; you get a count of zero.
lattice_node_id* ids;
size_t count;
lattice_get_nodes_by_label(db, "Person", 6, &ids, &count);
// ... use ids ...
lattice_free_node_ids(ids, count);
Use the _txn form to see the label as it looks inside a transaction, including
changes that transaction has made but not yet committed:
lattice_get_nodes_by_label_txn(txn, "Person", 6, &ids, &count);
lattice_get_all_nodes_txn(txn, &ids, &count); // every visible node
You own the returned array either way and must release it with
lattice_free_node_ids.
Edge Operations
Create / Delete
lattice_edge_id edge_id;
lattice_edge_create(txn, source_id, target_id, "KNOWS", &edge_id);
lattice_edge_delete(txn, source_id, target_id, "KNOWS");
The returned lattice_edge_id is stable. Use it for edge property APIs and to
identify traversal results. lattice_edge_create returns
LATTICE_ERROR_NOT_FOUND unless both ends exist as the transaction sees them: a
node the transaction created counts, and one it deleted does not.
Edge Properties
lattice_value since = {
.type = LATTICE_VALUE_INT,
.data.int_val = 2020
};
lattice_edge_set_property(txn, edge_id, "since", &since);
lattice_value out;
if (lattice_edge_get_property(txn, edge_id, "since", &out) == LATTICE_OK) {
/* consume out */
lattice_value_free(&out);
}
lattice_edge_remove_property(txn, edge_id, "since");
Traverse Edges
lattice_edge_result* edges;
lattice_edge_get_outgoing(txn, node_id, &edges);
uint32_t count = lattice_edge_result_count(edges);
for (uint32_t i = 0; i < count; i++) {
lattice_edge_id edge_id;
lattice_node_id source, target;
const char* type;
uint32_t type_len;
lattice_edge_result_get_id(edges, i, &edge_id);
lattice_edge_result_get(edges, i, &source, &target, &type, &type_len);
}
lattice_edge_result_free(edges);
The type comes back as a pointer and a length. The bytes are also NUL-terminated, so the pointer can be used as a C string; it stays valid until the result is freed.
Typed traversal accepts a limit. Pass 0 for no limit:
lattice_edge_get_outgoing_by_type(txn, node_id, "KNOWS", 100, &edges);
lattice_edge_get_incoming_by_type(txn, node_id, "KNOWS", 0, &edges);
lattice_edge_scan(txn, edge_type_or_null, limit, &edges) scans native edge
identities for administrative work such as index rebuilds or exports. It is not
the hot-path graph expansion API.
Batch Insert
Insert many nodes with vectors in a single call:
lattice_node_with_vector nodes[1000];
for (int i = 0; i < 1000; i++) {
nodes[i].label = "Document";
nodes[i].vector = vectors[i]; // float[128]
nodes[i].dimensions = 128;
}
lattice_node_id ids[1000];
uint32_t count;
lattice_batch_insert(txn, nodes, 1000, ids, &count);
An empty label ("") creates an unlabeled node, as lattice_node_create does; a
NULL label is rejected.
Vector Search
float query[128] = { /* ... */ };
lattice_vector_result* results;
lattice_vector_search(db, query, 128, 10, 64, &results);
uint32_t count = lattice_vector_result_count(results);
for (uint32_t i = 0; i < count; i++) {
lattice_node_id node_id;
float distance;
lattice_vector_result_get(results, i, &node_id, &distance);
printf("Node %llu: distance=%.4f\n", node_id, distance);
}
lattice_vector_result_free(results);
Parameters:
k— number of nearest neighbors to returnef_search— HNSW search parameter (0 = default 64). Higher values improve recall at the cost of latency. The search usesmax(ef_search, k), so akaboveef_searchstill returnskresults when the database holds that many.
A query vector with a NaN or infinite component returns LATTICE_ERROR_INVALID_ARG.
Full-Text Search
Declare an Index
/* One index per label and property. Declaring it reads the property from every
node already carrying the label; writes maintain it from then on. */
lattice_node_fts_index_create(db, "Document", "text");
Labels and relationship types share one namespace, so a node index and a
relationship index (lattice_edge_fts_index_create) on the same name and
property would share storage: declaring the second one returns
LATTICE_ERROR_ALREADY_EXISTS.
Search
lattice_fts_result* results;
lattice_fts_search(db, "Document", "text", "quick fox", 9, 10, &results);
uint32_t count = lattice_fts_result_count(results);
for (uint32_t i = 0; i < count; i++) {
lattice_node_id node_id;
float score;
lattice_fts_result_get(results, i, &node_id, &score);
printf("Node %llu: score=%.4f\n", node_id, score);
}
lattice_fts_result_free(results);
Fuzzy Search
lattice_fts_result* results;
lattice_fts_search_fuzzy(db, "Document", "text", "quik fox", 8, 10, 2, 4, &results);
// max_distance=2, min_term_length=4
Plain search requires every term; a term no document contains gives no results.
Fuzzy search matches documents containing any of the words, or a near spelling
of one. Both read the same query syntax as Cypher's @@: a OR b, -word,
"a phrase", word* and word~ (see
Query syntax). A query that only
excludes, or a phrase against an index created before 0.17.0, which stores no
word positions, returns LATTICE_ERROR_INVALID_ARG.
Embeddings
Hash Embeddings (Built-in)
float* vector;
uint32_t dims;
lattice_hash_embed("hello world", 11, 128, &vector, &dims);
// Use vector...
lattice_hash_embed_free(vector, dims);
HTTP Embedding Client
lattice_embedding_config config = {
.endpoint = "http://localhost:11434/api/embeddings", // the full URL to POST to
.model = "nomic-embed-text", // required; NULL is rejected with LATTICE_ERROR_INVALID_ARG
.api_format = LATTICE_EMBEDDING_OLLAMA,
.api_key = NULL,
.timeout_ms = 0 // wait for the response to begin; 0 means 30 seconds
};
lattice_embedding_client* client;
lattice_embedding_client_create(&config, &client);
float* vector;
uint32_t dims;
lattice_embedding_client_embed(client, "hello world", 11, &vector, &dims);
// Use vector...
lattice_hash_embed_free(vector, dims);
lattice_embedding_client_free(client);
The client POSTs to endpoint exactly as given, with nothing appended, and
copies the endpoint, model and API key when it is created, so the caller's
strings can be freed afterwards. timeout_ms bounds the wait for the server to
start answering. It does not bound connecting or reading the rest of a response
that has begun, and it is not applied on Windows. A request that times out
returns LATTICE_ERROR_IO.
Durable Streams
A stream is an append-only log stored inside the same database file. You publish records to it, and consumers read forward from wherever they left off. Because the log lives in the database, a record published in a transaction becomes visible exactly when that transaction commits, and never if it rolls back.
See Durable Streams for what they are useful for.
Publishing
lattice_value payload = {
.type = LATTICE_VALUE_STRING,
.data.string_val = { "user signed up", 14 }
};
lattice_stream_publish(txn, "events", 6, "signup", 6, &payload);
Streams are created the first time you publish to one, so there is no separate
setup step. Passing NULL and 0 for the kind uses "message". Names starting
with __lattice_ are reserved for internal use.
If you need the sequence number the record was given, use the longer name:
uint64_t sequence;
lattice_stream_publish_get_sequence(txn, "events", 6, NULL, 0, &payload, &sequence);
That sequence is only durable once the transaction commits.
Reading
Reading happens on the database rather than inside a transaction. You pass the sequence you last saw, and get back the records after it:
lattice_stream_batch* batch;
lattice_stream_read(db, "events", 6, /* after_sequence */ 0, /* limit */ 100,
/* timeout_ms */ 1000, &batch);
size_t n = lattice_stream_batch_count(batch);
for (size_t i = 0; i < n; i++) {
uint64_t sequence;
const char* kind;
size_t kind_len;
const lattice_value* payload;
lattice_stream_batch_get(batch, i, &sequence, &kind, &kind_len, &payload);
// kind and payload are borrowed from the batch
}
lattice_stream_batch_free(batch);
Two things to be careful with. The kind and payload pointers belong to the
batch, so copy anything you need to keep before calling
lattice_stream_batch_free. And reading does not record how far you got; that
is a separate step, described below.
timeout_ms is how long to wait when there is nothing new. It wakes early if
another part of the same process commits a record, which makes it useful for a
consumer loop that should react promptly without spinning.
To find out where a stream currently ends:
uint64_t last;
lattice_stream_get_last_sequence(db, "events", 6, &last); // 0 if empty
Remembering your place
Reading deliberately does not commit an offset, because that would mean losing a record if your program stopped between reading and handling it. Store the offset yourself once the work is actually done:
lattice_stream_set_offset(txn, "events", 6, "billing-worker", 14, sequence);
Because that happens in a transaction, the offset and whatever else the transaction wrote either both land or both do not.
To pick up where a consumer left off:
bool exists;
uint64_t sequence;
lattice_stream_get_offset(db, "events", 6, "billing-worker", 14, &exists, &sequence);
exists is false the first time a consumer runs, which is when you start from
the beginning.
Discarding old records
Once every consumer is past a point, the records before it can go:
lattice_stream_trim(txn, "events", 6, /* through_sequence */ 5000);
Nothing trims automatically. A stream you never trim grows forever.
The changefeed
The reserved stream __lattice_changes records every committed graph change,
and is read with lattice_stream_read like any other stream. It cannot be
published to; lattice_stream_trim drops its events through a sequence, as for
any stream. How much of it to keep is
a retention policy recorded in the file, set through lattice_open_options_v5:
lattice_open_options_v5 options = LATTICE_OPEN_OPTIONS_V5_DEFAULT;
options.changefeed_retention = LATTICE_CHANGEFEED_RETENTION_LAST;
options.changefeed_retention_value = 100000; /* events; milliseconds for AGE */
lattice_open_v5("graph.lattice", &options, &db);
The values are LATTICE_CHANGEFEED_RETENTION_DEFAULT (keep the file's policy),
_ALL, _LAST, _AGE and _OFF. lattice_changefeed_status(db, &mode, &value, &oldest, &last) reports the policy and the range held (oldest is 0
when no events are held), and lattice_changefeed_trim(db, &removed) applies
the policy in full now. Reading after a sequence whose next event was dropped
returns LATTICE_ERROR_NOT_FOUND; reading while the policy is off returns
LATTICE_ERROR_UNSUPPORTED. A transaction's events are its net effect, in an
order that can be replayed as it comes: the edges it deletes, the nodes that
exist after it, the edges that exist after it, then the nodes it deletes, each
group by ascending id. See The Changefeed.
Query Operations
Queries use a prepare/bind/execute pattern:
// 1. Prepare
lattice_query* query;
lattice_query_prepare(db, "MATCH (n) WHERE n.name = $name RETURN n", &query);
// 2. Bind parameters
lattice_value val = {
.type = LATTICE_VALUE_STRING,
.data.string_val = { "Alice", 5 }
};
lattice_query_bind(query, "name", &val);
// For vector parameters:
float vec[128] = { /* ... */ };
lattice_query_bind_vector(query, "embedding", vec, 128);
// 3. Execute
lattice_txn* txn;
lattice_begin(db, LATTICE_TXN_READ_ONLY, &txn);
lattice_result* result;
lattice_query_execute(query, txn, &result);
// 4. Iterate results
while (lattice_result_next(result)) {
uint32_t cols = lattice_result_column_count(result);
for (uint32_t i = 0; i < cols; i++) {
const char* name = lattice_result_column_name(result, i);
lattice_value val;
lattice_result_get(result, i, &val);
// Process val...
}
}
// 5. Cleanup
lattice_result_free(result);
lattice_commit(txn);
lattice_query_free(query);
Choosing a Transaction Mode
lattice_query_execute takes a transaction you opened, which means you have to
decide up front whether the query needs to write. Ask it:
lattice_query* query;
lattice_query_prepare(db, cypher, &query);
lattice_txn* txn;
lattice_begin(db,
lattice_query_writes(query) ? LATTICE_TXN_READ_WRITE
: LATTICE_TXN_READ_ONLY,
&txn);
This matters because the two modes fail in opposite directions. A read-only
transaction cannot run CREATE, SET, DELETE, MERGE, or REMOVE. A
read-write transaction takes the single writer slot, so opening one for a plain
read stops other reads running alongside it.
A query that does not parse is reported as not writing. Execution will report the parse error, and a read transaction is the weaker thing to have opened in the meantime.
Remember to commit rather than roll back when the query wrote something, or the work is discarded.
Finding Out What Went Wrong
lattice_query_prepare only stores the query text; parsing, analysis, planning
and execution all happen in lattice_query_execute, so that is where a bad query
fails. The return code says which kind of failure it was:
| Return code | Meaning |
|---|---|
LATTICE_ERROR_INVALID_ARG | The query does not parse, or does not make sense (an unknown function, a wrong argument count) |
LATTICE_ERROR | It could not be planned, or failed while running (division by zero, integer overflow, a type error) |
LATTICE_ERROR_HAS_RELATIONSHIPS | A DELETE named a node that still has relationships, as lattice_node_delete reports it |
LATTICE_ERROR_NOT_FOUND | A write needed a node or relationship that does not exist, such as a relationship to a node deleted earlier in the query, as lattice_edge_create reports it |
LATTICE_ERROR_IO | The storage failed under the query; the query itself may be fine |
LATTICE_ERROR_OUT_OF_MEMORY | An allocation failed under the query |
A storage or allocation failure fails the query; it is never read as a missing value. These functions describe the failure, and they read from the query handle:
if (lattice_query_execute(query, txn, &result) != LATTICE_OK) {
printf("%s: %s\n",
lattice_query_last_error_code(query), // e.g. "invalid_operator_types"
lattice_query_last_error_message(query)); // human-readable text
if (lattice_query_last_error_has_location(query)) {
printf(" at line %u, column %u, length %u\n",
lattice_query_last_error_line(query),
lattice_query_last_error_column(query),
lattice_query_last_error_length(query));
}
}
For RETURN 1/0 this prints:
DivisionByZero: Division by zero: 1 / 0
at line 1, column 9, length 1
and for MATCH (p:P) DELETE p over a node with a relationship, with
lattice_query_execute returning LATTICE_ERROR_HAS_RELATIONSHIPS:
NodeHasRelationships: Cannot delete node 3 because it still has relationships; delete them first, or use DETACH DELETE
at line 1, column 20, length 1
Execution errors carry a location when the failure belongs to one expression or
clause; a refused delete points at the variable in the DELETE. Plan errors
carry none, and name the part of the query in the message instead. The location is what lets you point at the
offending part of the query, the way the lattice command-line tool underlines
it. The diagnostic code is a stable name for the kind of failure:
parse and semantic failures use lowercase names such as unknown_function, and
execution failures the engine's error names, such as DivisionByZero,
IntegerOverflow, TypeError or NodeHasRelationships.
lattice_query_last_error_stage tells you how far the query got:
LATTICE_QUERY_STAGE_NONE // 0 - no error
LATTICE_QUERY_STAGE_PARSE // 1 - the text is not valid Cypher
LATTICE_QUERY_STAGE_SEMANTIC // 2 - it parses, but does not make sense
LATTICE_QUERY_STAGE_PLAN // 3 - no execution plan could be built
LATTICE_QUERY_STAGE_EXECUTION // 4 - it failed while running
The distinction is useful when deciding whether to blame the query text or the data: a parse or semantic failure will fail again no matter what the database contains, while an execution failure might not.
The returned strings belong to the query handle and stay valid until the next
lattice_query_execute on it, or until you free it.
Searching Inside a Transaction
Vector and full-text search have _txn variants that see the transaction's own
uncommitted changes, where the plain forms see only committed data. Use these
when you have just written something and need to search it in the same
transaction.
lattice_vector_search_txn(txn, query_vector, 128, /* k */ 10,
/* ef_search */ 64, &vector_result);
lattice_fts_search_txn(txn, "Document", "text", "graph database", 14, /* limit */ 20, &fts_result);
lattice_fts_search_fuzzy_txn(txn, "Document", "text", "databse", 7, /* limit */ 20,
/* max_distance */ 2, /* min_term_length */ 4,
&fts_result);
Results are freed the same way as their non-transactional equivalents.
Query Cache
// Clear cache
lattice_query_cache_clear(db);
// Get statistics
uint32_t entries;
uint64_t hits, misses;
lattice_query_cache_stats(db, &entries, &hits, &misses);
Utilities
// Get version string
const char* version = lattice_version(); // e.g. "0.17.0"
// Get error message ("Unknown error" for a code the library does not define)
const char* msg = lattice_error_message(LATTICE_ERROR_NOT_FOUND);
Releasing ID Arrays
Anything that hands you an array of IDs hands you ownership of it. Node IDs and edge IDs have separate release functions, and they are not interchangeable:
lattice_free_node_ids(node_ids, count);
lattice_free_edge_ids(edge_ids, count);
Python API
Python bindings for LatticeDB, an embedded knowledge graph database for AI/RAG applications.
Installation
pip install latticedb
The published wheels bundle the native shared library for Linux (x86_64, aarch64), macOS (x86_64, arm64) and Windows (x64, ARM64), so nothing else needs installing. From a source checkout, build it with zig build shared; the binding finds zig-out/lib (or set LATTICE_LIB_PATH).
Quick Start
import numpy as np
from latticedb import Database
with Database("knowledge.db", create=True, enable_vectors=True, vector_dimensions=4) as db:
# Create nodes, edges, and index content
db.create_node_fts_index("Person", "bio")
with db.write() as txn:
alice = txn.create_node(
labels=["Person"],
properties={"name": "Alice", "age": 30},
)
bob = txn.create_node(
labels=["Person"],
properties={"name": "Bob", "age": 25},
)
txn.create_edge(alice.id, bob.id, "KNOWS")
# Index text for full-text search
txn.set_property(alice.id, "bio", "Alice works on machine learning research")
txn.set_property(bob.id, "bio", "Bob studies deep learning and neural networks")
# Store vector embeddings
txn.set_vector(alice.id, "embedding", np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32))
txn.set_vector(bob.id, "embedding", np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float32))
txn.commit()
# Query with Cypher
result = db.query("MATCH (n:Person) WHERE n.age > 20 RETURN n.name, n.age")
for row in result:
print(row)
# Vector similarity search
query_vec = np.array([0.9, 0.1, 0.0, 0.0], dtype=np.float32)
for r in db.vector_search(query_vec, k=2):
print(f"Node {r.node_id}: distance={r.distance:.4f}")
# Full-text search
for r in db.fts_search("Person", "bio", "machine learning"):
print(f"Node {r.node_id}: score={r.score:.4f}")
# Fuzzy search (typo-tolerant)
for r in db.fts_search_fuzzy("Person", "bio", "machin lerning"):
print(f"Node {r.node_id}: score={r.score:.4f}")
API Reference
Database
Database(
path: str | Path,
*,
create: bool = False, # Create if doesn't exist
read_only: bool = False, # Open in read-only mode
cache_size_mb: int | None = None, # Page cache size; None = LATTICE_BUFFER_POOL_MB or 100
enable_wal: bool = True, # log commits so they survive a crash
enable_adjacency_cache: bool = False, # Accepted; no effect on queries
enable_vectors: bool | None = None, # Create a vector index if the file has none
enable_vector: bool | None = None, # Deprecated compatibility alias
vector_dimensions: int = 128, # Vector dimensions (0 = the file's)
lock: bool = True, # Take the file lock (see below)
sync_mode: str | None = None, # "full" or "normal"; None = LATTICE_SYNC_MODE or full
full_fsync: bool | None = None, # macOS F_FULLFSYNC; None = LATTICE_FULL_FSYNC or off
vector_metric: str | None = None, # "cosine", "euclidean" or "dot_product"
vector_m: int | None = None, # HNSW connections per node, 2..32 (default 16)
vector_ef_construction: int | None = None, # HNSW build candidate list, 1..4096 (default 200)
changefeed_retention: str | None = None, # "all", "off", "last:N", "age:7d"; None = the file's
)
Constructing a Database does not open it: use it as a context manager or call
open() first.
Vector index options
A database file records its vector index: dimensions, metric, vector_m and
vector_ef_construction. A database that has an index opens with it whether or
not enable_vectors is set, so reopening needs no vector options at all, also
after a crash. enable_vectors creates an index if the database has none, and
vector_metric, vector_m and vector_ef_construction configure that new
index; once it exists they are fixed. Any vector option you do pass (and
vector_dimensions when enable_vectors is set) must match the file, or opening
raises LatticeConfigMismatchError.
import numpy as np
from latticedb import Database
with Database("vectors.db", create=True, enable_vectors=True,
vector_dimensions=2, vector_metric="euclidean") as db:
with db.write() as txn:
a = txn.create_node(labels=["Doc"])
txn.set_vector(a.id, "embedding", np.array([1.0, 0.0], dtype=np.float32))
b = txn.create_node(labels=["Doc"])
txn.set_vector(b.id, "embedding", np.array([0.0, 2.0], dtype=np.float32))
txn.commit()
# No vector options: the file says how its index was built.
with Database("vectors.db") as db:
for r in db.vector_search(np.array([1.0, 0.0], dtype=np.float32), k=2):
print(f"Node {r.node_id}: distance={r.distance:.4f}")
# Node 1: distance=0.0000
# Node 2: distance=2.2361
The metric decides search distances, smallest first: cosine distance (vectors stored at unit length), L2 distance, or the negative dot product (vectors stored as given).
Durability options
sync_mode="normal" returns from a commit once the operating system has it: the
commit survives the process being killed, but a power cut or OS crash can lose
the most recent commits. The default, "full", syncs the log on every commit.
full_fsync=True makes each sync on macOS ask the drive to flush its cache. A
value you pass wins over the LATTICE_SYNC_MODE and LATTICE_FULL_FSYNC
environment variables; they apply only when you leave the option unset. See
Durability and the Log.
enable_wal=False logs nothing. Transactions, rollback, streams and the
changefeed work as with the log, but a commit reaches the file at the next
flush (close(), or when half the page cache holds changes) rather than when it
returns; see
Running without the log.
sync_mode, full_fsync, the three vector index options and
changefeed_retention need a native library with lattice_open_v5; against an
older one, setting any of them raises LatticeUnsupportedError.
latticedb.deserialize() takes them too, through lattice_deserialize_v5, with
the same fallback against an older library.
Read-only opens
read_only=True on a database that was not closed cleanly recovers it in
memory: the handle sees every committed transaction, and nothing is written to
the files. If that recovery needs more than 64 MB plus four times the size of
the log and journal, opening raises LatticeFullError; open the database
read-write once to recover it on disk. A file that a newer release has marked as
not writable by this one opens only with read_only=True; a writable open
raises LatticeNeedsNewerWriterError and writes nothing.
In-memory databases
import latticedb
db = latticedb.Database(":memory:")
db.open()
Pass :memory: as the path and the database has no files behind it. Nothing is
written to disk and nothing survives closing it, which suits a scratch database, a
test, or one you pulled out of object storage and will hand back as bytes.
It behaves like any other database — transactions, the write-ahead log, and serialization all work. The differences are that it disappears when closed, and that nothing locks it, since no other process can reach it.
The file lock
A database can only be open in one process at a time. Opening takes a lock on the
file, so a second process gets LatticeDatabaseLockedError rather than quietly
corrupting your data. A read-only handle shares the lock with other readers, but
is still refused while a writer holds the database, because what it would read is
a stale file that a checkpoint may be rewriting underneath it.
Pass lock=False only on filesystems where locking does not work. It does not
make concurrent access safe; it removes the thing that was going to tell you it
was not.
Methods
open()/close()- Open/close the database (also works as context manager)read()- Start a read-only transaction (context manager)write()- Start a read-write transaction (context manager)query(cypher, parameters=None)- Execute a Cypher query in its own transaction, read-write only if the query writes. If the commit fails, the transaction is rolled back before the error is raised, so the writer slot is free for the next writeserialize()- Return the whole database as bytesget_nodes_by_label(label)- IDs of every node with a labelvector_search(vector, *, k=10, ef_search=64)- k-NN vector searchfts_search(label, prop, query, *, limit=10)- Full-text search of one declared indexfts_search_fuzzy(label, prop, query, *, limit=10, max_distance=0, min_term_length=0)- Fuzzy full-text searchcreate_node_fts_index(label, property)/drop_node_fts_index(...)/has_node_fts_index(...)- Manage node full-text indexescreate_edge_fts_index(edge_type, property)/drop_edge_fts_index(...)/has_edge_fts_index(...)- Manage relationship full-text indexes. A node index and a relationship index cannot share a name and property: the second raisesLatticeAlreadyExistsErrorcreate_node_property_index(label, property_key)/drop_node_property_index(...)- Manage explicit node property indexes, used for equality lookups and by Cypher for ranges, prefixes and sortingcreate_edge_property_index(edge_type, property_key)/drop_edge_property_index(...)- Manage explicit edge property indexesread_stream(stream, *, after_sequence=0, limit=100, timeout_ms=0)- Read durable stream records by cursorget_stream_offset(stream, consumer)- Read a committed consumer offsetchanges(*, after_sequence=0, limit=100, timeout_ms=0)- Read the built-in graph changefeed. RaisesLatticeChangesTrimmedError(aLatticeNotFoundError) when retention has dropped the events afterafter_sequence, andLatticeUnsupportedErrorwhen the policy is"off"changefeed_status()- The changefeed's policy and range:ChangefeedStatus(retention, oldest_sequence, last_sequence),oldest_sequenceNone when it holds no eventstrim_changefeed()- Apply the retention policy in full now; returns the number of events droppedcache_clear()- Clear the query cachecache_stats()- Get cache hit/miss statistics
latticedb.deserialize(data, *, copy=True, ...) opens a database from bytes
produced by serialize(), taking the same options as Database apart from path,
create and read_only. latticedb.version() returns the native library version.
Transaction
Read Operations
get_node(node_id)- Get a node by ID, returnsNodeorNonenode_exists(node_id)- Check if a node existsget_property(node_id, key)- Get a property valueget_outgoing_edges(node_id)- Get outgoing edges from a nodeget_incoming_edges(node_id)- Get incoming edges to a nodeget_outgoing_edges_by_type(node_id, edge_type, *, limit=0)/get_incoming_edges_by_type(...)- Edges of one type (0 means no limit)get_nodes_by_label(label)- IDs of every node with a label, as this transaction sees themquery(cypher, parameters=None)- Run Cypher inside this transactionvector_search(...)/fts_search(...)/fts_search_fuzzy(...)- Searches inside this transactionfind_nodes_by_label_property(label, property_key, value, limit=100)- Indexed node equality lookupfind_edges_by_type_property(edge_type, property_key, value, limit=100)- Indexed edge equality lookupis_read_only/is_active- Transaction state
Write Operations
create_node(labels=[], properties=None)- Create a nodedelete_node(node_id, *, detach=False)- Delete a node. A node that still has relationships raisesLatticeHasRelationshipsErrorand nothing is deleted, as Cypher'sDELETEdoes;detach=Truedeletes its relationships with it, asDETACH DELETEdoes. Deleting a node that does not exist does nothing.set_property(node_id, key, value)- Set a property on a nodeset_vector(node_id, key, vector)- Set the node's vector embedding. A node has one vector, which Cypher reads asn.embedding;keymust be"embedding"(or""), and any other key raisesLatticeUnsupportedError. A vector with NaN or infinite components raisesLatticeInvalidArgError.batch_insert_vectors(label, vectors)- Insert vector-bearing nodes in one callbatch_insert(label, vectors)- Deprecated compatibility alias forbatch_insert_vectorscreate_edge(source_id, target_id, edge_type, properties=None)- Create an edge and return its stable edge ID on theEdge. RaisesLatticeNotFoundErrorunless both ends exist as the transaction sees themdelete_edge(source_id, target_id, edge_type)- Delete an edgeset_edge_property(edge_id, key, value)- Set an edge property by stable edge IDget_edge_property(edge_id, key)- Get an edge property by stable edge IDremove_edge_property(edge_id, key)- Remove an edge property by stable edge IDpublish_stream(stream, payload, kind="message")- Publish a durable stream recordpublish_stream_get_sequence(stream, payload, kind="message")- Publish and return the record's sequence numberset_stream_offset(stream, consumer, sequence)- Commit a durable consumer offsettrim_stream(stream, through_sequence)- Delete stream records through a sequencecommit()/rollback()- Commit or rollback the transaction. A commit that raisesLatticeTxnAbortedErrorhas ended the transaction, and rolling it back afterwards does nothing; after any other failure it stays open, and leaving thewithblock rolls it back
Bulk Vector Insertion
Insert many nodes with vectors in a single efficient call:
import numpy as np
from latticedb import Database
with Database("vectors.db", create=True, enable_vectors=True, vector_dimensions=128) as db:
with db.write() as txn:
vectors = np.random.rand(1000, 128).astype(np.float32)
node_ids = txn.batch_insert_vectors("Document", vectors)
print(f"Created {len(node_ids)} nodes")
txn.commit()
Full-Text Search
Exact Search
results = db.fts_search("Person", "bio", "machine learning", limit=10)
for r in results:
print(f"Node {r.node_id}: score={r.score:.4f}")
Fuzzy Search (Typo-Tolerant)
# Finds "machine learning" even with typos
results = db.fts_search_fuzzy("Person", "bio", "machne lerning", limit=10)
# Control fuzzy matching sensitivity
results = db.fts_search_fuzzy(
"Person",
"bio",
"machne",
limit=10,
max_distance=2, # Max edit distance (default: 2)
min_term_length=4, # Min term length for fuzzy matching (default: 4)
)
Embeddings
LatticeDB includes a built-in hash embedding function and an HTTP client for external embedding services.
Hash Embeddings (Built-in)
Deterministic, no external service needed. Useful for testing or simple keyword-based similarity:
from latticedb.embedding import hash_embed
vec = hash_embed("hello world", dimensions=128)
print(vec.shape) # (128,)
HTTP Embedding Client
Connect to Ollama, OpenAI, or compatible APIs:
from latticedb.embedding import EmbeddingClient, EmbeddingApiFormat
# Ollama (default). The endpoint is the full URL the client POSTs to.
with EmbeddingClient("http://localhost:11434/api/embeddings") as client:
vec = client.embed("hello world")
# OpenAI-compatible API
with EmbeddingClient(
"https://api.openai.com/v1/embeddings",
model="text-embedding-3-small",
api_format=EmbeddingApiFormat.OPENAI,
api_key="sk-...",
) as client:
vec = client.embed("hello world")
The endpoint is POSTed to exactly as given; nothing is appended, so a server's
base URL alone (http://localhost:11434) sends the request to / and embed
fails. timeout_ms is how long embed waits for the response to begin: it bounds the wait for the server to start answering (default 30 seconds), not connecting or reading the rest of a response that has begun, and is not applied on Windows.
Edge Traversal
with db.read() as txn:
outgoing = txn.get_outgoing_edges(node_id)
for edge in outgoing:
print(f"{edge.id}: {edge.source_id} --[{edge.edge_type}]--> {edge.target_id}")
incoming = txn.get_incoming_edges(node_id)
for edge in incoming:
print(f"{edge.id}: {edge.source_id} --[{edge.edge_type}]--> {edge.target_id}")
Edge Properties
Edge properties are addressed by stable edge ID. create_edge returns an
Edge object containing that ID, and traversal results include it.
with db.write() as txn:
edge = txn.create_edge(alice.id, bob.id, "KNOWS")
txn.set_edge_property(edge.id, "since", 2020)
assert txn.get_edge_property(edge.id, "since") == 2020
txn.commit()
Durable Streams
with db.write() as txn:
txn.publish_stream("jobs", {"id": 1, "status": "queued"}, kind="job.queued")
txn.set_stream_offset("jobs", "worker-a", 1)
txn.commit()
records = db.read_stream("jobs", after_sequence=0, limit=100)
changes = db.changes(after_sequence=0, limit=100)
changes() returns each transaction's net effect (a property set several times
is one event, from its value before the transaction to its last value), in an
order that can be replayed as it comes: the edges it deletes, the nodes that
exist after it, the edges that exist after it, then the nodes it deletes, each
group by ascending id. How much of the changefeed to keep is set with
changefeed_retention; see The Changefeed.
Cypher Queries
# Pattern matching
result = db.query("MATCH (n:Person) RETURN n.name")
# With parameters
result = db.query(
"MATCH (n:Person) WHERE n.name = $name RETURN n",
parameters={"name": "Alice"},
)
# Vector similarity in Cypher
result = db.query(
"MATCH (n:Document) WHERE n.embedding <=> $vec < 0.5 RETURN n.title",
parameters={"vec": query_vector},
)
# Full-text search in Cypher
result = db.query(
'MATCH (n:Document) WHERE n.content @@ "machine learning" RETURN n.title'
)
# Data mutation
db.query("CREATE (n:Person {name: 'Charlie', age: 35})")
db.query("MATCH (n:Person {name: 'Charlie'}) SET n.age = 36")
db.query("MATCH (n:Person {name: 'Charlie'}) DETACH DELETE n")
Query Cache
# Get cache statistics
stats = db.cache_stats()
print(f"Entries: {stats['entries']}, Hits: {stats['hits']}, Misses: {stats['misses']}")
# Clear the cache
db.cache_clear()
Checkpoints
stats = db.checkpoint("truncate") # fold the log into the file now
db.set_auto_checkpoint(10_000) # commits checkpoint every 10,000 frames
db.set_auto_checkpoint(0) # commits never checkpoint
"passive" gives way if a changed page is in use, "full" writes every changed
page and leaves the log, and "truncate" (the default) also empties it.
CheckpointStats has pages_flushed, duration_ns, checkpoint_lsn and
wal_truncated; set_auto_checkpoint takes min_interval_ms as well.
Without the setter, the LATTICE_AUTO_CHECKPOINT_FRAMES environment variable sets the frame count (default 1000). A larger interval means fewer pauses, each longer, a longer -wal file and more to replay after a crash; see Checkpointing.
Supported Property Types
None- Null valuebool- Booleanint- 64-bit integer; a value outside the signed 64-bit range raisesOverflowErrorfloat- 64-bit floatstr- UTF-8 stringbytes- Binary data- NumPy
ndarray(float32) - Vector list- List of any of these values, nested to any depthdictwithstrkeys - Map of any of these values, nested to any depth
Error Handling
from latticedb import Database, LatticeError, LatticeNotFoundError, LatticeIOError
try:
with Database("nonexistent.db") as db:
pass
except LatticeNotFoundError:
print("Database not found")
except LatticeIOError:
print("I/O error")
except LatticeError as e:
print(f"Error: {e}")
Every exception is a LatticeError and carries the C error code as .code.
The more specific classes include:
| Exception | Code | Raised when |
|---|---|---|
LatticeNotFoundError | -4 | The database file is missing, or create_edge names an end that does not exist |
LatticeDatabaseLockedError | -16 | Another process holds the file |
LatticeHasRelationshipsError | -17 | delete_node without detach=True on a node with relationships |
LatticeConfigMismatchError | -18 | Open options that contradict the file's vector index |
LatticeNeedsNewerWriterError | -19 | A writable open of a file only a newer release may write |
LatticeVersionMismatchError | -11 | An open, read-only included, of a file or log in a format only a newer release can read |
LatticeFullError | -10 | A read-only open whose crash recovery needs more memory than it may use |
LatticeCorruptionError | -3 | An open whose log is damaged where it had been synced, or holds a committed change that cannot be replayed |
LatticeQueryError | varies | Any failed Cypher query (below) |
Query errors
A failed query raises LatticeQueryError, which says what failed and where:
from latticedb import Database, LatticeQueryError
with Database("graph.db", create=True) as db:
try:
db.query("RETURN 1/0")
except LatticeQueryError as e:
print(e) # Division by zero: 1 / 0
print(e.code) # -1
print(e.stage) # execution
print(e.diagnostic_code) # DivisionByZero
print(e.location) # {'line': 1, 'column': 9, 'length': 1}
stage is "parse", "semantic", "plan" or "execution". A query that does
not parse or does not make sense (an unknown function such as lenght(x) is
unknown_function at the semantic stage) has code -6; one that fails while
running has code -1, except that a DELETE of a node that still has
relationships has code -17 and diagnostic code NodeHasRelationships, and a
relationship created to a node deleted earlier in the query has code -4 and
NotFound, the codes delete_node and create_edge give. A storage failure
under a query has code -2 and an allocation failure -13; these are still raised
as LatticeQueryError, so check .code to tell them from a fault in the
query. location is None when the failure does not belong to one place in the
text.
Requirements
- Python 3.9+
- NumPy (a required dependency)
- The native LatticeDB library (
liblattice.dylib/liblattice.so/lattice.dll), bundled in the published wheels
TypeScript / Node.js API
TypeScript/Node.js bindings for LatticeDB, an embedded knowledge graph database for AI/RAG applications.
Installation
npm install @hajewski/latticedb
The published package bundles the native shared library for Linux (x64, arm64), macOS (x64, arm64) and Windows (x64, arm64), so nothing else needs installing. From a source checkout, build it with zig build shared; the loader finds zig-out/lib (or set LATTICE_LIB_PATH).
Quick Start
import { Database } from "@hajewski/latticedb";
const db = new Database("knowledge.db", {
create: true,
enableVectors: true,
vectorDimensions: 4,
});
await db.open();
// Create nodes, edges, and index content
await db.createNodeFtsIndex("Person", "bio");
await db.write(async (txn) => {
const alice = await txn.createNode({
labels: ["Person"],
properties: { name: "Alice", age: 30 },
});
const bob = await txn.createNode({
labels: ["Person"],
properties: { name: "Bob", age: 25 },
});
await txn.createEdge(alice.id, bob.id, "KNOWS");
// Writing the indexed property is what makes it searchable
await txn.setProperty(alice.id, "bio", "Alice works on machine learning research");
await txn.setProperty(bob.id, "bio", "Bob studies deep learning and neural networks");
// Store vector embeddings
await txn.setVector(
alice.id,
"embedding",
new Float32Array([1.0, 0.0, 0.0, 0.0])
);
await txn.setVector(
bob.id,
"embedding",
new Float32Array([0.0, 1.0, 0.0, 0.0])
);
});
// Query with Cypher
const result = await db.query(
"MATCH (n:Person) WHERE n.age > 20 RETURN n.name, n.age"
);
for (const row of result.rows) {
console.log(row);
}
// Vector similarity search
const results = await db.vectorSearch(
new Float32Array([0.9, 0.1, 0.0, 0.0]),
{ k: 2 }
);
for (const r of results) {
console.log(`Node ${r.nodeId}: distance=${r.distance.toFixed(4)}`);
}
// Full-text search
const ftsResults = await db.ftsSearch("Person", "bio", "machine learning");
for (const r of ftsResults) {
console.log(`Node ${r.nodeId}: score=${r.score.toFixed(4)}`);
}
// Fuzzy search (typo-tolerant)
const fuzzyResults = await db.ftsSearchFuzzy("Person", "bio", "machin lerning");
for (const r of fuzzyResults) {
console.log(`Node ${r.nodeId}: score=${r.score.toFixed(4)}`);
}
await db.close();
API Reference
Database
const db = new Database(path: string, options?: DatabaseOptions);
interface DatabaseOptions {
create?: boolean; // Create if not exists (default: false)
readOnly?: boolean; // Open read-only (default: false)
cacheSizeMb?: number; // Cache size in MB; unset: LATTICE_BUFFER_POOL_MB, else 100
enableWal?: boolean; // log commits so they survive a crash (default: true)
enableAdjacencyCache?: boolean; // Accepted; no effect on queries (default: false)
enableVectors?: boolean; // Create a vector index if the file has none
enableVector?: boolean; // Deprecated compatibility alias
vectorDimensions?: number; // Vector dimensions (default: 128; 0 = the file's)
lock?: boolean; // Take the file lock (default: true)
syncMode?: 'full' | 'normal'; // Unset: LATTICE_SYNC_MODE, else 'full'
fullFsync?: boolean; // macOS F_FULLFSYNC; unset: LATTICE_FULL_FSYNC, else off
vectorMetric?: 'cosine' | 'euclidean' | 'dot_product'; // For a new index (default: cosine)
vectorM?: number; // HNSW connections per node, 2..32 (default: 16)
vectorEfConstruction?: number; // HNSW build candidate list, 1..4096 (default: 200)
changefeedRetention?: ChangefeedRetention; // 'all', 'off', 'last:N', 'age:7d' (default: the file's)
}
A database file records its vector index: dimensions, metric, vectorM and
vectorEfConstruction. A database that has an index opens with it whether or
not enableVectors is set, so reopening needs no vector options at all, also
after a crash. enableVectors creates an index if the database has none, and
vectorMetric, vectorM and vectorEfConstruction configure that new index;
once it exists they are fixed. Any vector option you do pass (and
vectorDimensions when enableVectors is set) must match the file, or open()
throws a LatticeError with code -18 (ConfigMismatch).
const db = new Database("vectors.db", {
create: true,
enableVectors: true,
vectorDimensions: 2,
vectorMetric: "euclidean",
});
await db.open();
await db.write(async (txn) => {
const a = await txn.createNode({ labels: ["Doc"] });
await txn.setVector(a.id, "embedding", new Float32Array([1, 0]));
const b = await txn.createNode({ labels: ["Doc"] });
await txn.setVector(b.id, "embedding", new Float32Array([0, 2]));
});
await db.close();
// No vector options: the file says how its index was built.
const reopened = new Database("vectors.db");
await reopened.open();
console.log(await reopened.vectorSearch(new Float32Array([1, 0]), { k: 2 }));
// [ { nodeId: 1n, distance: 0 }, { nodeId: 2n, distance: 2.2360680103302 } ]
await reopened.close();
The metric decides search distances, smallest first: cosine distance (vectors stored at unit length), L2 distance, or the negative dot product (vectors stored as given).
syncMode: 'normal' returns from a commit once the operating system has it: the
commit survives the process being killed, but a power cut or OS crash can lose
the most recent commits. The default, 'full', syncs the log on every commit.
fullFsync: true makes each sync on macOS ask the drive to flush its cache. A
value you pass wins over the LATTICE_SYNC_MODE and LATTICE_FULL_FSYNC
environment variables; they apply only when you leave the option unset. See
Durability and the Log.
enableWal: false logs nothing. Transactions, rollback, streams and the
changefeed work as with the log, but a commit reaches the file at the next
flush (close(), or when half the page cache holds changes) rather than when it
returns; see
Running without the log.
syncMode, fullFsync, the three vector index options and
changefeedRetention need a native library with lattice_open_v5; against an
older one, setting any of them throws with code -14 (Unsupported).
deserialize() takes them too, through lattice_deserialize_v5, with the same
fallback against an older library.
readOnly: true on a database that was not closed cleanly recovers it in
memory: the handle sees every committed transaction, and nothing is written to
the files. If that recovery needs more than 64 MB plus four times the size of
the log and journal, open() throws with code -10 (Full); open the database
read-write once to recover it on disk. A file that a newer release has marked as
not writable by this one opens only with readOnly: true; a writable open
throws with code -19 (NeedsNewerWriter) and writes nothing.
In-memory databases
const db = new Database(':memory:');
Pass :memory: as the path and the database has no files behind it. Nothing is
written to disk and nothing survives closing it, which suits a scratch database, a
test, or one you pulled out of object storage and will hand back as bytes.
It behaves like any other database — transactions, the write-ahead log, and serialization all work. The differences are that it disappears when closed, and that nothing locks it, since no other process can reach it.
The file lock
A database can only be open in one process at a time. Opening takes a lock on the
file, so a second process gets a LatticeError with
code === -16 (LATTICE_ERROR_DATABASE_LOCKED) rather than quietly corrupting your
data. A read-only handle shares the lock with other readers, but is still refused
while a writer holds the database, because what it would read is a stale file that
a checkpoint may be rewriting underneath it.
Pass lock: false only on filesystems where locking does not work. It does not
make concurrent access safe; it removes the thing that was going to tell you it
was not.
Methods
await db.open()- Open the database connectionawait db.close()- Close the database connectiondb.serialize()- Return the whole database as bytesawait db.read(fn)- Execute a read-only transactionawait db.write(fn)- Execute a read-write transactionawait db.query(cypher, params?)- Execute a Cypher queryawait db.getNodesByLabel(label)- IDs of every node with a labelawait db.vectorSearch(vector, options?)- k-NN vector searchawait db.ftsSearch(label, property, query, options?)- Full-text search of one declared indexawait db.ftsSearchFuzzy(label, property, query, options?)- Fuzzy full-text searchawait db.createNodeFtsIndex(label, property)/dropNodeFtsIndex(...)/hasNodeFtsIndex(...)- Manage node full-text indexesawait db.createEdgeFtsIndex(edgeType, property)/dropEdgeFtsIndex(...)/hasEdgeFtsIndex(...)- Manage relationship full-text indexes. A node index and a relationship index cannot share a name and property: the second is rejected as already existingawait db.createNodePropertyIndex(label, property)/dropNodePropertyIndex(...)- Manage explicit node property indexes, used for equality lookups and by Cypher for ranges, prefixes and sortingawait db.createEdgePropertyIndex(edgeType, property)/dropEdgePropertyIndex(...)- Manage explicit edge property indexesawait db.readStream(stream, options?)- Read durable stream records by cursor. WithtimeoutMs > 0the wait runs on a worker thread, so the event loop keeps running and a commit from the same process can end the waitawait db.getStreamOffset(stream, consumer)- Read a committed consumer offsetawait db.changes(options?)- Read the built-in graph changefeed. Rejects withLatticeChangesTrimmedErrorwhen retention has dropped the events afterafterSequence, and with code -14 (Unsupported) when the policy is'off'await db.changefeedStatus()- The changefeed's policy and range:{ retention, oldestSequence, lastSequence },oldestSequencenull when it holds no eventsawait db.trimChangefeed()- Apply the retention policy in full now; resolves to the number of events droppedawait db.cacheClear()- Clear the query cacheawait db.cacheStats()- Get cache hit/miss statisticsdb.isOpen()- Check if database is opendb.getPath()- Get database file path
deserialize(bytes, options?, copy = true), exported from the package root, opens a
database from bytes produced by serialize().
Node IDs, edge IDs and stream sequence numbers are bigint.
Transaction
Read Operations
await txn.getNode(nodeId)- Get a node by ID, returnsNodeornullawait txn.nodeExists(nodeId)- Check if a node existsawait txn.getProperty(nodeId, key)- Get a property value, ornullwhen the node does not have itawait txn.getOutgoingEdges(nodeId)- Get outgoing edges from a nodeawait txn.getIncomingEdges(nodeId)- Get incoming edges to a nodeawait txn.getOutgoingEdgesByType(nodeId, edgeType, ...)/getIncomingEdgesByType(...)- Edges of one typeawait txn.getNodesByLabel(label)- IDs of every node with a label, as this transaction sees themawait txn.query(cypher, params?)- Run Cypher inside this transactionawait txn.vectorSearch(...)/ftsSearch(...)/ftsSearchFuzzy(...)- Searches inside this transactionawait txn.findNodesByLabelProperty(label, property, value, limit?)- Indexed node equality lookupawait txn.findEdgesByTypeProperty(edgeType, property, value, limit?)- Indexed edge equality lookuptxn.isReadOnly()/txn.isActive()- Transaction state
Write Operations
await txn.createNode({ labels, properties })- Create a nodeawait txn.deleteNode(nodeId, { detach })- Delete a node. A node that still has relationships is refused with code -17 (HasRelationships) and nothing is deleted, as Cypher'sDELETEdoes;{ detach: true }deletes its relationships with it, asDETACH DELETEdoes. Deleting a node that does not exist does nothing.await txn.setProperty(nodeId, key, value)- Set a propertyawait txn.setVector(nodeId, key, vector)- Set the node's vector embedding. A node has one vector, which Cypher reads asn.embedding;keymust be"embedding"(or""), and any other key is rejected with an unsupported-operation error. A vector with NaN or infinite components is rejected as an invalid argument.await txn.batchInsertVectors(label, vectors)- Insert vector-bearing nodes in one callawait txn.batchInsert(label, vectors)- Deprecated compatibility alias forbatchInsertVectorsawait txn.createEdge(sourceId, targetId, edgeType, options?)- Create an edge and return its stable edge ID on theEdge. Throws with code -4 (NotFound) unless both ends exist as the transaction sees themawait txn.deleteEdge(sourceId, targetId, edgeType)- Delete an edgeawait txn.setEdgeProperty(edgeId, key, value)- Set an edge property by stable edge IDawait txn.getEdgeProperty(edgeId, key)- Get an edge property by stable edge IDawait txn.removeEdgeProperty(edgeId, key)- Remove an edge property by stable edge IDtxn.publishStream(stream, payload, kind?)- Publish a durable stream recordtxn.publishStreamGetSequence(stream, payload, kind?)- Publish and return the record's sequence (bigint)txn.setStreamOffset(stream, consumer, sequence)- Commit a durable consumer offsettxn.trimStream(stream, throughSequence)- Delete stream records through a sequencetxn.commit()/txn.rollback()- Commit or rollback. A commit that throws with code -7 (TxnAborted) has ended the transaction, androllback()afterwards does nothing; after any other failure it stays open forrollback()
Batch Insert
Insert many nodes with vectors in a single efficient call:
import { Database } from "@hajewski/latticedb";
const db = new Database("vectors.db", {
create: true,
enableVectors: true,
vectorDimensions: 128,
});
await db.open();
await db.write(async (txn) => {
const vectors = Array.from({ length: 1000 }, () =>
Float32Array.from({ length: 128 }, () => Math.random())
);
const nodeIds = await txn.batchInsertVectors("Document", vectors);
console.log(`Created ${nodeIds.length} nodes`);
});
await db.close();
Full-Text Search
Exact Search
const results = await db.ftsSearch("Person", "bio", "machine learning", { limit: 10 });
for (const r of results) {
console.log(`Node ${r.nodeId}: score=${r.score.toFixed(4)}`);
}
Fuzzy Search (Typo-Tolerant)
// Finds "machine learning" even with typos
const results = await db.ftsSearchFuzzy("Person", "bio", "machne lerning", { limit: 10 });
// Control fuzzy matching sensitivity
const precise = await db.ftsSearchFuzzy("Person", "bio", "machne", {
limit: 10,
maxDistance: 2, // Max edit distance (default: 0 = auto)
minTermLength: 4, // Min term length for fuzzy matching (default: 0 = auto)
});
Embeddings
LatticeDB includes a built-in hash embedding function and an HTTP client for external embedding services.
Hash Embeddings (Built-in)
Deterministic, no external service needed. Useful for testing or simple keyword-based similarity:
import { hashEmbed } from "@hajewski/latticedb/embedding";
const vec = hashEmbed("hello world", 128);
console.log(vec.length); // 128
HTTP Embedding Client
Connect to Ollama, OpenAI, or compatible APIs:
import { EmbeddingClient, EmbeddingApiFormat } from "@hajewski/latticedb/embedding";
// Ollama (default). The endpoint is the full URL the client POSTs to.
const client = new EmbeddingClient({
endpoint: "http://localhost:11434/api/embeddings",
});
const vec = client.embed("hello world");
client.close();
// OpenAI-compatible API
const openaiClient = new EmbeddingClient({
endpoint: "https://api.openai.com/v1/embeddings",
model: "text-embedding-3-small",
apiFormat: EmbeddingApiFormat.OpenAI,
apiKey: "sk-...",
});
const embedding = openaiClient.embed("hello world");
openaiClient.close();
The endpoint is POSTed to exactly as given; nothing is appended, so a server's
base URL alone (http://localhost:11434) sends the request to / and embed
throws. timeoutMs is how long embed waits for the response to begin: it bounds the wait for the server to start answering (default 30 seconds), not connecting or reading the rest of a response that has begun, and is not applied on Windows.
Edge Traversal
await db.read(async (txn) => {
const outgoing = await txn.getOutgoingEdges(nodeId);
for (const edge of outgoing) {
console.log(`${edge.id}: ${edge.sourceId} --[${edge.type}]--> ${edge.targetId}`);
}
const incoming = await txn.getIncomingEdges(nodeId);
for (const edge of incoming) {
console.log(`${edge.id}: ${edge.sourceId} --[${edge.type}]--> ${edge.targetId}`);
}
});
Edge Properties
Edge properties are addressed by stable edge ID. createEdge returns an Edge
object containing that ID, and traversal results include it.
await db.write(async (txn) => {
const edge = await txn.createEdge(alice.id, bob.id, "KNOWS");
await txn.setEdgeProperty(edge.id, "since", 2020);
const since = await txn.getEdgeProperty(edge.id, "since");
});
Durable Streams
await db.write(async (txn) => {
await txn.publishStream("jobs", { id: 1, status: "queued" }, "job.queued");
await txn.setStreamOffset("jobs", "worker-a", 1n);
});
const records = await db.readStream("jobs", { afterSequence: 0n, limit: 100 });
const changes = await db.changes({ afterSequence: 0n, limit: 100 });
changes() returns each transaction's net effect (a property set several times
is one event, from its value before the transaction to its last value), in an
order that can be replayed as it comes: the edges it deletes, the nodes that
exist after it, the edges that exist after it, then the nodes it deletes, each
group by ascending id. How much of the changefeed to keep is set with
changefeedRetention; see The Changefeed.
Cypher Queries
// Pattern matching
const result = await db.query("MATCH (n:Person) RETURN n.name");
// With parameters
const result = await db.query(
"MATCH (n:Person) WHERE n.name = $name RETURN n",
{ name: "Alice" }
);
// Vector similarity in Cypher
const result = await db.query(
"MATCH (n:Document) WHERE n.embedding <=> $vec < 0.5 RETURN n.title",
{ vec: new Float32Array([0.1, 0.2, 0.3, 0.4]) }
);
// Full-text search in Cypher
const result = await db.query(
'MATCH (n:Document) WHERE n.content @@ "machine learning" RETURN n.title'
);
// Data mutation
await db.query('CREATE (n:Person {name: "Charlie", age: 35})');
await db.query('MATCH (n:Person {name: "Charlie"}) SET n.age = 36');
await db.query('MATCH (n:Person {name: "Charlie"}) DETACH DELETE n');
Query Cache
// Get cache statistics
const stats = await db.cacheStats();
console.log(
`Entries: ${stats.entries}, Hits: ${stats.hits}, Misses: ${stats.misses}`
);
// Clear the cache
await db.cacheClear();
Checkpoints
const stats = await db.checkpoint('truncate'); // fold the log into the file now
await db.setAutoCheckpoint(10000); // commits checkpoint every 10,000 frames
await db.setAutoCheckpoint(0); // commits never checkpoint
'passive' gives way if a changed page is in use, 'full' writes every changed
page and leaves the log, and 'truncate' (the default) also empties it. The
stats report pagesFlushed, durationNs, checkpointLsn and walTruncated;
setAutoCheckpoint takes an optional minimum gap in milliseconds as its second
argument. Without the setter, the LATTICE_AUTO_CHECKPOINT_FRAMES environment variable sets the frame count (default 1000). A larger interval means fewer pauses, each longer, a longer -wal file and more to replay after a crash; see Checkpointing.
Supported Property Types
null- Null valueboolean- Booleannumber- Integer or floatbigint- 64-bit integerstring- UTF-8 stringUint8Array- Binary dataFloat32Array- Vector- Arrays of any of these values, nested to any depth
- Plain objects with string keys, whose values are any of these, nested to any depth
Error Handling
import { Database, isLibraryAvailable } from "@hajewski/latticedb";
// Check if native library is available
if (!isLibraryAvailable()) {
console.error("LatticeDB native library not found");
process.exit(1);
}
try {
const db = new Database("test.db", { create: true });
await db.open();
// ...
await db.close();
} catch (error) {
console.error("Database error:", error);
}
Errors from the native library are LatticeErrors whose code is the C error
code; LatticeErrorCode, exported from the package root, names them (with
QueryErrorStage for LatticeQueryError.stage; both are plain enums, readable
at run time). For example -4 (NotFound, also from createEdge when either end
does not exist), -10 (Full, a read-only open whose crash recovery needs more
memory than it may use), -11 (VersionMismatch, a file in a format only a newer
release can read), -16 (DatabaseLocked, another process holds the file), -17
(HasRelationships, a plain deleteNode of a node with relationships), -18
(ConfigMismatch, open options that contradict the file's vector index) and -19
(NeedsNewerWriter, a writable open of a file only a newer release may write).
A failed Cypher query throws a LatticeQueryError, a LatticeError that also
says where the query failed:
import { Database, LatticeQueryError } from "@hajewski/latticedb";
try {
await db.query("RETURN 1/0");
} catch (e) {
if (e instanceof LatticeQueryError) {
console.log(e.message); // Division by zero: 1 / 0
console.log(e.code); // -1
console.log(e.stage); // 4 (execution)
console.log(e.diagnosticCode); // DivisionByZero
console.log(e.location); // { line: 1, column: 9, length: 1 }
}
}
stage is a QueryErrorStage: 1 parse, 2 semantic, 3 plan, 4 execution. Parse
and semantic failures (an unknown function is unknown_function) have code -6
and execution failures -1, except that a DELETE of a node with relationships
has code -17 and a relationship created to a node deleted earlier in the query
-4, as deleteNode and createEdge report them. A storage failure under a query
has code -2 and an allocation failure -13. location is undefined when the
failure does not belong to one place in the query.
Building from Source
Requires Node.js 18+ and the LatticeDB native library.
# From the latticedb root directory
zig build shared
# Build the TypeScript bindings
cd bindings/typescript
npm install
npm run build
# Run tests
npm test
Requirements
- Node.js 18+
- The native LatticeDB library (
liblattice.dylib/liblattice.so/lattice.dll), bundled in the published package
Go
The Go binding wraps the C API through cgo. Everything is a normal Go value:
properties are any, errors are ordinary errors you can compare with
errors.Is, and transactions are closures so you cannot forget to finish one.
Installing
go get github.com/jeffhajewski/latticedb/bindings/go
Because it uses cgo, building needs the LatticeDB shared library, the header,
and the lattice.pc pkg-config file, which is what the default build looks up.
The install.sh script installs only the CLI and the shared library, so it is not
enough on its own. Either unpack a release archive (it carries include/, lib/
and lib/pkgconfig/lattice.pc) or install from a checkout, then point pkg-config
at it:
zig build install --prefix /tmp/lattice-install # or unpack a release archive
export PKG_CONFIG_PATH=/tmp/lattice-install/lib/pkgconfig
If you are working inside a checkout of the repository, build the library first
and use the repolocal build tag instead, which points the compiler and linker at
include/ and zig-out/lib:
zig build
go run -tags repolocal .
Opening a database
import latticedb "github.com/jeffhajewski/latticedb/bindings/go"
db, err := latticedb.Open("graph.lattice", latticedb.OpenOptions{Create: true})
if err != nil {
log.Fatal(err)
}
defer db.Close()
OpenOptions covers the things you have to decide when the file is created:
| Field | What it does |
|---|---|
Create | Create the file if it is not there |
ReadOnly | Open without the ability to write |
CacheSizeMB | How much memory to keep pages in (0: LATTICE_BUFFER_POOL_MB if set, else 100 MB) |
PageSize | Page size in bytes |
EnableVectors | Create a vector index if the database has none |
VectorDimensions | How many numbers are in each vector, when EnableVectors is set (0 means the file's; creating an index needs it set) |
VectorMetric | How a new index measures distance: VectorMetricCosine (the default), VectorMetricEuclidean or VectorMetricDotProduct |
VectorM | HNSW connections per node for a new index, 2..32 (0 means 16) |
VectorEfConstruction | HNSW candidate list size while building a new index, 1..4096 (0 means 200) |
SyncMode | When a commit waits for the disk: SyncModeFull or SyncModeNormal |
FullFsync | On macOS, whether syncs ask the drive to flush its cache: FullFsyncOn or FullFsyncOff |
EnableAdjacencyCache | Accepted for compatibility. Queries and edge calls do not read it, so it changes neither their speed nor their results |
DisableWAL | Open without write-ahead logging: transactions work as with the log, and a commit reaches the file at the next flush. See Running without the log |
DisableLock | Open without taking a lock on the file |
ChangefeedRetention | How much of the changefeed to keep: "all", "off", "last:N", "age:7d"; empty keeps the file's. See The Changefeed |
Three of these need a word of explanation. DisableWAL and DisableLock are
phrased as negatives because a Go bool cannot tell "the caller left this alone"
apart from "the caller set it to false", and both of those features default to
on. Set them when you genuinely want them off. There is also an older
EnableVector field kept for compatibility; new code should use EnableVectors.
In-memory databases
db, err := latticedb.Open(":memory:", latticedb.OpenOptions{})
Pass :memory: as the path and the database has no files behind it. Nothing is
written to disk and nothing survives closing it, which suits a scratch database, a
test, or one you pulled out of object storage and will hand back as bytes.
It behaves like any other database — transactions, the write-ahead log, and serialization all work. The differences are that it disappears when closed, and that nothing locks it, since no other process can reach it.
A database can only be open in one process at a time. Opening takes a lock on the
file, so a second process gets an error whose Code is ErrorDatabaseLocked
rather than quietly corrupting your data. A read-only handle shares the lock with
other readers, but is still refused while a writer holds the database, because
what it would read is a stale file that a checkpoint may be rewriting underneath
it. Set DisableLock only on filesystems where locking does not work; it does not
make concurrent access safe, it removes the thing that was going to tell you it
was not.
The vector index
A database file records its vector index: the dimensions, the metric,
VectorM and VectorEfConstruction. A database that has an index opens with it
whether or not EnableVectors is set, so reopening needs no vector options at
all, also after a crash. The metric and the two HNSW settings configure a new
index and are fixed once it exists. Any of them that is set, and
VectorDimensions when EnableVectors is set, must match the file, or Open
returns an error whose Code is ErrorConfigMismatch. VectorDimensions 0
with EnableVectors means the file's dimensions: it opens a database that has an
index whatever its size, and returns ErrorInvalidArg where an index would have
to be created.
db, err := latticedb.Open("vectors.lattice", latticedb.OpenOptions{
Create: true,
EnableVectors: true,
VectorDimensions: 2,
VectorMetric: latticedb.VectorMetricEuclidean,
})
// ... store vectors, close ...
db, err = latticedb.Open("vectors.lattice", latticedb.OpenOptions{})
results, err := db.VectorSearch([]float32{1, 0}, latticedb.VectorSearchOptions{K: 2})
// [{1 0} {2 2.236068}]
Cosine stores vectors at unit length and returns the cosine distance; Euclidean returns the L2 distance and dot product the negative dot product, both over vectors stored as given. Results come smallest first.
Durability settings
SyncModeFull, the default, syncs the log on every commit, so a commit that has
returned survives a power cut. SyncModeNormal returns once the operating
system has the commit: it survives the process being killed, but a power cut or
OS crash can lose the most recent commits. FullFsyncOn makes each sync on
macOS ask the drive to flush its cache. The zero values defer to the
LATTICE_SYNC_MODE and LATTICE_FULL_FSYNC environment variables, else a full
sync without F_FULLFSYNC; a value you set wins over them. See
Durability and the Log.
Open goes through lattice_open_v5, so the binding needs a native library
that has it, as does Deserialize, which takes the same options.
Read-only opens
ReadOnly: true on a database that was not closed cleanly recovers it in
memory: the handle sees every committed transaction and nothing is written to
the files. A recovery that needs more than 64 MB plus four times the size of the
log and journal fails with ErrorFull; open the database read-write once to
recover it on disk. A file that a newer release has marked as not writable by
this one opens only with ReadOnly: true; a writable Open returns
ErrorNeedsNewerWriter and writes nothing. A file in a format only a newer
release can read is refused by every open with ErrorVersionMismatch.
Checkpoints
stats, err := db.Checkpoint(latticedb.CheckpointTruncate) // fold the log into the file now
err = db.SetAutoCheckpoint(10000, 0) // commits checkpoint every 10,000 frames
err = db.SetAutoCheckpoint(0, 0) // commits never checkpoint
CheckpointPassive gives way if a changed page is in use, CheckpointFull
writes every changed page, and CheckpointTruncate does that and empties the
log. CheckpointStats reports PagesFlushed, Duration, CheckpointLSN and
WALTruncated. Without the setter, the LATTICE_AUTO_CHECKPOINT_FRAMES environment variable sets the frame count (default 1000). A larger interval means fewer pauses, each longer, a longer -wal file and more to replay after a crash; see Checkpointing.
Writing
Update runs a function inside a write transaction. Return nil and it
commits; return an error and it rolls back and hands you the error:
err = db.Update(func(tx *latticedb.Tx) error {
alice, err := tx.CreateNode(latticedb.CreateNodeOptions{
Labels: []string{"Person"},
Properties: map[string]latticedb.Value{"name": "Alice", "email": "[email protected]"},
})
if err != nil {
return err
}
bob, err := tx.CreateNode(latticedb.CreateNodeOptions{
Labels: []string{"Person"},
Properties: map[string]latticedb.Value{"name": "Bob"},
})
if err != nil {
return err
}
_, err = tx.CreateEdge(alice.ID, bob.ID, "KNOWS", latticedb.CreateEdgeOptions{
Properties: map[string]latticedb.Value{"since": int64(2020)},
})
return err
})
Value is an alias for any, so you pass Go values straight through. Strings,
int64, float64, bool, []byte, and []float32 for vectors all work. Note
int64 rather than int, since the stored type is explicitly 64-bit.
CreateEdge returns ErrorNotFound unless both ends exist as the transaction
sees them. DeleteNode refuses a node that still has relationships with
ErrorHasRelationships and deletes nothing, as Cypher's DELETE does;
DetachDeleteNode deletes the node and all its relationships, as
DETACH DELETE does:
err = db.Update(func(tx *latticedb.Tx) error {
return tx.DeleteNode(aliceID)
})
var latticeErr *latticedb.Error
if errors.As(err, &latticeErr) && latticeErr.Code == latticedb.ErrorHasRelationships {
err = db.Update(func(tx *latticedb.Tx) error {
return tx.DetachDeleteNode(aliceID)
})
}
Only one write transaction can be open at a time. A second one fails
immediately with ErrorLockTimeout rather than waiting, so if several
goroutines write, they need to take turns. See
One writer at a time.
Reading
View is the read-only counterpart:
err = db.View(func(tx *latticedb.Tx) error {
name, ok, err := tx.GetProperty(nodeID, "name")
if err != nil {
return err
}
if ok {
fmt.Println(name) // Alice
}
return nil
})
Property reads return a value, whether it was there, and an error. The middle return is what separates "this property is not set" from "this property is set to something empty", which a zero value alone could not tell you.
If you would rather manage the transaction yourself, BeginRead, BeginWrite,
Commit, and Rollback are available. Update and View are safer, because
they cannot leave a transaction open on an early return. Update also rolls
back when the commit itself fails; a manual Commit that returns an error leaves
the transaction open, holding the writer slot, until you call Rollback. The
exception is ErrorTxnAborted: the native transaction is already gone, so the
Tx is no longer active and Rollback does nothing.
Queries
result, err := db.Query(`MATCH (p:Person) WHERE p.email = "[email protected]" RETURN p.name`, nil)
The second argument is parameters, and using them is better than building query strings:
result, err := db.Query(
"MATCH (p:Person) WHERE p.email = $email RETURN p.name",
map[string]latticedb.Value{"email": "[email protected]"},
)
Tx.Query runs a query inside a transaction you already have open, so it sees
that transaction's own uncommitted changes.
Traversal
edges, err := tx.GetOutgoingEdges(nodeID)
edges, err := tx.GetIncomingEdges(nodeID)
When you only care about one kind of relationship, filter by type and bound the result, which stops collection early instead of gathering everything and discarding most of it:
edges, err := tx.GetOutgoingEdgesByType(nodeID, "KNOWS", 100)
Property indexes
err := db.CreateNodePropertyIndex("Person", "email")
err = db.View(func(tx *latticedb.Tx) error {
ids, err := tx.FindNodesByLabelProperty("Person", "email", "[email protected]", 10)
// ids -> [1]
return err
})
The limit is required and has to be greater than zero. Looking up a property with no index behind it returns an error rather than quietly scanning. See Property Indexes.
Edges use CreateEdgePropertyIndex and FindEdgesByTypeProperty.
Vector search
results, err := db.VectorSearch(queryVector, latticedb.VectorSearchOptions{
K: 10,
EfSearch: 64,
})
K is how many neighbours you want. EfSearch trades speed for accuracy: higher
values search more of the index and find more of the true nearest neighbours.
Benchmarks shows the measured effect at
different settings.
Store a vector on a node with tx.SetVector(nodeID, "embedding", vector), and
load many at once with tx.BatchInsertVectors. A node has one vector, which
Cypher reads as n.embedding; a key other than "embedding" (or "") returns
ErrorUnsupported, and a vector with NaN or infinite components
ErrorInvalidArg. A K larger than EfSearch widens the search to K.
Full-text search
results, err := db.FTSSearch("Document", "text", "graph database", latticedb.FTSSearchOptions{Limit: 20})
results, err = db.FTSSearchFuzzy("Document", "text", "databse", latticedb.FTSSearchOptions{
Limit: 20,
MaxDistance: 2,
MinTermLength: 4,
})
Declare an index over the property holding the text with
db.CreateNodeFTSIndex(label, property), or db.CreateEdgeFTSIndex(edgeType, property) for a relationship. Writing that property keeps it current,
and searching a label and property with no declared index is an error rather than
an empty result.
Fuzzy search tolerates misspellings. MaxDistance is how many single-character
edits away a word may be, and MinTermLength stops short words being matched
loosely, where one edit can turn any three-letter word into any other.
Durable streams
err = db.Update(func(tx *latticedb.Tx) error {
return tx.PublishStream("events", "signup", "alice joined")
})
records, err := db.ReadStream("events", 0, 10, 0)
for _, r := range records {
fmt.Println(r.Sequence, r.Kind, r.Payload)
// 1 signup alice joined
}
The arguments to ReadStream are the stream name, the sequence you last saw,
how many records you want, and how long to wait in milliseconds when there is
nothing new.
Reading does not record your position, on purpose: if it did, a crash between reading and handling a record would lose it. Save the position yourself once the work is done, inside the transaction that did the work:
err = db.Update(func(tx *latticedb.Tx) error {
// ... handle the records ...
return tx.SetStreamOffset("events", "billing-worker", lastSequence)
})
sequence, exists, err := db.GetStreamOffset("events", "billing-worker")
Changes reads the built-in stream of graph mutations, so you can react to
writes without publishing anything yourself. It returns an error matching
ErrChangesTrimmed when retention has dropped the events after the sequence
you pass, and ErrorUnsupported when the policy is "off"; ChangefeedStatus
reports the policy and the range held, and TrimChangefeed applies the policy
in full now. Each transaction's events are its net effect, in an order that can
be replayed as it comes: the edges it deletes, the nodes that exist after it,
the edges that exist after it, then the nodes it deletes, each group by
ascending id. TrimStream discards records every
consumer has passed; nothing trims automatically.
Errors
var latticeErr *latticedb.Error
if errors.As(err, &latticeErr) {
if latticeErr.Code == latticedb.ErrorLockTimeout {
// somebody else is writing
}
}
Query failures come back as QueryError, which carries where in the query text
the problem is, so you can point at it rather than just reporting that something
was wrong:
_, err := db.Query("RETURN 1/0", nil)
var queryErr *latticedb.QueryError
if errors.As(err, &queryErr) {
fmt.Println(err) // Division by zero: 1 / 0 (DivisionByZero)
fmt.Println(queryErr.Code) // -1
fmt.Println(queryErr.Stage) // 4, QueryErrorStageExecution
fmt.Println(queryErr.DiagnosticCode) // DivisionByZero
fmt.Println(*queryErr.Location) // {1 9 1}
}
Location is nil when the failure does not belong to one place in the text.
Parse and semantic failures have Code ErrorInvalidArg and execution failures
ErrorGeneric, except that a DELETE of a node with relationships has
ErrorHasRelationships and a relationship created to a node deleted earlier in
the query ErrorNotFound, as DeleteNode and CreateEdge report them. A
storage failure under a query has ErrorIO and an allocation failure
ErrorOutOfMemory.
Where to go next
- Quick Start for the same ideas in other languages
- Cypher Overview for the query language
- Transactions and Durability for the one-writer rule
Java
The Java binding (io.latticedb:latticedb, package io.latticedb) wraps the C
API through a small JNI bridge, bindings/java/native/lattice_jni.c. Its surface
mirrors the Go binding. It needs Java 21 or newer.
Installing
The binding is not published to a Maven repository; build it from a checkout. You need JDK 21+, Maven, Zig, and a C compiler for the JNI bridge:
# from the repository root: build the native library
zig build -Doptimize=ReleaseSafe
# build and test the binding; this compiles the JNI bridge into target/native
cd bindings/java
mvn test
The build stages liblattice and the JNI library into target/native. Point a
different build at them with -Dlattice.lib.dir= or -Dlatticedb.native.dir=.
CI builds and tests the Java binding on Linux and macOS; it has not been tested on
Windows.
Opening a database
import io.latticedb.*;
try (Database db = Database.open("graph.lattice",
OpenOptions.defaults().create(true).enableVectors(true).vectorDimensions(128))) {
// ...
}
OpenOptions has create, readOnly, cacheSizeMB (unset by default: the
LATTICE_BUFFER_POOL_MB environment variable if it is set, else 100), pageSize
(default 4096), enableVectors, vectorDimensions (default 128), enableWal
(default true), enableAdjacencyCache (accepted for compatibility; it changes
neither the speed nor the results of queries) and lock (default true), and,
passed through lattice_open_v5, syncMode(SyncMode.FULL | NORMAL),
fullFsync(Boolean), vectorMetric(VectorMetric.COSINE | EUCLIDEAN | DOT_PRODUCT), vectorM(int), vectorEfConstruction(int) and
changefeedRetention(String), all unset by default (null or 0). :memory:
opens an in-memory database, and Database.deserialize(bytes, options) opens one
from the bytes db.serialize() returned, taking the same options through
lattice_deserialize_v5 (create and readOnly are ignored).
enableWal(false) logs nothing. Transactions, rollback, streams and the
changefeed work as with the log, but a commit reaches the file at the next
flush (close(), or when half the page cache holds changes) rather than when it
returns; see
Running without the log.
try (Database db = Database.open("vectors.lattice",
OpenOptions.defaults().create(true).enableVectors(true).vectorDimensions(2)
.vectorMetric(VectorMetric.EUCLIDEAN).syncMode(SyncMode.NORMAL))) {
// ...
}
A database file records its vector index: the dimensions, the metric, M and
ef_construction. A database that has one opens with it whether or not
enableVectors is set, so reopening needs no vector options, also after a
crash. vectorMetric, vectorM and vectorEfConstruction configure a new
index and are fixed once it exists; any of them that is set, and
vectorDimensions when enableVectors(true) is set (it defaults to 128), must
match the file, or opening throws ErrorCode.CONFIG_MISMATCH. vectorDimensions(0)
means the file's dimensions: it opens a database that has an index whatever its
size, and throws ErrorCode.INVALID_ARG where an index would have to be created.
Cosine stores vectors at unit length and returns the cosine distance; Euclidean
returns the L2 distance and dot product the negative dot product, both over
vectors stored as given; results come smallest first.
SyncMode.NORMAL returns from a commit once the operating system has it: it
survives the process being killed, but a power cut or OS crash can lose the most
recent commits. fullFsync(true) makes each sync on macOS ask the drive to
flush its cache. Unset, they defer to the LATTICE_SYNC_MODE and
LATTICE_FULL_FSYNC environment variables, else a full sync without
F_FULLFSYNC; a value you set wins over them.
readOnly(true) on a database that was not closed cleanly recovers it in
memory: the handle sees every committed transaction and nothing is written to
the files. A recovery that needs more than 64 MB plus four times the size of the
log and journal throws ErrorCode.FULL; open the database read-write once to
recover it on disk. A file that a newer release has marked as not writable by
this one opens only with readOnly(true); a writable open throws
ErrorCode.NEEDS_NEWER_WRITER and writes nothing. A file in a format only a
newer release can read throws ErrorCode.VERSION_MISMATCH, read-only or not.
changefeedRetention sets how much of the changefeed the file keeps: "all",
"off", "last:N" or "age:7d"; unset keeps the file's policy (see
The Changefeed). db.changefeedStatus() reports the
policy and the range of events held, db.trimChangefeed() applies the policy
in full now, and db.changes(...) throws ChangesTrimmedException (error code
NOT_FOUND) when retention has dropped the events after the sequence it is
given, and a LatticeException with ErrorCode.UNSUPPORTED when the policy is
"off". Each transaction's events are its net effect, in an order that can be
replayed as it comes: the edges it deletes, the nodes that exist after it, the
edges that exist after it, then the nodes it deletes, each group by ascending
id.
close() is refused with ErrorCode.INVALID_ARG while a transaction or result
from the database is still open. The Database then keeps its handle, so you can
finish what is open and call close() again. A close that fails with
ErrorCode.IO has still closed the database.
db.checkpoint(CheckpointMode.TRUNCATE) (or checkpoint()) folds the log into
the database file now and returns CheckpointStats (pagesFlushed,
durationNs, checkpointLsn, walTruncated); PASSIVE gives way if a changed
page is in use, FULL leaves the log in place. db.setAutoCheckpoint(maxWalFrames, minIntervalMs) sets when commits checkpoint from then on, 0 frames for never.
Without the setter, the LATTICE_AUTO_CHECKPOINT_FRAMES environment variable sets the frame count (default 1000). A larger interval means fewer pauses, each longer, a longer -wal file and more to replay after a crash; see Checkpointing.
Transactions
read and write run a function in a transaction; write commits when the
function returns and rolls back if it throws:
long aliceId = db.write(txn -> {
Node alice = txn.createNode(List.of("Person"), Map.of("name", "Alice"));
Node bob = txn.createNode(List.of("Person"), Map.of("name", "Bob"));
txn.createEdge(alice.id(), bob.id(), "KNOWS");
return alice.id();
});
For manual control, beginRead() and beginWrite() return a Transaction,
which is AutoCloseable: closing it without commit() rolls it back. Only one
write transaction can be open at a time; beginning a second one fails at once with
ErrorCode.LOCK_TIMEOUT. A commit() that throws ErrorCode.TXN_ABORTED has
ended the transaction, and closing or rolling it back afterwards does nothing;
after any other failure it stays open, and closing it rolls it back.
Transaction.deleteNode refuses a node that still has relationships with
ErrorCode.HAS_RELATIONSHIPS and deletes nothing, as Cypher's DELETE does;
detachDeleteNode deletes the node with all its relationships, as
DETACH DELETE does. createEdge throws ErrorCode.NOT_FOUND if either end
does not exist as the transaction sees it.
Queries and search
QueryResult rows = db.query(
"MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN b.name AS name",
Map.of());
rows.rows().forEach(row -> System.out.println(row.get("name")));
db.createNodeFtsIndex("Person", "bio");
List<FTSSearchResult> hits =
db.ftsSearch("Person", "bio", "graph retrieval", FTSSearchOptions.defaults().limit(5));
List<VectorSearchResult> near =
db.vectorSearch(Embedding.hashEmbed("graph retrieval", 128),
VectorSearchOptions.defaults().k(5));
Database.query picks a read or write transaction from the query itself.
Transaction has its own query, ftsSearch, ftsSearchFuzzy and queryVector
for searching inside a transaction, including its uncommitted writes.
A node has one vector, which Cypher reads as n.embedding. setVector(nodeId, key, vector) takes a key that must be "embedding" (or ""); any other key
fails with ErrorCode.UNSUPPORTED, and a vector with NaN or infinite components
with ErrorCode.INVALID_ARG.
Values
| LatticeDB | Java |
|---|---|
| null | null |
| bool | Boolean |
| int | Long |
| float | Double |
| string | String |
| bytes | byte[] |
| vector | float[] |
| list | List<Object> |
| map | Map<String, Object> |
Any Number, List or Map is accepted on input. Long, Integer, Short,
Byte, AtomicInteger, AtomicLong and a BigInteger that fits in 64 bits
are stored as int (a larger BigInteger throws ArithmeticException); every
other Number, BigDecimal included, is stored as float.
Errors
Errors are unchecked. LatticeException carries an ErrorCode (getErrorCode())
and the native code (getNativeCode()). A failed query throws QueryException
(also unchecked) with the error code the call returned, the stage, the
diagnostic code and the source location; when the query has no diagnostic
message, the message is that code's. DATABASE_LOCKED means
another process holds the file; LOCK_TIMEOUT means another write transaction is
open in this one.
For RETURN 1/0, getMessage() is Division by zero: 1 / 0, getCode()
ERROR, getStage() EXECUTION, getDiagnosticCode() DivisionByZero and the
location line 1, column 9, length 1. Parse and semantic failures have
INVALID_ARG and execution failures ERROR, except that a DELETE of a node
with relationships has HAS_RELATIONSHIPS and a relationship created to a node
deleted earlier in the query NOT_FOUND, as deleteNode and createEdge
report them; a storage failure under a query has IO and an allocation failure
OUT_OF_MEMORY. hasLocation() is false when the failure does not belong to
one place in the query.
More
bindings/java/README.md
has the full API overview, and
bindings/java/src/main/java/io/latticedb/examples a runnable knowledge-graph
example (mvn -q compile exec:java@run-example -Dexec.args=/tmp/knowledge.db).
Architecture Overview
This section explains how LatticeDB's storage engine works, from the ground up. Each chapter builds on the previous, showing how simple primitives combine to create a durable, transactional graph database with vector search, full-text search, and local event streams.
LatticeDB is an embedded, single-file property-graph database with vector and BM25 full-text indexes, durable named streams, and a built-in graph changefeed. These chapters explain that substrate: local storage, graph layout, streams, vector search, full-text search, and the query layer over all of them.
The Stack
The Database (src/storage/database.zig) is the orchestrator. It owns every
component below it, stages each transaction's writes in an in-memory overlay, and at
commit time logs that overlay, has the transaction manager write and sync the commit
record, and only then applies the overlay to the stores. The transaction manager
only writes log records; it does not touch the B+Trees or the checkpointer. Dirty
pages reach the database file only in whole flushes that go through the journal.
Chapters
Storage Engine
- Virtual File System - Abstracting file I/O for portability and testing
- Portable Databases - Serializing to bytes, and running with no files at all
- Page Manager - Fixed-size pages, allocation, and checksums
- Buffer Pool - Caching pages in memory with eviction
- B+Tree - Ordered key-value storage with efficient lookups
Durability & Transactions
- Write-Ahead Log - Durability through logging committed changes
- Transaction Manager - Transactions with begin/commit/abort
- Checkpointing - Flushing dirty pages and resetting the log
- Recovery - Redo-only crash recovery from the log
Data Model
- Graph Storage - Nodes, edges, labels, and properties
- Durable Streams - Transactional event records and semantic graph changes
Search Indexes
- Vector Search - HNSW approximate nearest neighbor search
- Full-Text Search - BM25-scored inverted index, per-property declarations, and search as an access path
Query System
- Query Execution - Volcano iterator model, operators, and planning
Design Principles
Direct Page Manipulation
We don't deserialize B+Tree pages into node objects. Searches and in-place inserts read and write bytes directly in the page buffer at calculated offsets, with no intermediate representation of the node.
It is not copy-free end to end. get returns an owned copy of the value
(getBorrowed lends it from the pinned leaf instead), and splits, merges and
redistribution rebuild pages from a temporary list of their entries.
Everything in the File is Pages
The database file is built on fixed-size pages. The size is 4 KB by default and is chosen when the database is created (4096 to 65535 bytes); it is recorded in the file header and cannot change afterwards.
- B+Tree nodes are pages
- Large B+Tree values spill into linked overflow pages
- Vector data and HNSW neighbour lists live in their own page types
- The file header is page 0
- Free pages form a linked list of pages
This uniformity keeps the file simple: one page format and one caching layer for
everything in it. Two files sit beside it. The write-ahead log is a separate
<database>-wal file of page-sized frames, written directly through the VFS rather
than through the buffer pool. The flush journal, <database>-journal, holds a copy
of the pages a flush is writing, so a crash part way through can be finished; it is
empty between flushes and deleted at a clean close.
Durability Through WAL
A transaction's changes are held in memory until commit. At commit they are logged, the commit record is forced to disk, and only then are they applied:
- Commit = commit record is on disk (fast, sequential write)
- Data pages are written later, all dirty pages at once, through the journal, so the file moves from one whole image to the next
- Crash recovery re-executes committed log records onto that image
Simple Concurrency Model
A database allows one read-write transaction at a time; a second one is refused rather than queued. The C API also serialises the calls on a database handle behind one mutex. Below that, each buffer-pool frame has a reader-writer latch, which protects a page while it is being read or modified. There are no complex lock hierarchies - simplicity over maximum concurrency.
Virtual File System (VFS)
What It Is
The Virtual File System is an abstraction layer over file I/O operations. Instead of calling OS functions directly, all file operations go through a VFS interface.
Why We Need It
1. Databases that are not files
The most visible thing this buys is databases with nothing underneath them. Open
:memory: and the engine runs against a filesystem held in RAM:
Everything above the interface is unchanged. The B+Tree, the buffer pool, the write-ahead log, and recovery all run exactly as they do against a disk, because none of them knows the difference. That is why in-memory support was a new backend rather than a second path through the engine.
Tests get the same benefit, and run without touching a disk.
2. Portability
Different operating systems have different file APIs:
- Linux and macOS:
pread,pwrite,fsync - Windows:
ReadFile,WriteFile,FlushFileBuffers
The rest of the database only sees the VFS interface. There is one file-backed
implementation, PosixVfs, despite its name: it is written against Zig's
standard-library file API (positioned reads and writes, sync, locks) rather than
raw system calls, so the per-platform differences live in Zig's standard library.
defaultVfs returns it unconditionally.
3. A Seam for Failure Injection
A backend that records every write and sync can be dropped in behind the same
interface to test what a power cut does. FaultVfs (src/storage/fault_vfs.zig)
is that backend: an in-memory filesystem that keeps a trace of every create,
delete, write, truncate, file sync and directory sync, and a disk model that
replays part of the trace and cuts the power, losing, reordering or tearing what
was not synced. Database.openWithVfs opens a database on any Vfs and treats it
as a disk, journal and configured buffer pool included, which :memory: does not.
The power-loss tests drive the engine through it; see
Running Tests.
The same seam carries read-only recovery. OverlayVfs
(src/storage/overlay_vfs.zig) opens the files beneath it for reading only and
keeps every write in memory, in 4 KB blocks over them, up to a budget. A read-only
open of a crashed database runs recovery on it, so the handle sees every committed
transaction and the files are not touched (see
Recovery).
The older crash tests in tests/crash/ simulate a crash differently: some copy the
database file and its log while the handle is still open, which is what a killed
process leaves, and open the copy; others reset the database file to its header
page, leave the log in place, and check that reopening replays the committed
transactions; others build the state a crash part way through a flush leaves.
The Interface
File Operations
pub const File = struct {
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
read: fn(ptr, offset: u64, buf: []u8) VfsError!usize,
write: fn(ptr, offset: u64, data: []const u8) VfsError!void,
sync: fn(ptr) VfsError!void,
truncate: fn(ptr, size: u64) VfsError!void,
size: fn(ptr) VfsError!u64,
close: fn(ptr) void,
lock: fn(ptr, mode: LockMode) VfsError!void,
tryLock: fn(ptr, mode: LockMode) VfsError!bool,
unlock: fn(ptr) void,
};
// Convenience methods that call vtable
pub fn read(self: File, offset: u64, buf: []u8) !usize {
return self.vtable.read(self.ptr, offset, buf);
}
// ... etc
};
VFS Operations
pub const Vfs = struct {
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
open: fn(ptr, path: []const u8, flags: OpenFlags) VfsError!File,
delete: fn(ptr, path: []const u8) VfsError!void,
exists: fn(ptr, path: []const u8) bool,
// Optional: make a file's directory entry durable. PosixVfs syncs the
// parent directory; a backend without directories leaves it null.
syncParentDir: ?fn(ptr, path: []const u8) void = null,
};
};
The journal, a newly created database and a newly created log reach the directory
sync through the Vfs in use, so a power-loss test can see it.
Open Flags
pub const OpenFlags = struct {
read: bool = true, // Open for reading
write: bool = false, // Open for writing
create: bool = false, // Create if doesn't exist
exclusive: bool = false, // Fail if exists (with create)
truncate: bool = false, // Truncate file to zero length
};
Locks
LockMode is shared or exclusive. The page manager uses tryLock when it
opens a database: a read-write open takes the file exclusively and a read-only
open shares it, and a conflicting holder makes the open fail with
DatabaseLocked instead of waiting.
Key Operations
Positioned Read/Write
Unlike streaming I/O, we use positioned reads and writes:
// Read 4096 bytes starting at byte offset 8192
const bytes_read = try file.read(8192, buffer[0..4096]);
// Write 4096 bytes starting at byte offset 8192
try file.write(8192, data[0..4096]);
This maps directly to page-based access (shown for the default 4096-byte page):
- Page 0 is at offset 0
- Page 1 is at offset 4096
- Page N is at offset N * page_size
Sync (fsync)
The most important operation for durability:
try file.sync();
This asks the operating system to push all pending writes for the file to the storage device. Without it, data might sit in OS buffers and be lost on power failure.
How far the flush goes depends on the platform. sync is Zig's standard
File.sync, which is plain fsync on Linux and macOS and NtFlushBuffersFile on
Windows. On macOS plain fsync hands the data to the drive but does not force the
drive's own write cache out, so a power loss there can still lose writes the drive
had acknowledged. Setting full_fsync in the database configuration, or
LATTICE_FULL_FSYNC=1 in the environment, makes every sync on macOS use
fcntl(F_FULLFSYNC) instead, which does ask the drive to flush; a filesystem that
does not support it falls back to fsync. It is off by default because each sync
becomes markedly slower. The setting has no effect on other platforms.
fsync on a file covers its contents, not the directory entry that names it. When a
database is created, its parent directory is synced once after the new database
file and log are, so a power cut right after creation cannot leave complete files
that are missing from their directory (not on Windows, where this is skipped). The
flush journal, <database>-journal, is created at every read-write open and removed
at a clean close, so each session's journal is a new name in the directory: the
first journal write of a session syncs the directory before it returns, which is
before any page is written in place. A session that never flushes pays nothing. The
log is a new name too when an existing database is opened without one, as after a
backup is put back without its log: creating it syncs the new file and its
directory, once per file, so a power cut cannot take the log's name, and the
commits in it, with it. These directory syncs go through the Vfs in use.
The File Implementation
PosixVfs opens files through Zig's standard file API. compat.fs is a thin
shim in src/compat.zig that papers over differences between Zig versions. The
snippets in this section are simplified from src/storage/vfs.zig:
pub const PosixVfs = struct {
allocator: Allocator,
pub fn openFile(self: *Self, path: []const u8, flags: OpenFlags) VfsError!File {
const cwd = compat.fs.cwd();
const handle = if (flags.create)
cwd.createFile(path, .{ .read = flags.read, .truncate = flags.truncate,
.exclusive = flags.exclusive })
else
cwd.openFile(path, .{ .mode = if (flags.write) .read_write else .read_only });
// ... map std errors to VfsError, wrap the handle in a PosixFile
}
};
(The real openFile also opens an existing file instead of re-creating it when
create is set without truncate or exclusive.)
Read Implementation
Positioned reads, so there is no shared file cursor to seek:
pub fn readAt(self: *PosixFile, offset: u64, buf: []u8) VfsError!usize {
return self.handle.preadAll(buf, offset) catch |err| switch (err) {
error.InputOutput => VfsError.IoError,
else => VfsError.Unexpected,
};
}
Write Implementation
Positioned writes. A handle opened without write refuses them:
pub fn writeAt(self: *PosixFile, offset: u64, data: []const u8) VfsError!void {
if (!self.writable) return VfsError.NotOpenForWriting;
self.handle.pwriteAll(data, offset) catch |err| return switch (err) {
error.InputOutput => VfsError.IoError,
error.NoSpaceLeft => VfsError.DiskFull,
else => VfsError.Unexpected,
};
}
Sync Implementation
pub fn syncFile(self: *PosixFile) VfsError!void {
if (builtin.os.tag.isDarwin() and self.full_fsync) {
if (std.c.fcntl(self.handle.handle(), std.c.F.FULLFSYNC, 0) != -1) return;
}
self.handle.sync() catch |err| return switch (err) {
error.InputOutput => VfsError.IoError,
else => VfsError.Unexpected,
};
}
The Memory Implementation
MemoryVfs holds files in RAM. It backs :memory: databases and databases
opened from bytes, and it is a real backend rather than a testing convenience.
Files are chunks, not one buffer
A file is a list of page-sized pieces:
const Chunk = union(enum) {
borrowed: []const u8,
owned: []u8,
};
The obvious implementation is one growing buffer, and it is the wrong one. A growing buffer has to be reallocated as the file extends, and a reallocation moves every byte to a new address. Anything holding a slice from before that moment is left pointing at freed memory.
That matters because lending slices is the point. A database opened from a caller's bytes can point at them instead of copying, which halves what loading costs. That is only possible if addresses are stable, so chunks came first and the lending was built on top.
Copy-on-write
A chunk either owns its bytes or borrows them from whoever handed them over. Writing to a borrowed chunk copies it first, at page granularity.
So a database loaded from a blob starts out borrowing all of itself, and only the pages actually modified become private copies. Reading a database and changing a little of it keeps one copy of nearly all of it, and the caller's buffer is never modified.
Locking is a no-op
Every lock succeeds. A lock exists to keep a second process off a database, and no other process can reach memory this one owns. That is a decision rather than an omission: file-backed databases take a real lock and refuse a conflicting opener, and this backend declines to pretend there is anything to exclude.
What it costs
Peak memory is the database plus the buffer pool, and the pool is a small constant here — see Buffer Pool for why a cache barely matters when the storage underneath it is already RAM.
100 nodes | database 240 KB | pool 256 KB | 2.62x
4000 nodes | database 7416 KB | pool 256 KB | 1.04x
10000 nodes | database 18432 KB | pool 256 KB | 1.01x
The overhead at small sizes is mostly the write-ahead log, which is a second file in the same backend. It shrinks as automatic checkpointing truncates it, which is why the ratio falls rather than rises as the database grows.
An in-memory database has no flush journal: with no file behind it there is no crash for a journal to survive.
The log stays enabled in memory, incidentally. Turning it off with
enable_wal = false is allowed and changes less than it looks: transactions do not
depend on the log, so rollback and all-or-nothing queries work the same, and an
in-memory database has no crash for the log to protect against anyway.
Error Handling
VFS operations can fail in various ways:
pub const VfsError = error{
FileNotFound, // Path doesn't exist
PermissionDenied, // No access rights
DiskFull, // No space left
IoError, // Hardware failure
FileLocked, // Another process has it
InvalidPath, // Bad path string
AlreadyExists, // Exclusive create failed
NotOpenForWriting, // Write or truncate on a read-only handle
Unexpected, // Anything not mapped above
};
Each PosixFile method translates the standard library's errors itself, as in the
snippets above: FileNotFound and PathAlreadyExists keep their meaning,
AccessDenied becomes PermissionDenied, NoSpaceLeft becomes DiskFull,
InputOutput becomes IoError, and anything else becomes IoError or
Unexpected. There is no single mapping table.
Usage Pattern
// Create VFS
var posix_vfs = PosixVfs.init(allocator);
const vfs = posix_vfs.vfs(); // Get interface
// Open file
const file = try vfs.open("database.db", .{
.read = true,
.write = true,
.create = true,
});
defer file.close();
// Read page 5
var buf: [4096]u8 = undefined;
_ = try file.read(5 * 4096, &buf);
// Modify and write back
buf[0] = 42;
try file.write(5 * 4096, &buf);
// Ensure durability
try file.sync();
Why Not Just Use std.fs?
PosixVfs is Zig's standard library underneath, including its positioned reads
and writes. The layer exists for what the standard library does not give:
- A swappable implementation - The vtable is what lets
MemoryVfsstand in for the disk - Database-specific errors - One small error set instead of every std error
- One place to absorb std changes - File API changes between Zig versions are
handled in
compat.zigand the VFS, not throughout the engine
The VFS is a thin layer, but it gives us control where we need it.
Portable Databases
What It Is
A LatticeDB database can be handed around as a block of bytes, and it can run with no files behind it at all. Those are two features and one idea: a database is a single file, and the engine reaches that file through an interface it does not control.
This chapter is about how that works and why it was built this way.
Why one file matters
The same request — "let me keep many small databases in object storage and pull one down when I need it" — has been made of several embedded graph databases. For most of them it is hard, because a database is a catalog, a set of index files, a data file, and a log. Serializing means inventing a container format for all of them and keeping it in step with the engine as both change.
Here, serializing a database is reading its file. That is not a clever trick and there is no format to maintain; it falls out of the storage layout. It is the clearest practical argument for the single-file design, which otherwise looks like a mere convenience.
Serializing
serialize does two things:
_ = try self.quiesceForCopy(); // fold everything pending into the file
// ...then read the file
The first step is the interesting one. At any moment part of a database lives somewhere other than its file: dirty pages sit in the buffer pool, committed changes sit in the write-ahead log, and the vector index keeps state in memory until asked to persist it. Copying the file without settling all of that gives you something that opens and is then subtly wrong.
So quiescing persists the vector index, writes the tree roots, and runs a .full
checkpoint, which flushes dirty pages into the file and leaves the log alone. The
result is a file that needs no log beside it — which is exactly what somebody
uploading to a bucket wants, since they are going to upload one object.
backup performs the same step, and the two share it rather than keeping separate
copies that would drift apart.
Why it refuses during a transaction
serialize returns an error if a transaction is open. A copy taken while writes
land underneath it is torn in a way nothing downstream can detect: the bytes are
individually valid, the pages pass their checksums, and the structure is
inconsistent. Failing at the point of the mistake is the only place the problem is
visible.
Why deserialize validates
Opening a zero-length file is how a database gets created. So bytes that are empty
or truncated, written out and opened, would quietly become a brand new empty
database — and report success. deserialize therefore checks the length and magic
number before it does anything with the bytes.
This matters because the obvious failure in this workflow is a partial download.
Running without files
Every byte the storage layer moves goes through the VFS interface.
Swapping the implementation is therefore enough to give a database with nothing
underneath it, and :memory: does exactly that.
Nothing above the interface changes. The B+Tree, buffer pool, log, and recovery all run as they always do, because none of them can tell the difference. That sameness is the entire reason the feature was cheap, and it is worth protecting: the tempting optimizations in this area are mostly ones that would make the in-memory path structurally different, and each would buy a little memory in exchange for a second code path to keep correct.
Why :memory: is a path and not an option
Every binding already accepts a path string and passes it through to the C API. A magic path therefore works everywhere the moment the engine recognises it — Python, TypeScript, Go, C, and the command line — with no binding changes at all.
An option would have meant a new field, so a new versioned C struct, so a new entry point, so FFI declarations and public option types and documentation in four bindings, for exactly the same capability. The cost of the magic string is that it is a magic string.
Opening :memory: also implies creating it, since there is never a previous
in-memory database to find. Requiring create would have been a formality every
caller had to remember, which would have undone the point.
Why the log stays on
Turning the write-ahead log off in memory looks free. A log exists so a crash cannot lose committed data, and a process holding the only copy of a database in its own heap loses everything when it dies regardless.
Until 0.17.0 that reasoning did not survive contact with the code: transactions
were built on the log, so a database without one returned
TransactionsNotEnabled from beginTransaction, with no rollback and no
multi-statement atomicity. That was a much larger hole than the allocations it
saved, so the log stayed on in memory as on disk. A database without a log now
has transactions (see
Running without the log),
so enable_wal = false is a fair choice for an in-memory database; the default
stays the same for both kinds.
The log becomes a second file in the same memory backend, bounded by automatic checkpointing.
Why locks always succeed
A file-backed database takes a lock and refuses a conflicting opener, because two processes writing one file corrupt it. No other process can reach memory this one owns, so there is nothing to exclude, and every lock request in the memory backend succeeds.
That is a decision rather than an omission, which is worth stating plainly given the file-backed behaviour is the opposite.
What it costs
100 nodes | database 240 KB | pool 256 KB | total 628 KB | 2.62x
1000 nodes | database 1896 KB | pool 256 KB | total 3412 KB | 1.80x
4000 nodes | database 7416 KB | pool 256 KB | total 7676 KB | 1.04x
10000 nodes | database 18432 KB | pool 256 KB | total 18692 KB | 1.01x
Two things are worth reading out of that table.
The buffer pool is a small constant rather than a fraction of the data, because a cache stops earning its keep when the storage underneath it is already RAM. See Buffer Pool for the measurement behind that.
And the overhead at small sizes is not duplication, it is the write-ahead log living as a second file in the same backend. That is why the ratio falls as the database grows rather than rising: checkpointing truncates the log, and the fixed costs stop mattering.
Loading without a second copy
By default deserialize copies the caller's bytes. It can instead point at them,
which halves what loading costs.
The memory backend stores a file as page-sized chunks, and a chunk either owns its bytes or borrows them:
const Chunk = union(enum) {
borrowed: []const u8,
owned: []u8,
};
Writing to a borrowed chunk copies it first. A database loaded this way starts out borrowing all of itself and only the pages actually modified become private, so reading a database and editing a little of it keeps one copy of nearly all of it. The caller's buffer is never written to.
Why chunks, not one buffer
One growing buffer is the obvious layout and the wrong one. Growing it means reallocating, reallocating moves every byte, and anything holding a slice from before that moment is left pointing at freed memory. Lending slices is the whole point, so stable addresses had to come first.
Why some languages cannot borrow
Python and TypeScript can: the binding keeps a reference to the buffer on the wrapper object, and the collector cannot take it.
Go cannot, and this is a language rule rather than a gap in the binding. Its own
documentation says C code may not keep a copy of a Go pointer after the call
returns, and that slices cannot be pinned to work around it. Java cannot either,
for a different reason: pinning a byte[] for the lifetime of a database would
hold up the collector for exactly that long.
So there are two entry points and each language uses the one its rules allow. The copy happens inside the engine, so the bindings that must copy do not implement anything themselves.
What was considered and rejected
Frames borrowing from the memory backend. The buffer pool could point at pages in the memory backend for clean pages and copy on first write. This was the original plan for reducing duplication, and the measurements above closed it: the pool is a constant 256 KB, so there is nothing material left to save, and the change would add a new state — "this frame might not own its bytes" — to the structure that pinning, latching, and dirty tracking all run through, on every read and write in the engine.
Making the pool the storage. For an in-memory database the pool could be the file, with nothing ever evicted since there is nowhere to evict to. That gives exactly one copy by construction. It is rejected because it makes the in-memory path structurally different from the file path, and that sameness is why this works at all.
Related
- Virtual File System — the interface all of this rests on
- Buffer Pool — why the cache is sized differently here
- Backup and Replication — how to use it
Page Manager
What It Is
The Page Manager handles the lowest level of database storage: fixed-size pages. It manages the database file structure, page allocation/deallocation, and data integrity through checksums.
Why Fixed-Size Pages?
Simplicity
Every piece of data in the database file lives in a fixed-size page. The size is
4096 bytes by default and is chosen when the database is created (anything from
4096 to 65535 bytes, through page_size in the open options or the C API). It is
stored in the file header and fixed for the life of the file. This uniformity
simplifies everything:
To read page N: offset = N * page_size
Alignment with Hardware
- SSD pages: Modern SSDs have 4KB or 8KB internal pages
- OS pages: Most operating systems use 4KB virtual memory pages
- Disk sectors: Traditional HDDs use 512B or 4KB sectors
4KB aligns well with all of these, which in general enables:
- Direct I/O (bypassing OS cache)
- Atomic writes on some hardware
- Efficient memory mapping
LatticeDB uses neither direct I/O nor memory mapping today; pages are read and written through the VFS into the buffer pool.
Efficient Caching
Fixed-size pages make the buffer pool trivial - every frame is the same size, no fragmentation.
File Structure
Page 0: File Header
The first page is special - it contains metadata about the database. It is the
FileHeader extern struct from src/storage/page.zig (232 bytes, all integers
little-endian); the rest of page 0 is zero.
| Offset | Size | Field |
|---|---|---|
| 0–3 | 4 B | Magic number — 0x4C544442 ("LTDB") |
| 4–5 | 2 B | Format version (currently 4) |
| 6–7 | 2 B | Minimum reader version |
| 8–11 | 4 B | Page size |
| 12–15 | 4 B | Flags |
| 16–23 | 8 B | Node count |
| 24–31 | 8 B | Edge count |
| 32–35 | 4 B | Legacy B+Tree root page (unused, kept for compatibility) |
| 36–39 | 4 B | Vector segment page |
| 40–43 | 4 B | FTS segment page |
| 44–47 | 4 B | Freelist head page |
| 48–51 | 4 B | Schema page |
| 52–115 | 64 B | tree_roots[16] — root page of each B+Tree |
| 116–119 | 4 B | Padding |
| 120–127 | 8 B | WAL frame count |
| 128–131 | 4 B | checkpoint_seq — how many times the WAL has been reset |
| 132–135 | 4 B | Reserved |
| 136–151 | 16 B | File UUID |
| 152–159 | 8 B | Created timestamp |
| 160–167 | 8 B | Modified timestamp |
| 168–199 | 32 B | Application id |
The first 200 bytes are the header 0.16.0 knows. Format 4 added the fields after them, behind a magic number of their own:
| Offset | Size | Field |
|---|---|---|
| 200–203 | 4 B | Extension magic — 0x3458544C ("LTX4"); anything else means the fields below are absent |
| 204–205 | 2 B | Vector dimensions; 0 when no vector index is recorded |
| 206 | 1 B | Vector metric: 1 cosine, 2 euclidean, 3 dot product |
| 207 | 1 B | Reserved |
| 208–215 | 8 B | next_node_id, the id the next node created gets; 0 when absent |
| 216–217 | 2 B | HNSW m, connections per node |
| 218–219 | 2 B | HNSW m_max0, connections on layer 0 (twice m) |
| 220–221 | 2 B | HNSW ef_construction |
| 222–223 | 2 B | Minimum writer version; 0 means no restriction |
| 224–225 | 2 B | Minimum reader reasons: what raised the minimum reader version (see below) |
| 226–231 | 6 B | Reserved |
0.16.0 copies only its own 200 bytes and writes the rest of page 0 as zeros, so after 0.16.0 has written a file the extension magic no longer matches and the fields are ignored: the next open by this release finds the node id counter with one scan of the node tree, reads the vector configuration from the vector pages, and writes both back. That lets a file go back and forth between the two releases without either one trusting a value the other did not keep up to date, for as long as 0.16.0 may open it at all: see Format Versions for what keeps it out.
Key fields:
- Magic number: Identifies this as a Lattice database file. Opening a random file will fail fast.
- Format version, minimum reader and minimum writer version: see Format Versions below
- Freelist head: Points to the first free page (for allocation)
- Tree roots: The root page of each of the engine's B+Trees (nodes, edges,
labels, symbols, FTS, HNSW, streams, property indexes), indexed by
TreeIndex. The database copies the current roots into the in-memory header before every flush, so the file's header always names the roots of the pages written with it. - Checkpoint sequence: Incremented by every checkpoint that truncates the WAL, so anything following the log can tell frame 40 of one run from frame 40 of the next
- File UUID: Unique identifier, used to match WAL files
- Node id counter: written with every flush, in the same header image as the node tree pages it describes, so opening needs no scan and a committed node's id is never handed out again, even after the node is deleted. Ids handed out by a transaction that rolled back, or that had not committed when the process died, can be handed out again.
- Vector index configuration: dimensions, metric and HNSW parameters, recorded
from the moment the index exists. A database that has a vector index opens with
it whatever the open options say, and options that contradict it are refused
with
VectorConfigMismatchbefore anything is read. An index added to an existing file is written to the header at that open, so the log can never hold vector records for an index the file does not record.
The header page is written raw: unlike every other page it has no page header and no checksum. Between flushes it changes only in memory; it reaches the file as the first page of each journaled flush (see Buffer Pool).
Data Pages
Every other page starts with a common header:
| Offset | Size | Field |
|---|---|---|
| 0 | 1 B | Page type — btree_internal, btree_leaf, and so on |
| 1 | 1 B | Flags |
| 2–3 | 2 B | Reserved |
| 4–7 | 4 B | Checksum — CRC32C of bytes 8 to the end of the page |
| 8 → | page size − 8 | Page-specific data |
Page Types
pub const PageType = enum(u8) {
free = 0x00, // Unallocated, on freelist
btree_internal = 0x01, // B+Tree internal node
btree_leaf = 0x02, // B+Tree leaf node
overflow = 0x03, // Large value overflow
vector_data = 0x04, // Stored vectors
hnsw_layer = 0x05, // HNSW neighbour lists
fts_dictionary = 0x06,
fts_posting = 0x07, // FTS posting lists
freelist = 0x08,
schema = 0x09,
segment_directory = 0x0A,
};
Page Allocation
The Freelist
Free pages are linked together in a freelist:
Allocating a Page
The snippets in this section are simplified from src/storage/page_manager.zig:
allocPage and allocZeroedPage stand in for the page-sized, 4096-aligned buffer
the real code allocates (and frees) inline, and error mapping is left out.
pub fn allocatePage(self: *Self) !PageId {
if (self.read_only) return error.PermissionDenied;
// 1. A page freed since the last flush: the file has not heard it was freed
if (self.deferred_frees.pop()) |page_id| return page_id;
// 2. The freelist
if (self.header.freelist_page != NULL_PAGE) {
return self.allocateFromFreelist();
}
// 3. Extend the file with a zeroed page (type free, checksum 0). This only
// makes the file longer; nothing in the file refers to the page until
// a flush writes the pages that use it.
const page_id = self.pageCount();
const zeros = try allocZeroedPage(self.page_size);
const header: *PageHeader = @ptrCast(zeros.ptr);
header.* = PageHeader.init(.free);
try self.file.write(self.pageOffset(page_id), zeros);
return page_id;
}
The file header is not rewritten here. A file whose last page was cut short by a crash during such an extension is still opened; the partial page is not counted.
Allocating from Freelist
fn allocateFromFreelist(self: *Self) !PageId {
const page_id = self.header.freelist_page;
// The head must be inside the file, read back with a valid checksum, and be
// a free page. Otherwise the freelist is dropped and the page comes from the
// end of the file instead.
if (page_id >= self.pageCount()) return self.dropFreelistAndExtend();
const buf = try allocPage(self.page_size);
self.readPage(page_id, buf) catch |err| switch (err) {
error.ChecksumMismatch => return self.dropFreelistAndExtend(),
else => return err,
};
if (pageType(buf) != .free) return self.dropFreelistAndExtend();
// Next pointer is stored after the 8-byte header; one that points at the
// page itself or past the end of the file ends the list
var next_free = std.mem.readInt(u32, buf[8..12], .little);
if (next_free == page_id or next_free >= self.pageCount()) next_free = NULL_PAGE;
// Update the freelist head, in memory; the next flush writes the header
self.header.freelist_page = next_free;
self.header_dirty = true;
return page_id;
}
Checking the head matters because a stale or damaged header could otherwise hand
out a live page, giving it two owners. Dropping the list leaks the pages on it
(lattice compact rebuilds the list from page types) rather than corrupt a tree.
Freeing a Page
Freeing writes nothing to the file. The page joins a list of deferred frees:
pub fn freePage(self: *Self, page_id: PageId) !void {
// Can't free the header page, a page past the end of the file, the current
// freelist head, or a page already freed since the last flush
if (page_id == 0 or page_id >= self.pageCount()) return error.InvalidPageId;
if (page_id == self.header.freelist_page) return error.InvalidPageId;
if (self.deferred_free_set.contains(page_id)) return error.InvalidPageId;
try self.deferred_free_set.put(page_id, {});
try self.deferred_frees.append(page_id);
}
The buffer pool gives the freed page a blank free-page image in memory, so whoever is handed it next finds a free page, not what its last owner left. At the next flush the deferred pages are formatted as freelist pages, each linking to the next and the last to the current head, and written with the other dirty pages and the header. Writing a freelist link into a page the moment it was freed was the other way a page could reach the file on its own, over a page the file's image still used; that no longer happens.
The freelist is LIFO (a stack): the most recently freed pages are handed out first.
Physical Tail Reclamation
Normal allocation reuses freelist pages without moving live pages, so file size
does not need to grow again after deletes. To return space to the operating
system, lattice compact <path> flushes and evicts the buffer pool, rebuilds
the retained freelist, persists a head that excludes tail pages, and truncates
the contiguous free run at physical EOF. Live pages and logical IDs never move.
The header is synced before truncation. A crash between those steps can leave temporarily unreclaimed free pages, but cannot leave a freelist pointer beyond the new end of the file.
Checksums
Every page except the header page carries a CRC32C (Castagnoli) checksum in bytes 4–7 of its page header. It covers bytes 8 to the end of the page — everything after the page header — so the whole header is outside it: the page type and flags in bytes 0–1, the reserved bytes 2–3, and the checksum itself.
Why Checksums?
- Detect corruption: Hardware failures, cosmic rays, bugs
- Detect torn writes: Partial page writes from crashes
- Validate reads: Catch errors before using bad data
0.16.0 extended a file with pages of zeros, checksum 0 included, and a crash can
leave such a page behind. A file this release creates says in its header that it
never does (flag SEALED_PAGES, 0x20): the free page it extends the file with is
written with its checksum, so every page in the file carries one, and any page whose
checksum does not match fails verification, a page of zeros included. A B+Tree or
overflow pointer to a page that a fault turned to zeros is then an error, not an
empty free page.
A file without the flag, one that 0.16.0 created, keeps the older rule: a stored checksum of 0 is accepted only for a page that is exactly what 0.16.0's allocation wrote, the free page type and every other byte zero. Any other page with a checksum of 0 fails, which catches damage that zeroed the first sector of a written page. A page that is entirely zero still passes there. 0.16.0 copies the header's flags when it writes the header but extends the file with unsealed pages, so the flag counts only while the format-4 header fields are present, and a read-write open that finds them gone clears it. Only a new file gets the flag: no operation rewrites every page of an existing one, so an older file gains it by export and import into a new database.
Scans over every page, which meet pages that nothing refers to (lattice check,
truncating the free tail in compact), still take an all-zero page for a blank one
(readPageForScan); lattice check counts them. The header page has no checksum
at all (the journal checksums its copy of it during a flush).
Checksum Calculation
pub fn calculateChecksum(data: []const u8) u32 {
return crc32c.hash(data); // CRC32C (Castagnoli)
}
src/storage/crc32c.zig uses the CPU's CRC-32C instruction where there is one
(SSE4.2 on x86_64, the CRC extension on aarch64), chosen at run time because release
binaries are built for baseline CPUs, and a slicing-by-8 table walk otherwise. The
result is bit-identical to the byte-at-a-time std.hash.crc.Crc32Iscsi that earlier
releases used, so files and logs verify in both directions.
The buffer pool stamps the checksum when it seals a page for a flush, so the same
bytes go to the journal and then in place. writePage, below, does the same for
the page manager used on its own.
Writing with Checksum
pub fn writePage(self: *Self, page_id: PageId, buf: []u8) !void {
if (self.read_only) return error.PermissionDenied;
if (buf.len != self.page_size) return error.InvalidPageId;
if (page_id == 0) return error.InvalidPageId; // the header is not a data page
// Calculate checksum of everything after the 8-byte page header
const header: *PageHeader = @ptrCast(@alignCast(buf.ptr));
header.checksum = calculateChecksum(buf[8..]);
// Write to disk
try self.file.write(self.pageOffset(page_id), buf);
}
Reading with Verification
pub fn readPage(self: *Self, page_id: PageId, buf: []u8) !void {
try self.readPageRaw(page_id, buf); // reads page_size bytes at pageOffset(page_id)
// Verify checksum
const header: *const PageHeader = @ptrCast(@alignCast(buf.ptr));
const expected = calculateChecksum(buf[8..]);
// In a file whose pages are all sealed, any mismatch is damage. Otherwise
// one passes only for a page as 0.16.0's allocation wrote it: type free,
// every other byte zero (checksum 0 included)
if (header.checksum != expected) {
if (self.header.pagesSealed() or !isUnsealedFreePage(buf)) {
return error.ChecksumMismatch;
}
}
}
The extra check runs only when the checksum does not match, so a read that verifies costs what it always did. Every page except one freshly allocated by 0.16.0 has been sealed with its checksum by every release, and only files this release creates refuse an unsealed one, so no file that opened before is refused.
Read-Only Mode
The Page Manager supports opening databases read-only:
var pm = try PageManager.init(allocator, vfs, "db.file", .{
.read_only = true,
});
// This fails:
_ = try pm.allocatePage(); // error.PermissionDenied
try pm.writePage(1, &buf); // error.PermissionDenied
Useful for:
- Backup tools
- Read replicas
- Forensic analysis
Finishing an Interrupted Flush
When it opens a file, before reading the header, the page manager looks for
<database>-journal. If a flush was interrupted, the journal holds every page it
was writing; a complete journal for this database is written in place and synced,
and an incomplete one is discarded. A read-only open of the database applies the
journal to an in-memory overlay of the file instead, and writes nothing. See
Recovery.
File Locking
The page manager locks the file before it reads anything. A read-write open takes
an exclusive lock and a read-only open takes a shared one, using tryLock, so a
conflicting holder makes the open fail at once with DatabaseLocked rather than
wait. A reader is therefore refused while another process has the database open
for writing. The lock option turns this off for filesystems where locking does
not work; it does not make cross-process sharing safe.
Format Versions
The header has two gates for older releases:
- Minimum reader version. A release whose format version is lower may not open
the file at all; the page manager refuses it with
VersionTooNew(LATTICE_ERROR_VERSION_MISMATCH, -11, through the C API; the CLI says the file was written by a newer LatticeDB). A log whose version is newer than this release knows is refused the same way. - Minimum writer version. A release whose format version is lower may open the
file read-only but not for writing. A writable open is refused with
NeedsNewerWriter(LATTICE_ERROR_NEEDS_NEWER_WRITER) before anything is written; a read-only open works. 0 means no restriction.
This release is format 4. A read-write open of an older file sets the format version to 4 and writes the format-4 fields; it never lowers either gate, and raises the minimum writer version to 4. The minimum reader version stays 3, so 0.16.0 can still open the file, until the file holds something 0.16.0 would misread rather than refuse. Then it becomes 4, and the bit for the reason is set in the minimum reader reasons:
| Bit | Reason | Raised when |
|---|---|---|
0x01 | vector index settings | the vector index uses a metric other than cosine or an m other than 16 (ef_construction only affects how new vectors are inserted, so it does not count) |
0x02 | ordered property index | a property index is declared; 0.16.0 would take its keys for digests and find nothing |
0x04 | changefeed events | a commit records its first changefeed event; 0.16.0's changes() would skip events in this release's format without an error, and its trim would leave them |
0x08 | full-text positions | a full-text index that stores word positions takes its first document; 0.16.0 would append posting entries without a position count and garble the page |
Opening never raises it: a read-only open changes nothing, and a read-write open that
writes nothing leaves the version at 3. A changefeed with retention off records no
events, so it does not raise it either. Nothing lowers it again, not even a trim that
drops every event, because the file cannot tell that no copy of an event survives in
a log or a backup taken in between. lattice info and lattice check print the
version and the reasons.
The changefeed's raise is the one that happens in the middle of ordinary writing, so it is written ahead of everything else: the commit that stores the first event writes the two fields in place in page 0 and syncs the file before it logs the commit, or, without a log, before it writes a page. Only those two fields are written, because the header in memory runs ahead of the pages in the file (tree roots, the freelist) until the next flush; that flush writes the whole header with the same values. So every state a crash can leave holds either no durable event or a header that already refuses 0.16.0. Replaying a log's changefeed records raises the version again in the header the replay's flushes write, in case a stale journal put an older header back. The other three raise the header in memory, and it reaches the file no later than what they describe: in the same flush for a vector index and for a full-text index's first postings, and before the first entry for a property index.
0.16.0 predates the minimum writer version: it opens and writes a file that asks for a newer writer, and zeroes the field as it writes the header. So a later feature that must keep 0.16.0 from writing a file has to raise the minimum reader version as well.
Error Handling
pub const PageManagerError = error{
InvalidHeader, // File header is malformed
InvalidMagic, // Not a Lattice database file
InvalidPageSize, // Page size outside 4096..65535
VersionTooNew, // A newer reader is needed (min_reader_version)
WriterVersionTooNew, // Writable open of a file that needs a newer writer
ChecksumMismatch, // Data corruption detected
InvalidPageId, // Page ID out of range
PageNotAllocated, // Accessing unallocated page
IoError, // Underlying I/O failed
PermissionDenied, // Write to read-only database
OutOfMemory, // Page buffer allocation failed
Unexpected,
FileNotFound, // Database file doesn't exist
DiskFull, // No space for new pages
DatabaseLocked, // Another process holds a conflicting lock
};
Thread Safety
The Page Manager itself is NOT thread-safe (only its page count is atomic, so readers can check page ids while a writer allocates). Each operation directly touches the file. In a multi-threaded context, the Buffer Pool sits in front of it:
- Caching pages in memory
- Using latches (reader-writer locks) per frame
- Guarding its page table with a mutex
Writes are serialised above both layers: a database allows one read-write transaction at a time, and the C API serialises the calls on a handle.
Usage Pattern
// Open or create database
var pm = try PageManager.init(allocator, vfs, "my.db", .{
.create = true,
.page_size = 4096,
});
defer pm.deinit();
// Allocate a page
const page_id = try pm.allocatePage();
// Write data
var buf: [4096]u8 align(4096) = undefined;
const header: *PageHeader = @ptrCast(&buf);
header.* = PageHeader.init(.btree_leaf);
// ... fill in page data ...
try pm.writePage(page_id, &buf);
// Read it back
var read_buf: [4096]u8 align(4096) = undefined;
try pm.readPage(page_id, &read_buf);
// Free the page (deferred until the next flush)
try pm.freePage(page_id);
// Without a buffer pool to flush through, write the deferred frees and the
// header directly (not atomic), then make it durable
try pm.persistDeferredFrees();
try pm.sync();
Key Design Decisions
Fixed-Size Pages, 4KB by Default
4KB is the default for hardware alignment. The size can be raised at creation (up to 65535 bytes), for example to fit larger values inline; it is stored in the header and the same for every page in the file.
Freelist in Pages
The freelist uses the free pages themselves for storage. No external data structure needed. Elegant and space-efficient.
Checksum Covers the Body, Not the Header
The checksum doesn't cover itself (circular dependency). It sits in bytes 4–7 and covers bytes 8 onward, the whole page after its 8-byte header, in one pass. The price of that choice is that the rest of the header is unprotected too: the page type and flags in bytes 0–1 and the reserved bytes 2–3.
No Internal Fragmentation Tracking
We don't track free space within pages - that's the responsibility of higher layers (B+Tree). The Page Manager only deals with whole pages.
Buffer Pool
What It Is
The Buffer Pool is a cache that keeps frequently accessed pages in memory. Instead of reading from disk every time, we check the buffer pool first.
The Problem It Solves
Disk I/O is slow:
| Operation | Typical latency |
|---|---|
| CPU instruction | ~1 ns |
| RAM access | ~100 ns |
| SSD read | ~100,000 ns (100 µs) |
| HDD read | ~10,000,000 ns (10 ms) |
RAM is 1,000-100,000x faster than disk. If we can keep hot pages in RAM, performance improves dramatically.
Architecture
The Frame
Each frame holds one page:
pub const BufferFrame = struct {
page_id: PageId, // Which page is here (0 = empty)
data: []align(4096) u8, // The page bytes (page_size long)
pin_count: atomic(u32), // Reference count
dirty: bool, // Modified since read?
usage_count: u8, // For Clock eviction (0 or 1)
latch: RwLatch, // Reader-writer lock
};
Pin Count
The pin count is a reference count:
| Call | Effect | Meaning |
|---|---|---|
fetchPage() | pin_count += 1 | I am using this page |
unpinPage() | pin_count -= 1 | I am done with this page |
| Pin count | Consequence |
|---|---|
> 0 | Page is in use and cannot be evicted |
= 0 | Page may be evicted if a frame is needed and it is clean |
Dirty Flag
| Event | Dirty flag | Meaning |
|---|---|---|
| Read page | false | Frame matches disk |
| Modify page | true | Frame differs from disk |
| Flush | false | Frame matches disk again |
A dirty page is never evicted, and never written to the file on its own. It stays in its frame until the next flush writes every dirty page together (see Writing Pages Back).
Reader-Writer Latch
Multiple readers OR one writer
Read latch: "I'm reading, others can read too"
Write latch: "I'm modifying, exclusive access"
Fetching a Page
Simplified from src/storage/buffer_pool.zig (error cleanup left out):
pub fn fetchPage(self: *Self, page_id: PageId, mode: LatchMode) !*BufferFrame {
self.mutex.lock();
// 1. Check if already in buffer pool
if (self.page_table.get(page_id)) |frame_id| {
const frame = &self.frames[frame_id];
_ = frame.pin_count.fetchAdd(1, .monotonic);
frame.usage_count = 1; // a hit sets the use bit
self.mutex.unlock();
self.acquireLatch(frame, mode); // latch outside the mutex; waits
// while a fetch is still reading it
return frame;
}
// 2. Not in pool - take a free frame, evict a clean one, or grow the pool
const frame_id = try self.getFreeFrame();
const frame = &self.frames[frame_id];
// 3. Claim the frame, publish it in the page table, and latch it
// exclusively before letting go of the mutex. The frame was free or
// just evicted, so nobody holds or waits on its latch.
frame.page_id = page_id;
frame.dirty = false;
frame.usage_count = 1;
_ = frame.pin_count.fetchAdd(1, .monotonic);
try self.page_table.put(page_id, frame_id);
_ = frame.latch.tryAcquireExclusive(); // always succeeds here
self.mutex.unlock();
// 4. Read page from disk, outside the mutex but under the latch
try self.pm.readPage(page_id, frame.data);
// 5. Keep the latch the caller asked for (exclusive stays; shared is
// released and taken again shared)
return frame;
}
A second fetch of the same page that arrives while the first is still reading it finds the page in the table and waits on the frame's latch, as it would for any writer, until the read is done. It then checks that the frame still holds its page: if the read failed, it lets go and fetches again. A frame that such a waiter still has pinned is not put back on the free list; it is reclaimed like any unpinned frame. Before this, the second fetch could latch the frame before the read began and see the bytes the frame held before, another page's or zeroes.
The Clock Eviction Algorithm
When the buffer pool is full, we need to evict a page to make room. We use the Clock algorithm (also called "second chance").
Why Clock?
- LRU (Least Recently Used) is optimal but expensive - requires updating timestamps on every access
- Clock approximates LRU cheaply using a usage bit.
usage_countis au8, but a hit sets it to 1 rather than incrementing it, so it behaves as a bit
How It Works
Imagine the frames arranged in a circle with a clock hand:
To find a victim:
Simplified from getFreeFrame, which runs with the pool mutex held:
fn getFreeFrame(self: *Self) !FrameId {
// Try free list first
if (self.free_list.pop()) |frame_id| return frame_id;
// Clock sweep: at most two full rotations
var iterations: usize = 0;
var passed_over_dirty = false;
while (iterations < self.frame_count * 2) : (iterations += 1) {
const frame = &self.frames[self.clock_hand];
const frame_id: FrameId = @intCast(self.clock_hand);
// Skip pinned pages
if (frame.pin_count.load(.monotonic) > 0) {
self.advanceClock();
continue;
}
// Never evict a dirty page: it waits for the next flush
if (frame.dirty) {
passed_over_dirty = true;
self.advanceClock();
continue;
}
// Second chance: if used recently, clear and skip
if (frame.usage_count > 0) {
frame.usage_count -= 1;
self.advanceClock();
continue;
}
// Found a clean victim: drop it from the table, no write needed
_ = self.page_table.remove(frame.page_id);
frame.page_id = NULL_PAGE;
self.advanceClock();
return frame_id;
}
// Every frame pinned: the caller is holding too much at once
if (!passed_over_dirty) return error.BufferPoolFull;
// Some frames were only dirty: grow by one overflow frame instead
return self.addOverflowFrame();
}
The key insight: The use bit gives pages a "second chance". A recently used page survives one pass of the hand. Only pages that haven't been used since the hand last passed get evicted.
Eviction never writes anything: the victim is always a page the file already holds.
When the sweep passes over frames that are only dirty, the pool allocates an
overflow frame beyond its configured size instead. Overflow frames are given back
after the next flush has cleaned them. BufferPoolFull now means every frame is
pinned, which in practice is a pin that was never released.
A sweep that finds every frame of the pool proper dirty, as through most of a large commit or an index build, records that, and until a flush cleans the frames, or a frame goes back to the free list, the pool grows straight away instead of sweeping two full turns for every new page. The overflow list counts its released slots and is searched only when it has one.
The page table
The page table, from page id to frame, is a hash map. A removed key leaves a tombstone, and a lookup of a page that is not in the pool probes until it reaches a slot that has never held a key, so a pool that evicts and misses for long enough would turn its free slots into tombstones and make every miss walk more of the table. A large commit made this much worse: the table grew with the overflow frames and never shrank after the flush gave them back. Removals therefore rehash the table in place once a quarter of its slots may have become tombstones, a few slot visits per removal, and giving back the overflow frames, or emptying the pool, rebuilds the table at the size the pool's own frames need. In a process that had just built a million-node database, a full scan went from 28.9 µs to about 1 µs a node and a random node read from 51.1 µs to about 1.7 µs, the same as after reopening the file (release build, a busy machine).
Unpinning Pages
When done with a page:
pub fn unpinPage(self: *Self, frame: *BufferFrame, dirty: bool) void {
// Mark dirty if modified
if (dirty) {
frame.dirty = true;
}
// Release whichever latch is held (read from the latch state)
self.releaseLatch(frame);
// Decrement pin count
_ = frame.pin_count.fetchSub(1, .monotonic);
}
Always unpin! Failure to unpin causes:
- Pages stuck in memory forever
- Buffer pool eventually fills with pinned pages
BufferPoolFullerrors
Writing Pages Back
Most buffer pools write a dirty page out when they want its frame, and this one used to. It no longer does, because of the write-ahead log.
The log records what transactions did to the graph, not what happened to pages, so it can only be replayed onto a database file that is a complete, consistent image (see Write-Ahead Log). A page written on its own breaks that. A leaf split changes three pages; if the pool evicts and writes the old leaf, the file holds a leaf with half its keys missing while the new leaf and the parent that leads to them exist only in memory. After a checkpoint has emptied the log, that file is the only copy of everything committed before it, and a kill at that point lost committed data: 4000 small transactions against a 48-page pool lost nodes at the first kill.
So a dirty page reaches the file in exactly one way: as part of a flush of every dirty page, the pages freed since the last flush and the header, together, through a journal.
Simplified from flushAll and writeAtomically:
// Write every dirty page, the freed pages and the header as one atomic step.
pub fn flushAll(self: *Self) !u32 {
// Pages freed since the last flush join the freelist now
for (self.pm.deferredFrees()) |page_id| formatAsFreelistPage(page_id);
// Every dirty frame, in the pool and in overflow frames, sorted by page id
const dirty = self.collectDirtyFrames();
// 1. Copy the header image and every page to <db>-journal, and fsync it
try journal.write(file_uuid, page_size, header_image ++ dirty);
// 2. Write the header and the pages in place, then fsync the database file
try self.pm.writeSealed(0, header_image);
for (dirty) |frame| try self.pm.writeSealed(frame.page_id, frame.data);
try self.pm.sync();
// 3. Empty the journal (not synced: applying it again is harmless)
journal.clear() catch {};
for (dirty) |frame| frame.dirty = false;
self.releaseIdleOverflow();
return dirty.len;
}
If the process dies during the in-place writes, the journal holds a complete copy of everything being written, and the next open writes the same pages again before it reads anything else. If it dies while the journal itself is being written, the journal fails its checksums and is discarded, and the database file has not been touched. Either way the file is a whole image, before the flush or after it. Checkpointing describes the journal's format and what each crash point leaves. An in-memory database has no journal.
flushPage(page_id) still exists, but one page cannot go to the file on its own: if
the page is dirty, it flushes everything.
The pool cannot check the two rules that govern when a flush may run, so its callers keep them:
- Every tree a dirty page belongs to must be whole in memory, because the image written is what recovery will start from. The database knows that holds when no page is pinned: a page is pinned for the length of any tree operation that touches it.
- The log must be synced first, because pages may carry the effects of
transactions whose commit records have only been handed to the operating system
(
sync_mode = .normal). A page must never reach the file ahead of the log that explains it.
The database flushes at checkpoints, at close, on an explicit sync(), and early:
after a commit, between the entities a commit applies, before each write made
outside a transaction, and between the records recovery replays, it flushes if at
least half the pool's frames are dirty and nothing is pinned. Before flushing it
writes the vector index's in-memory node map into its tree and copies the tree roots
into the header, so the image is whole in those respects too, and syncs the log.
What this costs: every page a flush writes is written twice, once to the journal and once in place, and a flush syncs both files. Between flushes the pool holds every page changed since the last one, so a large transaction can take it well past its configured size.
Thread Safety
The buffer pool is thread-safe:
- Mutex protects page_table, free_list, clock_hand
- Per-frame latches protect page data
- Atomic pin_count for safe reference counting
| Step | Thread 1 — fetchPage(5) | Thread 2 — fetchPage(5) |
|---|---|---|
| 1 | mutex.lock() | mutex.lock() — blocked |
| 2 | look up page 5 | waiting |
| 3 | pin_count++ | waiting |
| 4 | mutex.unlock() | mutex.lock() — acquired |
| 5 | frame.latch.read() | look up page 5 — found |
| 6 | read data | pin_count++ |
| 7 | read data | mutex.unlock() |
| 8 | read data | frame.latch.read() |
| 9 | unpinPage() | read data |
| 10 | — | unpinPage() |
The page table mutex is held only long enough to find the frame and bump the pin count. Reading the page data happens under the per-frame latch, so two readers of the same page overlap rather than serialising. On a miss the mutex is likewise released after the frame is claimed, latched and entered in the page table, and the disk read happens outside it, under the frame's exclusive latch.
Multiple threads can read the same page concurrently (shared latch).
Memory Alignment
Page buffers are 4KB-aligned:
const page_alignment = comptime Alignment.fromByteUnits(4096);
const data = try allocator.alignedAlloc(u8, page_alignment, page_size);
Why?
- Direct I/O: Some systems require aligned buffers for O_DIRECT (LatticeDB does not use O_DIRECT today)
- SIMD: Aligned data enables vectorized operations
- Cache lines: Better CPU cache utilization
Sizing the Buffer Pool
// 64MB buffer pool = 16,384 pages at 4 KB
var bp = try BufferPool.init(allocator, &pm, 64 * 1024 * 1024);
The pool holds pool_size / page_size frames. A file-backed database sizes it
from, in order of priority:
- An explicit size:
buffer_pool_sizein the ZigDatabaseConfig, orcache_size_mbin the C open options (LATTICE_OPEN_OPTIONS_DEFAULTsets 100) - The
LATTICE_BUFFER_POOL_MBenvironment variable, if set to a positive number (a Ccache_size_mbof 0 that finds it unset means 100 MB) - Otherwise automatic sizing: 16 MB, plus 12 MB when full-text search is enabled (the Zig default) and 12 MB more when vectors are enabled
All of these are the pool's resting size. Between flushes it may hold more, since dirty pages are kept until the next flush rather than evicted.
Guidelines:
- More is better (to a point)
- Working set: Should fit frequently accessed pages
- Available RAM: Leave room for OS and other processes
In-memory databases are different
All of the above assumes there is a disk to avoid. When the storage underneath is
already RAM — a :memory: database, or one opened from bytes — a cache miss costs
a copy from one part of memory to another rather than a trip to a device, so the
pool stops being the difference between fast and slow.
Measured on a fourteen megabyte in-memory database, twelve full scans took 9.2 seconds against a 256 KB pool and 9.9 against a 32 MB one. A hundred and twenty times the memory bought nothing.
So an in-memory database gets a small fixed pool rather than a fraction of the data. That keeps peak memory close to the size of the database itself, which matters when the point of the feature is holding many small databases at once.
The floor is a correctness requirement, not a tuning choice. When the clock
sweep finds every frame pinned the pool returns BufferPoolFull, and that surfaces
as a failed query rather than a slow one. The pool must always have room for the
largest set of pages pinned simultaneously. (Frames that are merely dirty make the
pool grow instead, so the floor is about pins, not writes.)
That number was measured rather than guessed, since guessing it trades memory against query failures. Pools from four frames upward were run through a deep variable-length traversal, a filtered scan, a full-text search, and a bulk write over a fifteen-hundred node graph. Four frames completed all of it — the engine does not hold many pages pinned at once. The floor sits at sixty-four, sixteen times that, because the measurement was single threaded and concurrent readers each pin pages of their own.
Usage Pattern
var bp = try BufferPool.init(allocator, &pm, pool_size);
defer bp.deinit(); // Flushes dirty pages, best effort; close() reports errors
// Read a page
const frame = try bp.fetchPage(page_id, .shared);
defer bp.unpinPage(frame, false);
const value = readValueFromPage(frame.data);
// Modify a page
const frame = try bp.fetchPage(page_id, .exclusive);
defer bp.unpinPage(frame, true); // true = dirty
modifyPage(frame.data);
Key Invariants
- Pin before access: Never access page data without pinning
- Unpin when done: Every fetchPage must have matching unpinPage
- Mark dirty: If you modified the page, set dirty=true when unpinning
- Flush only between operations, with the log synced first: the database does
this at checkpoints, at close, in
sync()and in its early flushes.close()flushes and reports an error if the flush fails;deinit()flushes too but swallows the error
B+Tree
What It Is
A B+Tree is a self-balancing tree structure optimized for disk-based storage. It provides O(log N) lookups, inserts, and deletes, with efficient range scans.
Why B+Tree?
The Problem with Binary Trees
A binary search tree with 1 million entries is ~20 levels deep (log2(1M) ≈ 20). Each level requires a disk read. That's 20 disk reads per lookup!
B+Tree: Wide and Shallow
A B+Tree has many keys per node (hundreds), making it very shallow:
Binary Tree (1M entries): B+Tree (1M entries):
depth ~20 depth ~3
○ ○
/ \ / | \
○ ○ ○ ○ ○
/\ /\ / | \ / | \ / | \
○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○
... (20 levels) (leaf level)
20 disk reads 3 disk reads!
With 100 keys per node: log100(1M) ≈ 3 levels.
Data Only in Leaves
B+Trees store all data in leaf nodes. Internal nodes only contain keys for routing:
Our Implementation: Direct Page Manipulation
We don't create "node objects" in memory. Instead, we read/write bytes directly in page buffers. The "node" is just a lens over page bytes.
Searches, in-place inserts and leaf deletes need no intermediate node object. Two
places still copy: get returns an owned copy of the value (the caller frees it with
freeValue), and splits, merges and redistribution copy the entries into a
temporary list and rebuild the pages from it, in one pass. getBorrowed avoids the
first copy: it returns the value as a slice of its leaf, which stays pinned with a
shared latch until the caller calls release() (an overflow value is materialised
and freed by release()). The node, edge and symbol lookups use it, since they only
decode the value. A caller must release before writing to the same tree, or the
write waits on the latch for ever.
Page Layout
Leaf Node
Leaf pages are slotted pages. The header and slot array grow forward from byte 0; entry bytes grow backward from the end of the page; free space is whatever remains in the middle. (The tables show offsets; the page size is 4096 bytes by default.)
| Offset | Size | Field |
|---|---|---|
| 0–7 | 8 B | Page header — type (leaf), flags, reserved, checksum |
| 8–9 | 2 B | Entry count (u16) |
| 10–11 | 2 B | Flags (u16) |
| 12–15 | 4 B | Next leaf page (u32) |
| 16–19 | 4 B | Previous leaf page (u32) |
| 20 → | 2 B each | Slot array — one entry_offset (u16) per entry, growing forward |
| ← end of page | variable | Entries, growing backward: [key_len][value_len][key][value or overflow descriptor] |
Variable-length entries: Keys and values are stored at the end of the page, growing downward from high offsets. Slots at the front point to the entry records.
Large values are stored through generic B+Tree overflow records. A leaf entry uses the normal key bytes plus a compact overflow descriptor; the descriptor contains the total value length, first overflow page, page count, checksum, and a small local prefix. Point reads and range scans materialize the full value transparently, and deletes free the overflow chain.
Values up to 64 MiB are accepted by the B+Tree layer when the key and overflow
descriptor can fit in an empty leaf. Keys are unique: inserting a key that is
already present fails with DuplicateKey.
Keys are capped at BTree.maxKeySize(page_size), a quarter of an internal page's
payload less one slot: 1012 bytes at 4 KB pages. Any key can become a separator
in an internal node, and the cap guarantees that an overflowing internal node can
always split by bytes into two non-empty halves that fit. insert, replace, put
and canFitLeafEntry reject a longer key with PageFull. Longer keys already in a
file written by an earlier release can still be read and deleted. Symbol names
(labels, edge types, property keys) are stored as keys, so this also caps their
length. Inline-capable values may still be stored
as overflow records when keeping them inline would make future 4 KiB leaf splits
impossible to divide into two valid ordered pages.
Internal Node
Internal pages use the same slotted layout, but each slot carries a child pointer
alongside the key offset, and the values are separator keys rather than user data.
A node with n keys has n + 1 children: slot i's child holds keys that sort
below key i, and the rightmost child holds keys greater than or equal to the last
key.
| Offset | Size | Field |
|---|---|---|
| 0–7 | 8 B | Page header — type (internal), flags, reserved, checksum |
| 8–9 | 2 B | Key count (u16) |
| 10–11 | 2 B | Level (u16; 1 = parent of leaves, increasing toward the root) |
| 12–15 | 4 B | Rightmost child (u32) |
| 16 → | 6 B each | Slot array — key_offset (u16) plus child_page (u32), growing forward |
| ← end of page | variable | Separator keys, growing backward |
Point Lookup
Finding a value by key:
Simplified from src/storage/btree.zig (error mapping left out):
pub fn get(self: *Self, key: []const u8) !?[]const u8 {
// 1. Start at root
var page_id = self.root_page;
while (true) {
// 2. Fetch page from buffer pool
const frame = try self.bp.fetchPage(page_id, .shared);
defer self.bp.unpinPage(frame, false);
const header: *const PageHeader = @ptrCast(@alignCast(frame.data.ptr));
if (header.page_type == .btree_leaf) {
// 3. Binary search in leaf; return an owned copy of the value
const result = LeafNode.searchSlot(frame.data, key, self.comparator);
if (!result.found) return null;
const stored = LeafNode.getStoredValue(frame.data, result.slot);
return try self.materializeStoredValue(stored); // follows overflow chains
}
// 4. Binary-search the separators for the child, descend
page_id = self.findChild(frame.data, key);
}
}
Both searches are binary. In an internal node findChildIndex finds the first
separator greater than the key (an upper bound), or the rightmost child if there is
none.
Example lookup for key "dog":
Insertion
Simple Case: Space in Leaf
An insert either succeeds or returns an error with no page of the tree changed.
Simplified from insert (pin bookkeeping and error cleanup left out):
pub fn insert(self: *Self, key: []const u8, value: []const u8) !void {
if (key.len > maxKeySize(self.page_size)) return error.PageFull;
// 1. Descend from the root, pinning every page on the path exclusively and
// remembering which child was taken at each level
var path = InsertPath{};
defer path.release(self.bp);
try self.descendForInsert(key, &path);
// 2. Reject duplicates
const leaf = path.frames[path.len - 1];
const search = LeafNode.searchSlot(leaf.data, key, self.comparator);
if (search.found) return error.DuplicateKey;
// 3. Prepare either inline bytes or an overflow descriptor
var prepared = try self.prepareStoredValue(key, value);
// 4. Insert in place; one scan of the slot array finds the free space and
// reports PageFull if the entry does not fit
if (self.insertLeafEntryStored(leaf.data, search.slot, key, prepared.value, prepared.overflow)) |_| {
self.noteInsert(leaf.page_id, search.slot); // remembered for splits, below
return;
} else |err| if (err != error.PageFull) return err;
// 5. Does not fit: plan and apply a split
try self.splitAndInsert(&path, search.slot, false, prepared.entry(key), ...);
}
Splitting a Leaf
When a leaf is full:
splitAndInsert plans the whole split before it changes anything:
- Build the leaf's entries plus the new one, in order, and choose the split point
(
chooseInsertSplit): beside the new entry when inserts are arriving in key order (below), otherwise byte-balanced so that both halves fit a page (chooseLeafSplitPoint). - Walk up the pinned path while the separator does not fit the parent. For each
ancestor that overflows, build its combined key/child image and choose the
promoted key: after a leaf split at an edge, when the new separator lands at the
same edge of this node, the key next to it (
edgeInternalPromotion), so the node keeps all but one of its keys; otherwise by bytes (chooseInternalPromotion). - Reserve every new page the split needs, one per splitting level plus a new root
if the root splits, by allocating and pinning it, and find the right sibling
whose
prevlink must change.
If any of that fails (an I/O error or a full disk allocating a page, no buffer frame, no memory for an image), the reserved pages go back to the freelist and the error is returned with the tree untouched. Only then is the plan applied, which rewrites pinned pages and cannot fail: both leaves are written, the sibling links fixed (old → new → the old leaf's former next leaf), and each separator inserted into its parent or carried up into the next split.
A split down the middle is chosen by serialized byte size, not just entry count. This matters when a leaf mixes small keys with large values: both halves must fit in the configured page size after the new entry is included. Internal nodes are split by bytes too; with the key-size cap that always yields two halves that fit.
The middle is the wrong place when keys arrive in order. A tree filled in key order
(node ids, a label's members, an ordered property index being built) inserts past
the last entry every time; split down the middle, each leaf is left half empty for
good, because nothing is inserted into its left half again. So the tree remembers,
for a few leaves (recent_inserts, 16 of them, in memory only), the slot the last
insert into each took (noteInsert). An insert counts as in order when it lands
right after the previous insert into the same leaf, or past the last entry of the
rightmost leaf, which needs no history. Then:
- past the last entry, every existing entry stays and the new one starts the new leaf alone;
- in front of keys already there, the new entry ends this leaf and the keys after it move to the new one, so the ordered run goes on filling this leaf.
Descending order, right before the previous insert or before the first entry of the leftmost leaf, is the mirror image. Random inserts meet these conditions about once per leaf's worth of inserts, and a leaf split that way splits by bytes the next time. A side that would not fit a page falls back to the other side of the new entry, then to a split by bytes. An ordered run therefore fills its pages full instead of half full.
Replacing a Value
replace(key, value) changes the value of an existing key and returns
KeyNotFound otherwise; put(key, value) inserts or replaces. Both make one
descent over the same pinned path and are all or nothing like insert. The new
value, including any overflow chain, is prepared before the leaf changes. A value of
the same stored size is overwritten in place; otherwise, if the leaf has room once
the old entry is gone, the old entry is removed and the new one written into the
same leaf; otherwise the leaf splits through the planned split, with the old entry
left out of the leaf image. The old overflow chain is freed only after no leaf
points at it. The node store's update uses replace, so a node update can no longer
fail half way and leave the node deleted.
Growing the Tree
When the root splits, we create a new root:
The tree grows at the top, not the bottom. All leaves stay at the same depth.
Range Scan
Thanks to linked leaves, range scans are efficient:
Simplified from src/storage/btree.zig:
pub fn range(self: *Self, start_key: ?[]const u8, end_key: ?[]const u8) !Iterator {
// 1. Find starting leaf
const leaf_page = if (start_key) |key|
try self.findLeafForKey(key)
else
try self.findFirstLeaf();
// 2. Keep it pinned and position at the first entry >= start_key
const frame = try self.bp.fetchPage(leaf_page, .shared);
const start_slot: u16 = if (start_key) |key|
LeafNode.searchSlot(frame.data, key, self.comparator).slot
else
0;
return Iterator{
.tree = self,
.current_frame = frame,
.current_slot = start_slot,
.end_key = end_key,
.scratch_value = null,
};
}
The range is half-open: start_key is inclusive and end_key is exclusive, so
the iterator stops at the first key that is greater than or equal to end_key.
Call deinit on the iterator if you stop early, to unpin the current leaf.
rangeBackward(start_key, end_key) reads the same half-open range from its last key
down. It descends once to the leaf end_key leads to, starts below end_key's
slot, and follows the link each leaf keeps to the one before it, stopping below
start_key (or at the first leaf when start_key is null). An ordered property
index uses it to answer ORDER BY ... DESC with a LIMIT without reading the
range forward first.
Iterator walks the leaf chain:
No need to traverse internal nodes for each entry - just follow the links.
Concurrency
The B+Tree does not do latch crabbing. A lookup latches one page at a time through
the buffer pool: it unpins (and so unlatches) a node before it fetches the child. An
insert, replace or put pins and exclusively latches the whole root-to-leaf path on
the way down and releases it in one place when it is done, so a split can update the
parents it already holds.
That is only safe because nothing modifies a tree concurrently with another operation on it. A database has a single writer, and the C API serialises the calls on a handle behind one mutex. The per-frame latches protect individual pages, not the shape of the tree.
The BTree Struct
pub const BTree = struct {
bp: *BufferPool, // Page cache
root_page: PageId, // Current root
comparator: KeyComparator, // For ordering
page_size: u32, // Usually 4096
allocator: Allocator,
// The slot the last insert into each of a few leaves took, so a split
// can tell that inserts arrive in key order. Memory only.
recent_inserts: [16]RecentInsert,
// ...methods
};
This is 168 bytes of metadata, 128 of them the remembered inserts. The actual data lives in pages on disk.
The operations: get (owned copy), getBorrowed (lent value, release() it),
contains, insert, replace, put, delete, range (an iterator) and
rangeBackward (an iterator from the last key down).
Key Design Decisions
Variable-Length Keys and Values
We store the actual bytes, not fixed-size slots. This supports:
- Short keys efficiently (no wasted space)
- Long keys, up to
maxKeySize(1012 bytes at 4 KB pages) - Any binary data
Separator Keys in Internal Nodes
Internal nodes store separator keys, not full key-value pairs. This maximizes fanout (keys per internal node).
In-Place Delete and Leaf Merging
A delete removes the entry inside the leaf: whatever lies below it in the entry heap moves up by its size and its slot is removed, so the heap stays contiguous, with no allocation and one pass. Any overflow chain owned by the removed entry is freed afterwards, once the leaf no longer points at it; if freeing fails part way, the rest of the chain is leaked rather than left referenced by a live entry.
Siblings are looked at only when the leaf has fallen below a third of a page. Then adjacent leaves under the same parent are merged whenever their combined payload fits on one page. The redundant leaf is unlinked and returned to the freelist, and a root with only that leaf remaining is collapsed. Space within a surviving leaf is reusable immediately by later inserts or updates, while reclaimed pages are reused by any later database allocation.
When a sparse leaf cannot merge because its sibling is too full, entries are redistributed by stored byte size and the parent separator is updated. Removing a leaf separator can in turn rebalance internal pages: compatible internal siblings absorb their parent separator and merge, while oversized pairs redistribute keys and promote a new separator. Rebalancing propagates to the root, collapsing every now-redundant tree level.
Page-Based, With Explicit Overflow
Each B+Tree node is exactly one page. Large values span linked overflow pages through an explicit descriptor stored in the leaf; ordinary internal and leaf pages remain fixed-size and directly addressable.
Example: Full Insert Sequence
Insert "zebra" into a tree:
Performance Characteristics
| Operation | Average Case | Worst Case |
|---|---|---|
| Lookup | O(log N) | O(log N) |
| Insert | O(log N) | O(log N) |
| Range(k) | O(log N + k) | O(log N + k) |
Where N is the number of entries and k is the number of entries in range.
Disk I/O per operation: ~3-4 reads for trees up to billions of entries.
Write-Ahead Log (WAL)
The Problem
Imagine you're updating a B+Tree. You need to:
- Modify a leaf page
- Maybe split it (modify parent)
- Maybe split the parent (modify grandparent)
- Update the root
If power fails between steps 2 and 3, your database is corrupted - the tree structure is broken.
Even a single page write isn't safe. A 4KB page write might not be atomic at the hardware level - you could end up with half old data, half new data (a "torn write").
The Insight
Instead of modifying data pages directly, first write a log of what you intend to do. The log is append-only and sequential. Only after the log is safely on disk do you modify the actual data pages.
If you crash:
- Before log write: Nothing happened, no corruption
- After log write, before data write: Replay the log to finish the operation
- After both: Everything is fine
This is the write-ahead rule: log first, then data.
How LatticeDB applies it
LatticeDB logs logical changes — "create node 42 with label Person", "set property name on edge 7" — not page images, and it logs them at commit rather than as each statement runs. Inside a transaction, writes go to an in-memory overlay and nothing reaches the log or the stores. At commit the database:
- appends the overlay's changes to the log as records (buffered; full frames are written but not synced),
- appends
TXN_COMMITand syncs the log — the commit is durable from here, - applies the overlay to the stores, which dirties pages in the buffer pool,
- flushes early if half the buffer pool is dirty, runs an automatic checkpoint if the log has grown past its threshold, and returns.
The synced commit record is the commit point. Nothing has been applied before it, so a failure up to that point leaves nothing committed. A failure after it (the sync itself fails, or applying the overlay fails) cannot be taken back: the handle marks itself failed and the next open replays the log. The Transaction Manager page walks through the sequence.
A log of logical records can only be replayed onto a database file that is a whole, consistent image of the database as of some moment. A record that says "insert node 42" cannot repair a leaf that was half written, or a parent that was written without its new child. Three rules follow, and the rest of the storage engine keeps them:
- The file changes one whole image at a time. The buffer pool never writes a dirty page on its own. Every write to the database file is a flush of all the dirty pages, the freed pages and the header together, copied first to a journal file so that a crash part way through can be finished (see Checkpointing).
- The log is synced before every flush. A flush can capture half of a transaction (commit applies changes one entity at a time), and only the log can finish it after a crash.
- Replay is idempotent. The file can already hold some of what the log holds.
Recovery replays every committed record anyway, and the records state outcomes
("property
ageof node 42 is 31") so that replaying one twice changes nothing.
If you crash:
- Before the commit record is on disk: the transaction does not count; recovery skips its records, and none of its changes reached the file
- After the commit record is on disk: recovery re-executes its records against the stores, so the change survives whether or not any page was written
Why Append-Only Sequential Writes Are Special
The WAL relies on a key property: sequential append is much safer than random writes.
With random writes, the disk head jumps around. A crash can leave any combination of pages in inconsistent states.
With sequential append:
- Only one "frontier" where writing happens
- Everything before the frontier is complete
- Everything after doesn't exist yet
- Much simpler to reason about crash states
The System Primitive: fsync
The WAL's safety depends on one critical system call: fsync (or fdatasync).
write(fd, data, len); // Data goes to OS buffer cache
fsync(fd); // Asks the OS to push the data to the storage device
Without fsync, your "written" data might sit in RAM for seconds or minutes. A power failure loses it. fsync is a durability barrier - when it returns, the operating system has handed the data to the device. How far that goes depends on the platform: on macOS plain fsync does not force the drive's write cache, so a commit there survives a process or OS crash but not necessarily a power cut. The full_fsync option (or LATTICE_FULL_FSYNC=1 in the environment) makes every sync use F_FULLFSYNC, which does ask the drive to flush; it is off by default because it makes each sync markedly slower. See Virtual File System.
This is expensive (milliseconds, not microseconds), and it is most of what a small
write transaction costs. In the default sync mode every commit that changed
something pays for exactly one. sync_mode = .normal (or LATTICE_SYNC_MODE=normal)
skips it: the commit record is handed to the operating system and commit returns,
so the transaction survives the process being killed and reaches the disk at the
next checkpoint, flush or sync(). A power cut or OS crash can then lose the most
recent commits, from the end only. See
Durability and the Log.
There is no group commit. One writer runs at a time and the transaction manager holds its lock across the sync, so there is never a second commit to share an fsync with.
WAL Structure
The WAL is a separate file next to the database, named <database>-wal. It is a
4 KB header followed by a sequence of frames. A frame is the size of a database
page (4096 bytes by default, up to 65535); the size is recorded in the WAL header,
and an existing log keeps the frame size it was created with.
WAL header (4 KB)
| Field | Purpose |
|---|---|
magic | 0x574C4F47 ("WLOG") |
frame_size | Size of every frame in this file |
frame_count | How many frames have been written |
checkpoint_lsn | Where recovery starts replaying |
database_uuid | Binds this WAL to one database file |
version | WAL format version: 3 while the log holds frames, 2 when it is empty |
checksum | CRC32C of the rest of the header |
Frame header (32 bytes, at the start of every frame)
| Field | Purpose |
|---|---|
frame_number | Position of this frame in the file |
record_count | How many records the frame carries |
data_size | Bytes of the frame actually used |
prev_frame_lsn | LSN of the last record in the previous frame |
checksum | CRC32C over the other header fields and the frame's data area |
synced_frames | How many frames, from the start of the log, had been synced when this frame was written |
A log that holds frames is format version 3. An empty log is the same in every
version, so its header says 2, and 0.16.0, which reads versions up to 2, still
opens a database this release closed cleanly or checkpointed. A log this release
left holding frames after a crash says 3, and 0.16.0 refuses it rather than misread
it. This release reads logs written by 0.16.0, whose frames carry no
synced_frames and have a checksum of the data alone; appending to such a log adds
version 3 frames after the old ones.
Each record has its own 32-byte header — record_type, flags, payload_size,
txn_id, lsn, prev_lsn — followed by its payload.
The remainder of each frame holds records back to back, then unused space. Each commit writes out the frame it is in, so a small transaction uses at least one whole frame, and the next commit starts a new one. A frame carrying a single-statement transaction might look like this:
| LSN | Record | Transaction |
|---|---|---|
| 1 | TXN_BEGIN | 1 |
| 2 | INSERT (with payload) | 1 |
| 3 | TXN_COMMIT | 1 |
LSN: The Universal Clock
Every record gets a Log Sequence Number (LSN) - a monotonically increasing integer.
Because a transaction writes all of its records at commit and only one writer runs at a time, one transaction's records sit together in the log:
LSN 1: TXN_BEGIN (txn 1)
LSN 2: INSERT node 42 (txn 1)
LSN 3: UPDATE node 42 name (txn 1)
LSN 4: TXN_COMMIT (txn 1)
LSN 5: TXN_BEGIN (txn 2)
LSN 6: DELETE edge 7 (txn 2)
LSN 7: TXN_COMMIT (txn 2)
LSN serves two purposes:
- Ordering: Total order of all operations
- Recovery point: "Replay from LSN 42"
LSNs are not a permanent clock. When a checkpoint empties the log, the running session keeps counting, but a later open of an empty log starts again at 1: the next LSN is always one past the largest the file holds. Data pages do not record an LSN, and nothing compares a page's state with the log; recovery decides what to redo from transaction outcomes alone.
The prev_lsn Chain
Each record stores prev_lsn - the previous LSN for the same transaction:
| LSN | Record | Transaction | prev_lsn |
|---|---|---|---|
| 1 | TXN_BEGIN | 1 | 0 |
| 2 | INSERT | 1 | 1 |
| 3 | UPDATE | 1 | 2 |
| 4 | TXN_COMMIT | 1 | 3 |
Following prev_lsn from LSN 4 walks transaction 1 backwards: 4 → 3 → 2 → 1.
The chain is the classic tool for rolling a transaction back from the log. LatticeDB writes it but nothing follows it for that: an abort has nothing in the log to undo, because a transaction's changes are only logged when it commits, and recovery has no undo pass. The one reader is the reassembly of fragmented records (below), which checks that the pieces of one record agree.
Write Flow
Records accumulate in an in-memory frame and reach the file a frame at a time:
- When the next record will not fit, the frame is written to the file and the header is rewritten with the new frame count. Neither write is synced.
- A commit ends with
sync(), which writes the partial frame and the header and fsyncs the file, or, insync_mode = .normal, withflush(), which writes them and returns. A small commit therefore costs two writes (the frame and the 4 KB header) and, by default, one fsync.
Nothing is written when a transaction begins. TXN_BEGIN goes out with the
transaction's first record, so a read-only transaction, or a read-write one that
changed nothing, never touches the log: it costs no write and no fsync. An abort
that does have records in the log (a commit that failed after logging some of
them) appends TXN_ABORT without syncing it; recovery only redoes transactions
whose commit record it finds, so a lost abort record changes nothing.
Logical WAL records can be larger than a single frame. Large graph, stream, vector, and
property payloads are fragmented into physical large_fragment records and
reassembled by recovery before redo. The logical payload limit is 64 MiB; a
record above that limit returns ValueTooLarge.
Vector replacements and removals are logical transaction records too. Recovery replays them into the vector index only for committed transactions; an index that cannot replay a vector record causes open to fail rather than return incomplete search results. The database file records its vector index, and the index is written to the file at the open that creates it, before any vector record can be logged, so recovery always has the index to replay into without being told its dimensions. Deleting a node logs a vector removal only when the node has a committed vector. (Logs written by 0.16.0 hold a removal for every deleted node; recovery skips those when the file holds no vector data.)
The log file is created when a database is first opened for writing, and again if it has gone missing, as when a backup is put back without its log. Creating it syncs the new file and its directory entry, once per file, so a power cut cannot lose the log's name together with the commits in it. No commit pays for this.
Commit Protocol
When you call COMMIT on a transaction that changed something:
1. Append the overlay's changes as logical records (TXN_BEGIN first; full frames
written, nothing synced)
2. Append TXN_COMMIT, write the current frame, and fsync() - WAIT for the device
(sync_mode = .normal: write it and do not wait)
3. Apply the overlay to the stores (dirty pages in the buffer pool)
4. Flush early if half the pool is dirty; checkpoint automatically if the log has
reached its frame threshold (best effort: a failed checkpoint does not fail the
commit)
5. Return "committed" to the application
After step 2, even if power fails immediately, the commit record is on disk. Recovery will see the commit and redo the transaction's records.
If we crash before step 2 completes, the commit record might be lost. Recovery won't see a commit for that transaction, so it skips its records. The application was never told the commit succeeded, and nothing of the transaction reached the database file, because nothing was applied before step 2.
If step 2 or step 3 fails, the outcome cannot be undone: the commit record may be
on disk, or is on disk and the stores are missing part of the transaction. The
database marks the handle failed and returns an error. A failed handle refuses new
transactions, commits, sync() and checkpoints, and writes nothing more to the
database file; closing and reopening replays the log.
A read-only transaction, or one that changed nothing, writes nothing to the log at all.
Recovery: Redo Only
On startup, we need to:
- Find the end of valid log - Verify each frame's checksum; a torn tail is cut off when the log is opened, and damage to frames that had been synced refuses the open
- Redo committed transactions - Apply the logical records of every transaction with a commit record, each as an assignment of the state it logged
- Skip everything else - Records of transactions without a commit record are ignored; there is no undo pass
- Empty the log - Checkpoint, so the next open has nothing to replay
Redo is exact. Every record sets the state it describes, whether or not the file already holds it: a node insert makes the node exist with exactly the logged labels and no properties (its property records follow it), a property or label record sets or clears exactly that key or label and its index entry, a delete makes the node or edge absent. Replaying a record twice, or into a file a flush had already brought up to date, gives the same result. A record that cannot be applied fails the open instead of being skipped; see Recovery.
| LSN | Record | Transaction |
|---|---|---|
| 1 | TXN_BEGIN | 1 |
| 2 | INSERT x=1 | 1 |
| 3 | TXN_COMMIT | 1 |
| 4 | TXN_BEGIN | 2 |
| 5 | INSERT y=2 | 2 |
| 6 | INSERT z=3 | 2 |
The process crashes after LSN 6, while transaction 2 is still writing its records.
| Transaction | Has TXN_COMMIT? | Recovery action |
|---|---|---|
| 1 | Yes | Redo — x=1 is permanent |
| 2 | No | Skip — y=2 and z=3 are never applied |
See Recovery for the whole sequence at open.
Why Frames?
Why not just append individual records?
Reason 1: Atomicity
A page-sized write at a page-aligned offset is more likely to be atomic than arbitrary-sized writes. Many storage systems guarantee 512-byte or 4KB atomic writes. Frames start after the 4 KB header at multiples of the frame size, which reduces torn write risk.
Reason 2: Batching writes
Records reach the file a frame at a time, so a large transaction costs one write per page of log rather than one per record. Frames do not batch fsyncs across transactions: each commit syncs its own frame.
Reason 3: Checksums
Each frame has a checksum, so the log can be verified a frame at a time and cut off at the point where it stops being trustworthy.
Reason 4: Large logical records
Frames remain page-sized for torn-write detection and batching, but the WAL no longer requires each logical record to fit inside one frame. Fragmentation keeps large transactional property updates on the WAL path without changing the frame format used for normal records.
The Checksum
We use CRC32C (the Castagnoli polynomial, the same function as page checksums) to detect corruption:
Every frame stores, in its header, a CRC32C of the header's other fields and of
its data area, so a damaged synced_frames cannot pass:
| Frame region | Contents |
|---|---|
| Header | frame_number, record_count, data_size, prev_frame_lsn, checksum = 0xABCD1234, synced_frames |
| Data | [record 1][record 2][record 3] |
On read the checksum is recomputed and compared. A frame verifies only if it also holds at least one record: a frame that never reached the disk reads back as zeroes, and a frame of zeroes would otherwise pass as an empty one. Every reader of the log (the open, recovery and replication) applies the same check. Frames written by 0.16.0 have a checksum of the data alone; a frame is read as old or new by which of the two checksums it matches.
Telling a torn tail from damage. After a power cut, the frames written since the
last sync can be in any state: some whole, some torn or never written, in any order,
because a disk need not write them in the order they were issued. None of them was
promised durable, so none of that is damage. A frame that was synced and then fails
its checksum is damage. synced_frames tells the two apart. Opening the log takes
the largest synced_frames among the frames that verify; call it S. The first frame
that fails is:
- below S: it had been synced, so this is damage to data that was promised durable. It is left exactly as found, and recovery refuses the open (see Recovery) rather than drop the commits in it.
- at or above S: it belongs to the unsynced tail. The log is cut back to the frame before it, and the next frame written takes its place.
A log of 0.16.0 frames only carries no such statement and keeps the rule it was written under: a bad frame with any frame that verifies after it is damage, and one with none after it is a torn tail.
The rule costs a commit nothing: the claim is the frame count at the last completed sync, already in memory, and no extra write or sync is made for it. In exchange, the open syncs a non-empty log before any new frame vouches for it, because a killed process's frames may be only in the operating system's cache, and removes any bytes past the frames the header counts, so a stale frame cannot later be read as part of the log.
The limit. Only frames written after a later sync can vouch for a frame. Damage to the last frames of the newest sync batch, with nothing written after them, cannot be told from a torn write and is cut off as a torn tail: the commits in those frames are lost without an error.
A transaction whose large record was being written as fragments when the process died leaves the first fragments in whole frames and no commit record. When the next record belongs to another transaction, as it does once later commits have been logged after it, the unfinished fragments are skipped; a break in the fragments of one transaction is still damage.
The header has a checksum too. A header whose checksum fails but whose magic, version, frame size and database id are intact was torn while being rewritten; it is rebuilt, taking the frame count from the file's length, and replay starts from the beginning of the log.
This catches:
- Torn writes (partial frame written)
- Bit rot (storage degradation)
- Wrong WAL file (UUID also checked)
The UUID Link
The WAL header stores the database file's UUID:
This prevents accidentally using database A's WAL with database B. The UUID is generated randomly when the database is created.
Record Types
pub const WalRecordType = enum(u8) {
// Transaction control
txn_begin = 0x01,
txn_commit = 0x02,
txn_abort = 0x03,
// Data modifications
insert = 0x10,
update = 0x11,
delete = 0x12,
// Page-level operations
page_write = 0x20,
// Checkpointing
checkpoint_begin = 0x30,
checkpoint_end = 0x31,
// Savepoints
savepoint = 0x40,
savepoint_rollback = 0x41,
// Compensation (for undo during recovery)
clr = 0x50,
// Physical record used to fragment a larger logical WAL record
large_fragment = 0x60,
};
Not every type is in use. Transactions write txn_begin, txn_commit,
txn_abort, insert, update and delete, plus large_fragment for big
records. The first byte of an insert/update/delete payload says which logical
operation it is (node insert, delete or property update; edge insert, delete or
property update; label add or remove; vector set or remove; stream append, offset
or trim). Checkpoints write checkpoint_begin/checkpoint_end, which recovery
treats as informational. savepoint and savepoint_rollback are only written by
the transaction manager's internal savepoint calls, and page_write and clr are
reserved: nothing writes them, and recovery refuses a log that holds a committed
page_write record, as it refuses a payload type no release writes.
WalManager API
// Append a record, get back its LSN
const lsn = try wal.appendRecord(.insert, txn_id, prev_lsn, payload);
// Write buffered records and fsync (commit in sync_mode .full, checkpoints)
try wal.sync();
// Write buffered records without an fsync (commit in sync_mode .normal)
try wal.flush();
// Iterate records for recovery
var iter = wal.iterate(start_lsn);
while (try iter.next(&buf)) |record| {
// Process record
}
// Update checkpoint position
try wal.setCheckpointLsn(lsn);
// Reset to an empty, header-only log (truncate checkpoints)
try wal.truncateToEmpty();
Summary
| Concept | Purpose |
|---|---|
| Write-ahead rule | Commit record synced before anything is applied; log synced before every flush |
| Sequential append | Simpler crash states than random writes |
| fsync | Durability barrier to the storage device |
| LSN | Universal ordering of all operations |
| Sync mode | .full fsyncs every commit; .normal leaves it to the next checkpoint or sync |
| prev_lsn chain | Per-transaction back links (written; only fragment reassembly reads them) |
| Frames | Page-sized, checksummed units of writing; a torn tail is cut off at open |
synced_frames | Each frame says how much of the log was synced before it, so damage to synced frames refuses the open instead of being cut off |
| Checksums | Detect corruption and torn writes |
| UUID | Match WAL to correct database file |
The WAL transforms the problem from "make random writes atomic" (very hard) to "make sequential append reliable" (much easier).
Transaction Manager
What is a Transaction?
A transaction is a logical unit of work - a group of operations that should either all succeed or all fail together.
This chapter explains the internal transaction machinery: the TxnManager in
src/transaction/manager.zig and how the Database uses it. It is not by itself
the public contract. For what a transaction guarantees to an application, see
Transactions and Durability.
| Without transactions | With transactions | |
|---|---|---|
| Step 1 | Debit Alice $100 — succeeds | BEGIN |
| Step 2 | Crash | Debit Alice $100 |
| Step 3 | Credit Bob $100 — never runs | Credit Bob $100 |
| Step 4 | — | COMMIT |
| Result | Alice lost $100 and Bob got nothing | Either both happen or neither does |
The ACID Properties
Transactions guarantee four properties:
| Property | Meaning | How We Achieve It |
|---|---|---|
| Atomicity | All or nothing | Per-transaction overlay + commit record |
| Consistency | Valid state to valid state | Application logic |
| Isolation | Transactions don't interfere | One writer at a time; snapshot copies for other open transactions |
| Durability | Committed = permanent | The synced commit record, and recovery |
The public contract permits one live read-write transaction per database. Starting
a second one while the first is open fails with TransactionConflict (in C,
LATTICE_ERROR_LOCK_TIMEOUT) instead of waiting. The transaction manager also
hands out MVCC-style timestamps (start_ts, commit_ts), and
src/transaction/mvcc.zig holds version-chain machinery, but the storage layer
does not use either; they are an internal target, not a guarantee.
The Core Data Structures
Transaction (User-Facing Handle)
This is what the application sees:
pub const Transaction = struct {
id: u64, // Unique identifier (1, 2, 3, ...)
state: TxnState, // active, committed, or aborted
mode: TxnMode, // read_only or read_write
isolation: IsolationLevel, // snapshot, read_committed, serializable
start_ts: u64, // When transaction started (for visibility)
commit_ts: u64, // When committed (0 until commit)
};
TxnEntry (Internal State)
The manager keeps more detailed state internally:
const TxnEntry = struct {
txn: Transaction, // The user-facing handle
last_lsn: u64, // LSN of most recent operation
begin_lsn: u64, // LSN of TXN_BEGIN, once it has been written
wal_started: bool, // Whether TXN_BEGIN has been written
savepoints: ArrayList, // Stack of savepoints
undo_log: ArrayList, // Operations to reverse on abort
};
TxnManager (The Coordinator)
pub const TxnManager = struct {
allocator: Allocator,
wal: *WalManager, // For durability
active_txns: HashMap(u64, TxnEntry), // All running transactions
next_txn_id: u64, // Counter for IDs
current_ts: u64, // Global timestamp clock
committed_count: u64, // Statistics
aborted_count: u64,
mutex: Mutex, // Thread safety
};
Transaction Lifecycle
1. BEGIN
When you start a transaction:
Database.beginTransaction first refuses a second read-write transaction while one
is open, and refuses everything on a handle that has failed.
Then the transaction manager:
- Locks the manager mutex.
- Assigns the next transaction id.
- Assigns
start_ts. - Creates a
TxnEntrywithwal_started = falseand stores it inactive_txns. - Unlocks the mutex and returns the
Transactionto the caller.
Nothing is written to the log. TXN_BEGIN is appended with the transaction's first
record, which for a transaction begun through the database means at commit. A
transaction that never logs anything never touches the log at all.
The database then creates an empty overlay for the transaction. That happens for read-only transactions too.
Transaction ids do not restart with each session. A log can outlive the session that wrote it, and if ids started at 1 again, a later recovery could read one session's uncommitted records and another session's commit as a single transaction. Recovery reports the largest id it saw in the log, and the new session numbers its transactions above it.
start_ts is recorded but nothing in the storage layer reads it.
2. Operations
Writes inside a transaction do not go to the log as they happen. Creating a node, setting a property or deleting an edge records the new state in the transaction's overlay, an in-memory map from node, edge and vector ids to their pending state, plus lists of stream appends, offsets and trims. Reads in the same transaction look in the overlay first. Checks that can reject a change for its content, such as an edge too large for a page, run when the change is staged, so a transaction that would fail for what it contains fails before anything is logged.
The log is written at commit, when the database turns each overlay entry into one
or more records and passes them to logOperation:
- Check
txn.canWrite(). - Look up the
TxnEntry. - If
wal_startedis false, appendTXN_BEGINfirst and set it. appendRecord(INSERT, txn_id, prev_lsn = last_lsn, payload = data). The WAL returns the new LSN.- Update
last_lsnand return the LSN to the caller.
Notice how prev_lsn points to the previous operation. This builds a backward chain.
(A write with no transaction at all, through the Zig API's null transaction, goes
straight to the stores and is not logged. It reaches the file only when its pages
are flushed.)
3. COMMIT
Commit makes everything permanent. The transaction manager's part:
- Check that
txn.state == active. - If the transaction has written anything (
wal_started):appendRecord(TXN_COMMIT, prev_lsn = last_lsn), thenwal.sync(), which issues thefsync(). Insync_mode = .normalit callswal.flush()instead, which writes the frame without waiting for the disk. - Assign
commit_ts, settxn.state = committed, remove the entry fromactive_txns, and incrementcommitted_count.
A transaction that wrote nothing skips step 2: no record, no write, no fsync.
Database.commitTransaction wraps those steps. For a transaction whose overlay
holds changes, it runs, in order:
- Copy the pre-commit state of every node, edge and vector the overlay changes into each other open transaction's overlay (see Timestamps and Isolation).
- Stage graph changefeed records and assign stream sequence numbers.
- Log the overlay: append its logical records (
logOperation); nothing is synced. tm.commit: appendTXN_COMMITand sync the WAL. This is the commit point. Before the sync returns the transaction can still be lost, and losing it is the same as it never having run; after it, recovery will find the commit record and redo the transaction.- Apply the overlay to the base stores — graph stores, label index, vector index, streams, and the full-text and property indexes that follow from them. This dirties pages in the buffer pool.
- Discard the overlay, clear the active writer, flush early if half the buffer pool is dirty and nothing is pinned, and wake stream readers if streams changed.
- Run an automatic checkpoint if the WAL has reached its threshold (best effort).
Steps 1, 2, 3 and 5 all compare each changed node and edge with what the store holds for it. That is read once, before step 1, in id order, and kept on the overlay until it is discarded; the store cannot change in between, since only the one writer changes it. A commit holds those pre-images, the decoded records of the nodes and edges it updates or deletes (not the ones it creates), alongside the overlay until step 6.
A transaction with no changes, read-only or not, goes straight to tm.commit,
which writes nothing.
The order used to be different: the overlay was applied before the commit record was written. A failure while applying then left half a transaction visible in the process, and written out by the next checkpoint, while the log said it had never committed. With the synced commit record as the commit point, nothing is applied until the log holds the whole transaction.
Large property updates avoid carrying both old and new full values in commit-time WAL records when redo does not require both; the changefeed uses summary maps for values that would exceed stream/WAL sizing limits.
When commit fails
A failure before the commit point (steps 1 to 3) is an ordinary error. Some of the transaction's records may be in the log, but no commit record, so recovery will ignore them. The transaction is still open, and the caller rolls it back.
A failure at or after the commit point cannot be undone. If the sync fails, the commit record may or may not be on disk, and nobody can say which. If applying fails, the record is on disk and the stores are missing part of the transaction. Either way the process's memory no longer matches its log, so the database marks the handle failed and returns an error.
A failed handle refuses new transactions and commits, refuses sync() and
checkpoints, does no early flushes, and on close abandons its dirty pages, so the
half-applied state never reaches the database file. Open transactions are ended
without writing to the log, since an abort record after a commit record of unknown
fate would decide an outcome nobody knows. The caller's recourse is to close and
reopen: recovery replays the log and produces the state it describes, which includes
the transaction if its commit record reached the disk.
4. ABORT
Abort discards everything. At the database level that means dropping the transaction's overlay: nothing it staged ever reached the stores. (The transaction manager also keeps a per-transaction undo log, replayed on abort only for writes that bypassed the overlay; ordinary transactional writes do not.) Then the transaction manager:
- If the transaction has written anything to the log, appends
TXN_ABORT. It is not synced. - Sets
txn.state = aborted, cleans up theTxnEntryand removes it fromactive_txns. - Returns to the caller.
In the common case nothing was logged, so abort does not touch the log. An
overlay transaction has records in the log only if a commit attempt failed after
logging some of them. The abort record is not synced because recovery only redoes
transactions whose commit record it finds: a lost TXN_ABORT changes nothing.
Written, it lets recovery report the transaction as aborted rather than as in
progress at the crash. On a failed handle, open transactions are ended with
discard, which writes nothing.
The prev_lsn Chain
Every record points back to the previous record from the same transaction. This creates a linked list through the WAL:
| LSN | Record | Transaction | prev_lsn |
|---|---|---|---|
| 1 | TXN_BEGIN | 1 | 0 |
| 2 | INSERT | 1 | 1 |
| 3 | UPDATE | 1 | 2 |
| 4 | TXN_COMMIT | 1 | 3 |
| 5 | TXN_BEGIN | 2 | 0 |
| 6 | DELETE | 2 | 5 |
| 7 | TXN_COMMIT | 2 | 6 |
Because records are written at commit and only one writer runs at a time, one
transaction's records are contiguous in the log. Following prev_lsn backwards
gives each transaction's chain:
- Transaction 1: 4 → 3 → 2 → 1
- Transaction 2: 7 → 6 → 5
What is it for? In a classic ARIES design the chain drives rollback and undo during recovery without scanning the whole log. LatticeDB writes it, but nothing follows it for that: abort discards the overlay, and recovery identifies uncommitted transactions by scanning the log forward and has no undo pass. The one reader is the reassembly of fragmented records, which checks that the pieces of one record agree.
Savepoints (Internal, Incomplete)
TxnManager has savepoint and rollbackToSavepoint, but nothing above it calls
them: there is no savepoint API in the database layer, the C API, the bindings or
Cypher. They are also incomplete. Rolling back to a savepoint logs
SAVEPOINT_ROLLBACK and truncates the transaction manager's undo log, but it does
not touch the transaction's overlay, and recovery ignores savepoint records, so
nothing is actually undone.
Timestamps and Isolation
Every transaction gets two timestamps:
start_ts: Assigned at BEGIN
commit_ts: Assigned at COMMIT
They are the hooks an MVCC design would use to decide visibility. The storage layer does not consult them. Isolation comes from two simpler mechanisms instead:
- One writer. Only one read-write transaction can be open at a time, so writers never interleave.
- Snapshot copies at commit. Uncommitted writes live only in the writer's overlay, so nobody else can see them. When the writer commits, the database first copies the pre-commit state of every node, edge and vector it changed into each other open transaction's overlay (unless that overlay already has an entry for it). Those transactions read their overlay first, so they keep seeing the values from before the commit.
Snapshot Isolation Example
| Step | Transaction | Event |
|---|---|---|
| 1 | Txn A | BEGIN (read-write) |
| 2 | Txn A | SET x = 100 — staged in A's overlay |
| 3 | Txn B | BEGIN (read-only) |
| 4 | Txn A | COMMIT — the old x is copied into B's overlay, then A logs, syncs and applies its change |
| 5 | Txn B | Reads x |
Question: What does Txn B see when it reads x?
Txn B was open when Txn A committed, so its overlay received the old value of x
at step 4. B does NOT see x=100; it sees whatever x was before Txn A.
The copies cover node, edge and vector state only. How long-lived concurrent readers behave beyond that is not part of the public contract.
Read-Only Transactions
Read-only transactions are special:
var txn = try tm.begin(.read_only, .snapshot);
// This fails:
const result = tm.logOperation(&txn, .insert, "data");
// Error: TxnError.ReadOnly
Why have read-only transactions?
- No single-writer conflict - any number can be open alongside the one writer
- A stable view - they receive snapshot copies when a writer commits, as above
- Nothing to log - their overlay stays empty, so commit has nothing to apply
They cost no log I/O: begin writes nothing, and commit or abort writes no record and does no fsync. A read-write transaction that changes nothing behaves the same way.
What a reader does cost is memory, and some of the writer's time: each commit copies into the reader's overlay the committed state of every entity the writer changed that the reader does not already hold. A long-lived reader does not hold back checkpoints, which only wait for open transactions that have records in the log (see Checkpointing).
Thread Safety
The TxnManager uses a mutex to protect shared state:
pub fn begin(self: *Self, ...) TxnError!Transaction {
self.mutex.lock(); // ← Only one thread at a time
defer self.mutex.unlock(); // ← Released when function exits
// Safe to modify next_txn_id, active_txns, etc.
...
}
This is a simple approach. The mutex is held briefly, and the WAL I/O dominates
latency anyway. commit holds it across the log sync, so commits are serialised
through it as well.
Statistics
The manager tracks statistics for monitoring:
const stats = tm.getStats();
stats.active_count // Currently running transactions
stats.committed_count // Total successful commits
stats.aborted_count // Total aborts
stats.oldest_active_id // Oldest running transaction
stats.current_ts // Current timestamp
oldest_active_id is what garbage collection of old versions would need. The
engine keeps no old versions to collect, so nothing uses it yet.
API Summary
This is the internal API the Database drives; applications use
Database.beginTransaction, commitTransaction and abortTransaction (or the
bindings' equivalents) instead.
var tm = TxnManager.init(allocator, &wal);
// Start a transaction
var txn = try tm.begin(.read_write, .snapshot);
// Log operations (the database does this at commit, from the overlay)
_ = try tm.logOperation(&txn, .insert, payload);
_ = try tm.logOperation(&txn, .update, payload);
// Commit or abort
try tm.commit(&txn); // or tm.abort(&txn)
// Has any open transaction written to the log? (checkpoints check this)
const busy = tm.hasLoggedActiveTxn();
Integration
The Transaction Manager is the log-facing half of transactions - it doesn't store
data itself, and it does not touch the B+Trees. It assigns ids, writes the begin,
commit and abort records, and owns the sync that makes a commit durable. The
Database owns the other half: the overlays, the single-writer rule, applying
committed changes once the commit record is on disk, and the failed state when that
cannot be finished.
Checkpointing
The Problem
Without checkpointing, two bad things happen:
- WAL grows forever - Every transaction appends records, file gets huge
- Recovery takes forever - After crash, must replay entire WAL from the beginning
After a year of operation the WAL holds millions of records stretching back to day one, and recovery has to replay every one of them. Without checkpoints, startup time grows without bound.
The Solution
A checkpoint says: "Everything up to this point is safely on disk in the main database file. We don't need the old WAL records anymore."
Most of the work of a checkpoint is getting the pages into the file, and that is the part that has to be done carefully.
Why Pages Cannot Go One at a Time
The obvious flush is a loop: for each dirty page, write it at its offset. A crash can stop that loop anywhere. For a log of page images that would not matter, but LatticeDB's log is logical (see Write-Ahead Log), and a logical record can only be replayed onto a file that is a whole, consistent image. Take a B+Tree split that changed three pages: the leaf that split, its new sibling, and the parent that points at both. If the loop writes the leaf and dies before the parent, the file holds a leaf that has lost half its keys and a parent that knows nothing of the sibling holding them. The log says "insert node 42"; it has no way to say "put the parent back".
So the database file only ever moves from one whole image to the next. That takes three pieces.
A buffer pool that never writes a page on its own
The buffer pool never evicts a dirty page. When the clock sweep finds only dirty (or pinned) frames, the pool grows by an overflow frame beyond its configured size, and gives the extra frames back after the next flush has cleaned them. Freed pages are deferred the same way: freeing a page does not write a freelist link into the file; the page manager remembers it, and the next flush chains it onto the freelist together with everything else. The file header, with the tree roots and the freelist head, changes only in memory between flushes. See Buffer Pool.
Flushing early
Holding every dirty page costs memory: between flushes, a large transaction, a long
recovery or a run of direct writes can push the pool well past its configured
size. So the database also flushes before a checkpoint is due. When at least half
the pool's frames are dirty and no page is pinned, it writes the vector index's
in-memory node map into its tree, copies the tree roots into the header, syncs the
log, and flushes; without a log, it first applies the changefeed's retention policy
(below), since there are no checkpoints to do it. It is called after every commit,
before each write made outside a transaction, and between the operations recovery
replays, and does nothing when it cannot act. With a log it is also called between
the entities a commit applies (relieveApplyPressure).
"Nothing pinned" is how it knows no B+Tree operation is half done: a page is pinned for the length of an operation that touches it. An early flush can still land in the middle of a commit and write half a transaction, but that transaction's commit record is already in the log, so recovery finishes it. Without a log nothing could finish it, so no early flush runs while a commit is being applied: the pool grows past its size if it must, and the flush the end of the commit offers writes the transaction whole. Early flushes are not checkpoints: they leave the log as it was.
The journaled flush
Every write of pages to the database file goes through one function,
BufferPool.flushAll, and it writes everything at once: every dirty page, the
pages freed since the last flush (formatted as freelist pages), and the header,
sorted by page number. What makes that one step atomic is writing it twice.
Before any page is written in place, the whole set is written to a second file
beside the database, <database>-journal, and synced. The journal is a 4 KB header
(magic "LTDJ", version, page size, page count, the database's file UUID, a
checksum of the table and one of the header itself), a table of page ids and CRC32C
checksums padded to 4 KB, and then the page images, header first. It is written
images first, then the table, then the header, and synced once. Only then are the
pages written in place, header first, and the database file synced. Finally the
journal is truncated, without a sync.
The journal is read only when the database is opened, before anything else reads the file (see Recovery). If its header and table verify, it names this database, and every image matches its checksum, all of it is written in place; otherwise it is discarded.
| Crash during | State | Next open |
|---|---|---|
| Writing the journal | Journal incomplete; database file untouched | Journal fails its checks and is discarded: the old image |
| Writing pages in place | Journal complete and synced; file part old, part new | Journal applied: the new image |
| Truncating the journal | File complete and synced; journal perhaps still there | Journal applied again, writing bytes the pages already hold: the new image |
The cost is plain: every page reaches the disk twice, and every flush syncs two files. Flushes are much rarer than commits, which is what makes that affordable. An in-memory database has no journal, since there is no crash for it to survive. While a database is open the journal file exists, empty between flushes; a clean close deletes it.
Log first, then pages
Every caller of the flush syncs the log first when there is one: an early flush, a
checkpoint, sync(), and close. An image may contain half of a transaction that the
log can finish, but only if the log has it. In the default sync mode the log is
already synced at every commit and this extra sync is cheap; in
sync_mode = .normal it is what makes recent commit records durable before the
pages that depend on them. A database opened without a log has only the journaled
flush: a commit is durable once a flush after it has finished, and because the
flush never writes part of a transaction, the file always holds whole
transactions.
How a Checkpoint Runs
Every checkpoint goes through one function in the database, runCheckpoint.
Refusals
Two refusals come first:
- A failed handle (see Transaction Manager) holds trees missing part of a committed transaction. Checkpointing them would write that state to the file and then empty the log that could repair it, so the checkpoint returns an error.
- An open transaction with records in the log. Recovery only redoes a
transaction whose
TXN_BEGINit reads; a checkpoint that moved the replay point past that record, or emptied the log under it, would make recovery drop the transaction's commit. Such a checkpoint returnsTransactionConflict. Because a transaction writes nothing to the log until it commits, this is rare in practice: readers, and writers still staging changes, do not hold a checkpoint back.
Changefeed retention
Next the checkpoint applies the changefeed's retention policy. Under last:N
(keep the newest N events) or age: (keep the events committed within that long)
it drops the events the policy no longer keeps, oldest first; under all, the
default, it does nothing, and under off no events are written at all. The deletes
are not logged. The pass first raises a floor kept beside the feed, below which
every event is gone, and the floor and the deletes reach the file in this
checkpoint's flush, together. Replay skips any logged event below the floor, so a
dropped event cannot come back, and a reader that asks for the feed from its
beginning starts at the floor. The pass is bounded, to 4,096 events plus those
committed since the last complete pass, so a backlog left by a stricter policy is
worked off over several checkpoints instead of stalling one;
Database.trimChangefeed (lattice_changefeed_trim in C) applies the policy in
full and syncs. Without a log, where there are no checkpoints, the same pass runs
before the flushes of sync(), close and the early flush.
State outside the buffer pool
Then two pieces of state that live outside the buffer pool are put into it: the vector index's in-memory node map is written into its B+Tree, and the B+Tree root page numbers are copied into the file header. Without that, the flush would write pages whose roots the header does not name, and a process killed after a truncating checkpoint would reopen onto stale roots with nothing left in the log to replay.
The eight steps
The Checkpointer in src/storage/checkpoint.zig then runs:
- Append
CHECKPOINT_BEGINto the log. - Sync the log.
- In truncate mode, advance
checkpoint_seqin the header, in memory. The flush in the next step writes it, so it is durable before the log is reset in step 8; anything following the log for replication reads the reset from it. - Flush: the journaled flush above, which also syncs the database file.
- Append
CHECKPOINT_END, with the number of pages flushed. - Set the log header's
checkpoint_lsnto theCHECKPOINT_ENDrecord. - Sync the log.
- In truncate mode, cut the log back to its header and sync it. If that fails the
pages are already durable, so the checkpoint still succeeds and reports
wal_truncated = false.
The begin and end records are informational: recovery reads past them. What
recovery uses is checkpoint_lsn in the log header and, in the default mode, the
truncation.
The Checkpoint Modes
The mode decides what happens at steps 4 and 8.
Truncate Mode
Flushes everything and then resets the log to its header. It is the only mode that
bounds the log's size, the default for automatic checkpoints, and what open, close
and lattice checkpoint use. The running session keeps counting LSNs; a later open
of the empty log starts again from 1.
Full Mode
Flushes everything and leaves the log in place, with checkpoint_lsn marking where
replay now starts. Backup and serialisation use it to make the file a complete
database before copying it, without disturbing anything reading the log.
Passive Mode
Does not wait. If any dirty page is pinned, it writes nothing at all and returns
with checkpoint_lsn where it was. It cannot flush the pages it is able to and skip
the rest, because a flush of some dirty pages and not others is exactly a torn image.
A full or passive checkpoint keeps every frame, so the log keeps growing. It bounds recovery time, not disk space.
What If We Crash Mid-Checkpoint?
The file is always a whole image, and the log is never emptied before the image that replaces it is synced.
| Crash after | Database file | What recovery does |
|---|---|---|
| Steps 1–3 | The previous image | Replays the log as before; CHECKPOINT_BEGIN is ignored |
| During step 4 | The previous image or the new one, decided by the journal | Replays the whole log onto whichever it is |
| Steps 4–7 | The new image | Replays from whichever checkpoint_lsn the header holds; the records it replays are already in the image, and replaying them changes nothing |
| Step 8 | The new image | Finds an empty log, or one the truncation had not yet reached |
The last two rows depend on replay being idempotent: the log records state outcomes
("property age of node 42 is 31"), so replaying one onto an image that already
holds it changes nothing. A torn checkpoint costs replay time, not correctness.
Statistics
Each checkpoint returns stats:
CheckpointStats{
pages_flushed: 42, // How many dirty pages written
duration_ns: 15_000_000, // 15ms
checkpoint_lsn: 1002, // New checkpoint position
wal_truncated: false, // Whether WAL was reset
}
They say what the checkpoint did, including when a passive checkpoint wrote nothing or a truncation failed after the flush succeeded. Useful for monitoring:
- If
pages_flushedis always high, consider checkpointing more often - If
duration_nsis high, disk might be slow - Track
checkpoint_lsngrowth over time
When to Checkpoint
Usually you don't decide. Checkpoints run at four moments.
After a commit, when the log holds at least max_wal_frames frames. The
auto_checkpoint setting in DatabaseConfig is on by default:
| Setting | Default | Meaning |
|---|---|---|
max_wal_frames | 1000 | WAL frames written before a checkpoint is considered |
min_interval_ns | 0 | Shortest gap between two automatic checkpoints |
mode | .truncate | The only mode that resets the log, so the only one that bounds its size |
Each commit that changed something writes at least one frame, so the default is
at most a thousand write transactions; single-node commits reach it about once in a
few hundred. The automatic checkpoint is best
effort: it runs after the commit has succeeded, and if it fails, or is refused
because a transaction has records in the log, the commit still reports success and
the next commit tries again. Setting auto_checkpoint = null turns it off.
Database.setAutoCheckpoint changes the policy commits follow on an open database
(null or 0 frames for none) without changing what open and close do; the C API's
lattice_set_auto_checkpoint, each binding's setter, the CLI's
--auto-checkpoint=<frames> and the LATTICE_AUTO_CHECKPOINT_FRAMES variable all
set it.
It runs inside the commit call that crossed the threshold, not on a background thread, so that one call returns later. In the published measurements (Benchmarks: 0.17.0 through the C API, default settings, Apple M5), of 20,000 single-node commits the median took 44 µs and the 99.9th percentile 1.4 ms; about one commit in a few hundred also ran a checkpoint, and those, with the disk's own stalls, are that 99.9th percentile. The slowest single commit ranged from 2 ms to over 200 ms from run to run. Taking the checkpoint off the commit path would need a background checkpointer, which LatticeDB does not have; a program that cannot afford the pause can raise the interval, or turn the automatic checkpoint off and run checkpoints itself.
At open, after recovery, if the log holds records after its last checkpoint, so the next open has nothing to replay and a torn frame at the log's tail does not sit in front of new ones. A read-only open that recovers a crashed database runs this checkpoint too, on its in-memory overlay of the files, so it changes nothing on disk (see Recovery).
At close, for the same reason: Database.close() runs a truncate checkpoint when
the log holds records after its last checkpoint, and the C API's lattice_close
syncs the database first and then does the same. A log that ends at its own last
checkpoint (a .full or .passive checkpoint, such as the one a replication
snapshot takes, leaves its records behind) has nothing to fold in and is left as it
is: resetting it would advance the log's reset counter, which replication reads as
the start of a new generation. Either way a cleanly closed database needs nothing
from its log, and the journal is deleted. Both the open and the close checkpoint are skipped when
auto_checkpoint is null, which leaves truncating the log to the caller, and both
are skipped on a failed handle.
On request:
Database.checkpoint(mode)in the Zig API,lattice_checkpoint(db, mode, &stats)in C, and each binding'scheckpoint. While a transaction has records in the log it is refused withTransactionConflict(LATTICE_ERROR_LOCK_TIMEOUTin C). Without a log it does nothing and reports no pages flushed; on a read-only handle the Zig call does nothing and the C call returnsLATTICE_ERROR_READ_ONLY.lattice checkpoint <path>: opens the database and runs a truncate checkpoint.backupandserialize: run a full checkpoint so the copied file stands on its own (see Portable Databases).
The Checkpointer also has a size check you can use when managing checkpoints by
hand:
// Check if WAL has grown too large
if (checkpointer.shouldCheckpoint(1000)) {
_ = try checkpointer.checkpoint(.truncate);
}
A small threshold means a short replay after a crash and a flush, with its journal, every few commits; a large one means fewer flushes, a longer log, and more reliance on early flushes to keep the buffer pool in bounds.
Integration
The Checkpointer coordinates between:
- BufferPool:
flushAll, the journaled flush of every dirty page, freed page and the header, which also syncs the database file - PageManager: bumps
checkpoint_seqin the in-memory header - WalManager: Records checkpoint markers, updates checkpoint_lsn, truncates the log
The database around it decides whether a checkpoint may run at all, applies the changefeed's retention policy, and puts the vector index map and tree roots in place first.
API
From the database (returns null for a read-only handle or one without a WAL):
// Checkpoint and reset the log
if (try db.checkpoint(.truncate)) |stats| {
log("Flushed {} pages", stats.pages_flushed);
}
The Checkpointer underneath. Called directly it skips the database's refusals and
the vector index and tree-root step, which is why the database never does:
var checkpointer = Checkpointer.init(allocator, &bp, &pm, &wal);
// Passive checkpoint: writes nothing if a dirty page is pinned
const passive_stats = try checkpointer.checkpoint(.passive);
// Full checkpoint (pages durable, log left in place)
const full_stats = try checkpointer.checkpoint(.full);
// Truncate checkpoint (reclaim WAL space)
const truncate_stats = try checkpointer.checkpoint(.truncate);
// Check if checkpoint needed
if (checkpointer.shouldCheckpoint(1000)) {
_ = try checkpointer.checkpoint(.truncate);
}
// Get last checkpoint stats
if (checkpointer.getLastStats()) |stats| {
log("Flushed {} pages in {}ms", stats.pages_flushed, stats.duration_ns / 1_000_000);
}
Summary
| Concept | Purpose |
|---|---|
| Journaled flush | Every dirty page, freed page and the header reach the file together, or not at all |
| No dirty eviction | The buffer pool grows instead of writing a page on its own |
| Early flush | Half the pool dirty and nothing pinned: flush without checkpointing |
| checkpoint_lsn | Recovery starting point |
| CHECKPOINT_BEGIN/END | Markers in the log; informational |
| Passive mode | Writes nothing if a dirty page is pinned |
| Full mode | Flushes everything, keeps the log |
| Truncate mode | Flushes everything and empties the log; the automatic default |
| Auto-checkpoint | After a commit, at 1000 frames; refused while a transaction has records in the log |
Checkpointing is the bridge between WAL-based durability (fast commits) and bounded recovery time (fast restart). Without it, durability requires replaying the entire history on every startup.
Crash Recovery
The Problem
Databases crash. Power fails, operating systems panic, processes get killed. When this happens, the database must be able to restart and return to a consistent state without losing committed data.
Consider what is where when a crash occurs:
Scenario: Crash during normal operation
Buffer Pool (RAM): gone
dirty pages, all from committed transactions
the vector index's in-memory node map
Transaction overlays (RAM): gone
open transactions' staged changes - never logged, never applied
Database File (Disk):
a whole image of the database as of its last flush
Journal (Disk):
empty, or the flush that was being written
WAL (Disk):
[committed txn records][records without a commit record][partial frame?]
Because no page ever reaches the file on its own (see Checkpointing), the file is never a mixture of two images, except while a flush is writing it, and then the journal holds the newer one.
After restart, we need to:
- Finish an interrupted flush - so the file is one whole image
- Redo committed work - If a transaction committed (COMMIT record in WAL) but its changes weren't flushed to the database file, redo them
- Ignore uncommitted work - If a transaction never committed, pretend it never happened
The ARIES Philosophy
Our recovery is inspired by ARIES (Algorithms for Recovery and Isolation Exploiting Semantics), a recovery algorithm developed at IBM, but it is much smaller: redo only, and logical rather than physical. The key insight:
Write-Ahead Logging + Redo at Recovery = Durability
The WAL contains everything we need. After a crash:
- Read the WAL from the last checkpoint
- Determine which transactions committed
- Redo only committed operations, by re-executing them against the stores
The Order of Work at Open
Recovery is not one function but a sequence spread through Database.open:
- The page manager finishes any interrupted flush from the journal, before it reads the file's header.
- The log is opened: its database id is checked, an unsynced tail is cut off and a torn header rebuilt.
- The trees, graph stores, full-text index and vector index are loaded from the file. The vector index has to exist before replay, because replay needs somewhere to put vectors; the file records the index's configuration, so it is loaded whatever the open's options say.
- Analysis and redo run (below).
- If anything was redone, the property and full-text indexes are rebuilt from the trees, since replay does not maintain them, and the result is flushed.
- The transaction manager starts, numbering transactions above the largest id the log contained.
- Unless
auto_checkpointis null, a truncate checkpoint empties the log, so a second crash does not replay it all again and a torn frame does not sit in front of new ones. A log that ends at its own last checkpoint is left as it is, since the file already holds everything in it.
A database opened with enable_wal = false never opens the log and never replays
it.
A read-only open of a database whose log holds frames, or whose journal holds a
flush, runs exactly these steps on an overlay filesystem (OverlayVfs): the files
are opened for reading only, and every write recovery makes, the journal applied,
the replay and the checkpoint that folds it in, goes to memory in 4 KB blocks over
the files. The handle is then read-only as usual. Nothing reaches the disk, and the
next read-write open recovers the files itself. The overlay may hold at most 64 MB
plus four times the size of the log and journal; a recovery that needs more fails
the open with BufferPoolFull, and a read-write open recovers such a database. A
read-only open with an empty log and no journal reads the file directly, as before.
The reader's shared lock keeps a writer out while it reads. Opened without locking beside a live writer, a read-only handle recovers the log as far as it had been written at that moment.
Finishing an Interrupted Flush
If a crash interrupted a flush, the journal (<database>-journal) holds it. A
journal is applied only if its header and table verify, it names this database, and
every page image in it matches its checksum. Then all its pages are written in place
and the file is synced. A journal that fails any check is the trace of a crash while
it was being written, before the database file was touched, and is discarded:
applying the images that verify and skipping the rest would recreate the torn image
the journal exists to prevent.
A read-only open applies the journal to its in-memory overlay, so it sees the finished flush without writing the file; the next read-write open applies it to the file.
After this step the file is a whole image, from before the flush or after it.
Opening the Log
A log whose header names a different database is refused. A header that fails its
checksum while its magic, version, frame size and database id are intact was torn in
the middle of a rewrite; it is rebuilt, with its frame count taken from the file's
length and checkpoint_lsn reset to zero, so the whole log is replayed.
Then the end of the log is found. The header's frame count says how many frames were
written, not how many survived. Every frame is checked, and each frame that verifies
says how many frames had been synced when it was written (synced_frames, see
Write-Ahead Log). The largest of those claims divides the
log. A bad frame at or above it belongs to the unsynced tail, which a power cut can
leave in any state: the log is cut back to the frame before it and the header
rewritten. A bad frame below it was synced, and its damage is real: the log is left
exactly as found, for recovery to refuse. A log written entirely by 0.16.0 carries
no claims, and a bad frame in it is damage if any later frame verifies.
A non-empty log is synced before anything new is written after it, since a killed process's frames may still be only in the operating system's cache, and bytes past the frames the header counts are removed.
Two-Phase Recovery
Phase 1: Analysis
Scan the WAL from checkpoint_lsn to understand what happened. Because a
transaction writes all its records at commit and there is only one writer, a
transaction's records are contiguous; a crash can cut the last one short.
| LSN | Record | Transaction | Meaning |
|---|---|---|---|
| 1 | TXN_BEGIN | 1 | Transaction 1's records begin |
| 2 | INSERT | 1 | Transaction 1 modified data |
| 3 | UPDATE | 1 | Transaction 1 modified data |
| 4 | TXN_COMMIT | 1 | Transaction 1 committed |
| 5 | TXN_BEGIN | 2 | Transaction 2's records begin |
| 6 | DELETE | 2 | Transaction 2 modified data |
The process dies while transaction 2 is logging, giving:
| Transaction | State |
|---|---|
| 1 | COMMITTED — has TXN_COMMIT |
| 2 | IN_PROGRESS — no commit or abort |
During analysis, we build:
- Transaction table: State of each transaction (committed, aborted, in-progress)
- Redo list: All data operations that might need to be redone
Phase 2: Redo
Apply committed operations to the database:
For each operation in the redo list:
- Check whether its transaction committed. If not, skip it — the change is discarded.
- Re-execute the operation against the stores (see Logical Redo).
- Continue to the next operation.
Against the log above:
| LSN | Operation | Transaction | Outcome |
|---|---|---|---|
| 2 | INSERT | 1 | Redo — transaction 1 committed |
| 3 | UPDATE | 1 | Redo — transaction 1 committed |
| 6 | DELETE | 2 | Skip — transaction 2 never committed |
Between records, recovery calls the same early flush that commits use, so a long replay does not have to fit in the buffer pool: when half the pool is dirty, the log is synced and the pages are flushed as one image. The log is not emptied until the end, so a crash in the middle of recovery leaves a whole image and the whole log, and the next attempt replays all of it again.
Why No Undo?
Traditional ARIES has three phases: Analysis, Redo, Undo. We skip Undo because of how we structure our system:
Our approach: Keep a transaction's changes out of the stores until commit
- During a transaction, changes live in its in-memory overlay, not in pages
- On commit, the overlay is logged, the commit record is synced, and only then is the overlay applied to the stores (dirtying pages in the buffer pool); the dirty pages reach the file later, in a whole flush
- On crash, an open transaction's overlay is simply lost, and nothing of it was logged as committed or applied
So no flush, early or otherwise, can write an uncommitted change into the file, and after a crash there is nothing of one to reverse. The one trace an uncommitted transaction can leave is a symbol (a label, edge type or property name) it interned, which nothing refers to.
Traditional approach: Apply changes immediately, undo on abort
- Changes written to data pages as transaction runs
- If abort/crash, must read WAL backwards and undo each change
- More complex, but allows larger transactions (not limited by RAM)
For an embedded database like Lattice, the simpler "don't undo" approach works well. The price is that a transaction's overlay must fit in memory.
The Checkpoint Starting Point
Recovery doesn't scan the entire WAL - only from the last checkpoint:
The checkpoint_lsn in the WAL header marks where recovery begins. The Checkpointer
sets it after the flush has written the pages and synced the database file. A
passive checkpoint that finds a dirty page pinned writes nothing and leaves it where
it was (see Checkpointing). A truncate checkpoint
resets the log, and with it checkpoint_lsn, to empty.
A transaction exists for analysis only from its TXN_BEGIN: a commit record whose
begin record lies before the point recovery starts reading belongs to no
transaction, and its records are not redone. That is why a checkpoint refuses to run
while an open transaction has records in the log
(Checkpointing).
Transaction States
During recovery, each transaction can be in one of three states:
| State | Meaning | WAL Record | Action |
|---|---|---|---|
committed | Completed successfully | TXN_COMMIT present | Redo operations |
aborted | A commit failed after logging some records, and was rolled back | TXN_ABORT present | Ignore operations |
in_progress | Crash while the transaction was logging | No commit/abort | Ignore operations |
The distinction between aborted and in_progress is informational - both are handled the same way (ignore their changes).
Record Type Handling
Different WAL records are handled differently:
switch (record.record_type) {
.txn_begin => {
// Track new transaction as in_progress
},
.txn_commit => {
// Mark transaction as committed
},
.txn_abort => {
// Mark transaction as aborted
},
.insert, .update, .delete, .page_write => {
// Data modification - save for redo phase
},
.checkpoint_begin, .checkpoint_end => {
// Informational - no action needed
},
.savepoint, .savepoint_rollback => {
// Track the LSN only; a savepoint rollback is not applied
},
.clr => {
// Compensation Log Record - nothing to do (and never written)
},
}
large_fragment records never reach this switch: the WAL iterator reassembles a
fragmented record into its logical record before handing it to recovery.
Logical Redo
Recovery is logical: it re-executes committed operations through the same stores the database uses, rather than writing page images.
An insert, update or delete record carries a logical payload whose first byte
names the operation (wal_payload.PayloadType):
| Payload | Redo |
|---|---|
node_insert, node_delete, node_update | Node store and label index |
edge_insert, edge_delete, edge_property_update | Edge store |
label_add, label_remove | Node store and label index |
vector_set, vector_remove | Vector index |
stream_append, stream_offset_set, stream_trim | Stream trees |
changefeed_events | Changefeed: a run of compact events, with the names of the symbols they use; the names are interned again and each event stored with the recovered ids. Events below the changefeed's floor, dropped by retention after they were logged, stay dropped, and the file's minimum reader version is raised again |
The database opens recovery with a LogicalRecoveryContext that points at the node
store, edge store, symbol table, label index, stream trees, the page manager and,
when vectors are enabled, the vector index. Labels, edge types and property keys are mostly logged
by name and re-interned through the symbol table, so symbol ids need not match the
session that wrote the log.
Replaying twice is safe
Recovery redoes every committed record from checkpoint_lsn on, whether or not
its effect already reached the database file: every early flush since the last
checkpoint wrote changes that are still in the log, and a flush in the middle of a
commit can have written part of a transaction. Recovery does not know which records
the image reflects, and does not try to.
That works because each record is applied as an assignment of the state it logged, never as a change to whatever is there:
| Record | Applied as |
|---|---|
| node insert | the node exists with exactly the logged labels, their label-index entries, and no properties (its property records follow it in the log) |
| property set or removal, label add or remove | exactly that key or label, and its label-index entry, is set or cleared |
| node or edge delete | the node or edge is absent |
| edge insert | the edge exists with exactly the logged endpoints and type, and no properties |
Replaying one onto a state that already has it changes nothing. Replaying an older record onto a newer state can change something, but the later record is in the log after it and is replayed after it, and the image never runs ahead of the log, since the log is synced before every flush. A record that finds its node or edge missing is accepted only when a later committed record in the same log deletes it, which means the file is from after that delete.
The vector index needed an exception. Inserting a vector the index already holds is a replacement, which unlinks the node from its neighbours and links it again, and doing that for every vector in the log left a graph that searches could no longer cross. Replay now skips a vector write when the index already holds exactly that vector for the node.
Replay errors
A committed record that cannot be replayed fails the open rather than being skipped, since skipping it would open a database missing a change that was acknowledged:
| What recovery meets | The open fails with |
|---|---|
A payload that does not decode, a payload type no release writes, a page_write (page image) record, or a change to a node or edge that is missing and not deleted later in the log | InvalidDatabase (LATTICE_ERROR_CORRUPTION) |
| A store that reports an error while applying a record | IoError |
| Memory running out | OutOfMemory |
| Vector records, with no vector index to replay them into | IoError |
The last case can only arise for a database last written by 0.16.0 whose dimensions cannot be read from its vector pages, since every other database records its index; the CLI recognises it and asks for the dimensions. The one vector record that is skipped is a removal in a file that has never held vectors, which 0.16.0 logged for every deleted node and which has nothing to remove.
Corruption Detection
When a frame fails its checksum, recovery must determine whether this is:
- An unsynced tail - frames a power cut or a kill caught before they were synced (safe to drop: nothing in them was promised)
- Damage to synced data - a frame that was promised durable (unsafe to drop)
Opening the log has already sorted every bad frame into one or the other (see Opening the Log): it cut an unsynced tail off and recorded damage, which recovery reports.
Telling Them Apart
Each frame says how many frames had been synced when it was written. Take the largest such claim among the frames that verify:
Scenario 1 — an unsynced tail
| Frame | Checksum | synced_frames |
|---|---|---|
| 0 | OK | 0 |
| 1 | OK | 1 |
| 2 | Mismatch | |
| 3 | OK | 2 |
| 4 | Mismatch |
The largest claim is 2, and the first bad frame is frame 2, which no frame claims was synced. Frames 2 to 4 were written after the last sync and a power cut left them in any order, frame 3 whole and frames 2 and 4 not. The log is cut back to frames 0 and 1. A kill without a power cut would leave all of them whole; the old rule, which called any bad frame with a good one after it corruption, refused such a database.
Scenario 2 — damage to synced data
| Frame | Checksum | synced_frames |
|---|---|---|
| 0 | OK | 0 |
| 1 | Mismatch | |
| 2 | OK | 2 |
| 3 | OK | 3 |
Frame 2 says two frames had been synced before it, so frame 1 was durable and its
damage is real. Recovery fails with MidLogCorruption, and the open fails with
InvalidDatabase, rather than silently discarding committed data.
A frame verifies only if it holds records. A frame that never reached the disk reads back as zeroes, which would otherwise pass as an empty frame and let recovery read on past it into the whole frames after it, replaying a transaction without the records of the lost frame.
A log written by 0.16.0 carries no claims, and keeps the rule it was written under: a bad frame with any valid frame after it is damage.
Why This Matters
Mid-log corruption is dangerous because the corrupted frame might contain:
- A
TXN_COMMITrecord we can't see - Data modifications needed for consistency
If we skip the corrupted frame and continue, we might:
- Treat a committed transaction as uncommitted (data loss)
- Apply partial transaction state (inconsistency)
By failing on mid-log corruption, we force manual intervention (restore from backup) rather than silently losing data.
Implementation
// At open (WalManager.findLogEnd), over every frame the header counts:
// S = the largest synced_frames among frames that verify (version 3)
// b = the first frame that does not verify
const corrupt = if (any_version3_frame) b < S else valid_frame_after_b;
if (corrupt) wal.damaged_frame = b // recovery returns MidLogCorruption
else truncate the log to b frames // an unsynced tail
A frame that goes bad after the open, while recovery reads it, is judged by the 0.16.0 rule: any frame that verifies after it makes it damage.
A large record is logged as a chain of fragments over several frames. A process killed while writing the chain leaves its first fragments and no commit record. When the record after an unfinished chain belongs to another transaction, the chain is skipped and that record read as itself; a break inside one transaction's chain is still damage.
When an Open Is Refused
Opening refuses, rather than guess, when:
- the log belongs to a different database, or its header is damaged beyond the torn-header case above;
- the log is damaged in frames that had been synced;
- a committed record cannot be replayed (Replay errors);
- a read-only recovery would need more memory than its overlay may hold;
- on a read-write open of a file that does not record its node id counter (one last written by 0.16.0), the node tree cannot be scanned to find the next node id: starting the ids over at 1 would overwrite existing nodes;
- on a read-write open of an existing file, the symbol table cannot be scanned or the edge id counter cannot be read: restarting either would give a new label, edge type or property name the id of an existing one, or a new edge the id of an existing edge.
What Survives What
The guarantee depends on what failed, the sync mode and, on macOS, whether
full_fsync is on (see Durability and the Log).
| Configuration | Process killed | Power lost or OS crash |
|---|---|---|
sync_mode = .full (default) on Linux, or on macOS with full_fsync | Every acknowledged commit survives | Every acknowledged commit survives, if the device honours its flush |
.full on macOS without full_fsync | Every acknowledged commit survives | Not guaranteed: fsync does not flush the drive's cache, so neither the commit nor the ordering the journal relies on is assured |
sync_mode = .normal | Every acknowledged commit survives | Commits since the last sync or checkpoint may be lost, from the end only |
"Acknowledged" means the commit call returned. A commit that was running when the
process died is either wholly present or wholly absent, according to whether its
commit record reached the disk. In .normal mode the database after a power cut
holds a whole number of transactions up to some point no earlier than the last log
sync, none applied in part. In every mode a crash during recovery, a second power
cut included, changes nothing: the next recovery reaches the same state.
Durability and the Log states
the guarantee in full.
Statistics
Recovery returns detailed statistics:
RecoveryStats{
start_lsn: 1000, // Where we started (checkpoint_lsn)
end_lsn: 1523, // Last valid record
records_scanned: 523, // Total records processed
transactions_found: 15, // Distinct transactions
transactions_committed: 12, // Successfully committed
transactions_aborted: 2, // Explicitly aborted
transactions_rolled_back: 1, // In-progress at crash
redo_operations: 156, // Operations redone
duration_ns: 45_000_000, // 45ms
stopped_at_corruption: true, // Hit tail corruption
corrupted_frame: 42, // Frame number with bad checksum
max_txn_id: 27, // Largest transaction id in the log
}
Database.open uses redo_operations (to decide whether to rebuild indexes) and
max_txn_id (to number the new session's transactions) and discards the rest;
nothing reports them to the caller. They are available when you drive
RecoveryManager yourself.
API
This is what Database.open does (simplified):
var rm = RecoveryManager.initWithLogicalContext(allocator, .{
.node_store = &self.node_store,
.edge_store = &self.edge_store,
.symbol_table = &self.symbol_table,
.label_index = &self.label_index,
.stream_trees = self.streamTrees(),
.hnsw_index = if (self.hnsw_index) |*hnsw| hnsw else null,
// Whether the file has ever held vectors (for 0.16.0's stray removals)
.file_has_vectors = has_vector_data,
// Called between records: the early flush
.between_operations = .{ .context = self, .call = relieveBufferPressureHook },
// Whose header a replayed changefeed run raises the reader version in
.page_manager = &self.page_manager,
});
const stats = rm.recover(wal, &self.page_manager) catch |err| switch (err) {
// Damage in synced frames, or a committed record that cannot be applied
error.MidLogCorruption, error.InvalidRecord, error.CorruptedWal => return DatabaseError.InvalidDatabase,
error.OutOfMemory => return DatabaseError.OutOfMemory,
else => return DatabaseError.IoError,
};
recoverDatabase(allocator, &wal, &pm) and RecoveryManager.init also exist, but
they have no logical context: they scan the log and count what they would redo
without changing anything.
Known Limits
- Damage in the newest sync batch reads as a torn tail. Only a frame written after a later sync can vouch that a frame was synced. Damage to the last frames before the most recent sync, with nothing written after them, is cut off as an unsynced tail, and the commits in them are lost without an error.
- A read-only recovery is bounded by memory: 64 MB plus four times the size of the log and journal. Beyond that the read-only open fails, and a read-write open is needed.
- What the power-loss tests do not reach. The power-loss simulation (see Running Tests) drives the Zig API on an in-memory disk model. Backup, restore and replication use the filesystem directly, outside the model, and the C API layer, Cypher and streams are not in its workload.
Summary
| Concept | Purpose |
|---|---|
| Journal | Finish or discard an interrupted flush, so the file is one whole image |
| Unsynced-tail trim | Cut frames written after the last sync off the log at open, if any is bad |
| Analysis phase | Determine transaction outcomes |
| Redo phase | Apply committed operations |
| checkpoint_lsn | Recovery starting point |
| Transaction states | committed, aborted, in_progress |
| Checksum verification | Detect corruption/partial writes |
| Unsynced tail | Frames a crash caught before their sync, safe to drop |
| Synced damage | Real corruption, fail to prevent data loss |
synced_frames | Each frame's claim of how much was synced, which tells the two apart |
| Read-only recovery | The same recovery over an in-memory overlay, writing nothing |
| No Undo | Uncommitted changes stay in the overlay, never applied |
| Logical redo | Committed records applied as assignments through the stores; safe to repeat, and a record that cannot be applied refuses the open |
| Checkpoint at open | Empty the log once recovery is done |
Recovery transforms a potentially inconsistent crash state into a consistent database by leveraging the WAL as the authoritative record of committed transactions.
Graph Storage
The Property Graph Model
Lattice implements a Labeled Property Graph - the same model used by Neo4j, Amazon Neptune, and other graph databases. It consists of:
Node:
- id: unique identifier (u64)
- labels: set of strings (e.g., "Person", "Employee")
- properties: key-value pairs (e.g., name: "Alice", age: 30)
Edge:
- id: stable unique identifier (u64)
- source: node id
- target: node id
- type: string (e.g., "KNOWS", "WORKS_AT")
- properties: key-value pairs (e.g., since: 2020)
This model is expressive enough to represent almost any domain while remaining simple to query and traverse.
The Storage Challenge
How do you store a graph in a B+Tree (which is fundamentally a key-value store)?
The key insight: decompose the graph into multiple B+Trees, each optimized for a specific access pattern.
The core graph uses these six trees. The database keeps further trees beside them for property indexes, full-text search, vectors and streams; the Summary lists the graph-related ones.
String Interning (Symbol Table)
Graphs have lots of repeated strings: label names, property keys, edge types. Storing "Person" thousands of times wastes space. Instead, we intern strings.
| Interned string | Symbol ID |
|---|---|
"Person" | 1000 |
"Employee" | 1001 |
"name" | 1002 |
"KNOWS" | 1003 |
Storing "Person" costs 6 bytes every time it appears; storing the symbol 1000
costs 2. On a graph with millions of nodes carrying a handful of labels each, that
is most of the property storage.
The Symbol Table uses two B+Trees:
SYMBOLS (forward): SYMBOLS_REVERSE:
"Person" → 1000 1000 → "Person"
"Employee" → 1001 1001 → "Employee"
"name" → 1002 1002 → "name"
"KNOWS" → 1003 1003 → "KNOWS"
Symbol IDs are u16 (0-65535):
- 0: Reserved (null)
- 1-999: Reserved for system use
- 1000-65535: User-defined symbols
The next ID to hand out is found when the database opens, by scanning the reverse tree for the highest one in use. If that scan fails when an existing database is opened for writing, the open fails: starting again at 1000 would give a new name the ID of an existing one, and the two names would become one.
API
var symbols = SymbolTable.init(allocator, &forward_tree, &reverse_tree);
// Intern a string (creates if not exists, returns existing if present)
const person_id = try symbols.intern("Person"); // 1000
// Lookup without creating
const id = try symbols.lookup("Person"); // 1000
// or
try symbols.lookup("Unknown"); // SymbolError.NotFound
// Resolve ID back to string
const name = try symbols.resolve(person_id); // "Person"
defer symbols.freeString(name); // Must free allocated string
Node Storage
Nodes are stored in a B+Tree with simple u64 keys:
NODES B+Tree:
Key: node_id (u64, little-endian)
Value: NodeData (serialized)
NodeData Format
NodeData
| Field | Type | Notes |
|---|---|---|
num_labels | u16 | |
labels | u16 × num_labels | Interned symbol ids |
num_properties | u16 | |
properties | PropertyEntry × num_properties |
PropertyEntry
| Field | Type | Notes |
|---|---|---|
key_id | u16 | Interned string id |
value_type | u8 | See the table below |
value_data | variable | Encoding depends on value_type |
Value types
| Code | Type | Encoding |
|---|---|---|
| 0 | Null | No payload |
| 1 | Bool | 1 byte, 0 or 1 |
| 2 | Int64 | 8 bytes, little-endian |
| 3 | Float64 | 8 bytes, IEEE 754 |
| 4 | String | u32 length, then bytes |
| 5 | Bytes | u32 length, then bytes |
| 6 | Vector | u32 length, then f32 values |
| 7 | List | u32 length, then nested values |
| 8 | Map | u32 length, then key/value entries |
Node records are serialized into heap buffers sized from the exact labels and properties being written. The old fixed 4 KiB serialization buffer is no longer part of the node path; large string and bytes properties are handed to the B+Tree, which stores them inline or through overflow pages according to the entry-size rules in B+Tree.
API
var store = NodeStore.init(allocator, &nodes_tree);
// Create a node
const labels = [_]SymbolId{ person_id, employee_id };
const properties = [_]Property{
.{ .key_id = name_id, .value = .{ .string_val = "Alice" } },
.{ .key_id = age_id, .value = .{ .int_val = 30 } },
};
const node_id = try store.create(&labels, &properties);
// Get a node
var node = try store.get(node_id);
defer node.deinit(allocator);
// Check existence (can fail with an I/O error, so it needs `try`)
if (try store.exists(node_id)) { ... }
// Update a node
try store.update(node_id, &new_labels, &new_properties);
// Delete a node
try store.delete(node_id);
Node ids
Node ids come from a counter that never goes down. The database keeps it in the file header and writes it with every flush, in the same header image as the node tree pages it describes, so opening a database reads it rather than scanning the node tree, and the id of a committed node is never handed out again, even after the node is deleted. Ids handed out by a transaction that rolled back, or that had not committed when the process died, can be handed out again. A file last written by 0.16.0 has no stored counter; the first read-write open finds the highest id with one scan and stores the counter from then on. If that scan fails, the open fails rather than start the ids again at 1.
Deleting a node that has relationships
NodeStore.delete removes the node record only. The rule that a node with
relationships cannot be deleted lives one level up, in the database:
Database.deleteNode (C lattice_node_delete) refuses a node that has any
relationship the transaction can see, its own uncommitted ones included, with
NodeHasRelationships (LATTICE_ERROR_HAS_RELATIONSHIPS), and
detachDeleteNode (lattice_node_detach_delete) deletes the relationships with
the node. Cypher's DELETE and DETACH DELETE go through the same two calls. The
check is one range probe over the node's edge keys, plus a look at the node's own
pending edges in the transaction. Creating an edge likewise checks that both its
ends exist as the transaction sees them, a key probe each, and fails with
NotFound (LATTICE_ERROR_NOT_FOUND) otherwise. So no committed edge points at a
node that does not exist.
Edge Storage
Edges are more complex because we need efficient traversal in both directions and stable identity for properties, recovery, and parallel edges:
- "Find all people Alice knows" (outgoing)
- "Find all people who know Alice" (incoming)
- "Set this edge's properties after creation" (stable edge ID)
Traversal Tree Plus Edge-ID Index
For edge (Alice)-[:KNOWS]->(Bob), the traversal tree stores two keys and
the payload is stored once in an edge-ID index:
Entry 1 (Outgoing from Alice):
Key: (Alice, OUTGOING, KNOWS, Bob, edge_id)
Value: empty
Entry 2 (Incoming to Bob):
Key: (Bob, INCOMING, KNOWS, Alice, edge_id)
Value: empty
Payload entry:
Key: edge_id
Value: serialized source, target, type, and properties
This keeps traversal efficient in either direction without duplicating large
edge properties. The stable edge_id lets callers update properties by ID and
lets the storage layer restore or delete the exact edge during WAL recovery.
Because the traversal keys carry no payload, changing an edge's properties
rewrites only its payload entry (EdgeStore.replaceProperties, one B+Tree
replace); the traversal keys are left alone. That is so on commit, for direct
writes, for an undo and for a replayed log record. Setting one property on each
of 20,000 edges in one transaction went from about 6.6 µs to 3.6 µs an edge,
commit included.
Edge-ID Index
The edge-ID tree is a separate B+Tree from the traversal tree. Unlike the traversal keys, its keys are little-endian u64 edge IDs, because nothing needs them in ID order: lookups are by exact ID, and a walk of the whole tree comes back in a stable order that is not numeric (edge 256 before edge 2).
| Key | Value |
|---|---|
0 (EDGE_ID_META_KEY) | next_edge_id: u64, little-endian |
edge_id (≥ 1) | Edge payload, see below |
Key 0 is reserved: it stores the next edge ID to hand out, so IDs survive a reopen and are never reused. Edge IDs therefore start at 1. If the metadata entry is missing, the store derives it from the largest edge ID in the tree and writes it back. If the tree cannot be read when an existing database is opened for writing, the open fails rather than counting from 1 again, which would hand out the IDs of existing edges.
Edge payload (all integers little-endian)
| Field | Type | Notes |
|---|---|---|
source | u64 | Source node id |
target | u64 | Target node id |
edge_type | u16 | Interned edge type |
num_properties | u16 | |
properties | PropertyEntry × num_properties | Same encoding as node properties |
Key Format
Edge keys are 27 bytes, stored big-endian so that byte order matches sort order
and a prefix scan on source_id returns all edges out of a node.
| Offset | Size | Field |
|---|---|---|
| 0–7 | 8 B | source_id: u64 |
| 8 | 1 B | direction: u8 |
| 9–10 | 2 B | type_id: u16 — interned edge type |
| 11–18 | 8 B | target_id: u64 |
| 19–26 | 8 B | edge_id: u64 |
direction | Meaning |
|---|---|
| 0 | Outgoing — source → target |
| 1 | Incoming — target ← source |
Big-endian encoding ensures keys sort correctly for range scans:
- All edges from node X are contiguous
- Within that, all outgoing edges are together
- Within that, edges of same type are together
- Within a source/type/target tuple, parallel edges remain distinct by edge ID
Why This Key Order?
The key (source, direction, type, target) is optimized for common queries:
Query: "All outgoing edges from Alice"
Scan: (Alice, 0, *, *)
Keys are contiguous!
Query: "All KNOWS edges from Alice"
Scan: (Alice, 0, KNOWS, *)
Even more specific prefix!
Query: "Does Alice know Bob?"
Prefix scan: (Alice, 0, KNOWS, Bob, *)
Returns the first matching edge ID, if present
Large edge properties use the same heap serialization and B+Tree overflow path
as node properties. The store checks whether the serialized edge payload can be
represented before replacing an existing edge-ID entry, so oversized updates
return ValueTooLarge without deleting the previous edge record.
API
var store = EdgeStore.init(allocator, &edges_tree, &edge_id_tree);
// Create an edge
const properties = [_]Property{
.{ .key_id = since_id, .value = .{ .int_val = 2020 } },
};
const edge_id = try store.createAndGetId(alice_id, bob_id, knows_id, &properties);
// Get an edge (the lowest edge ID among parallel edges; use getById for an exact edge)
var edge = try store.get(alice_id, bob_id, knows_id);
defer edge.deinit(allocator);
// Check existence
if (store.exists(alice_id, bob_id, knows_id)) { ... }
// Delete an edge (removes both outgoing and incoming entries)
try store.delete(alice_id, bob_id, knows_id);
// Iterate all outgoing edges from a node
var iter = try store.getOutgoing(alice_id);
defer iter.deinit();
while (try iter.next()) |e| {
var edge = e; // deinit needs a mutable Edge
defer edge.deinit(allocator);
// Process edge...
}
// Iterate incoming edges
var incoming = try store.getIncoming(bob_id);
defer incoming.deinit();
// Filter by edge type
var knows_edges = try store.getOutgoingByType(alice_id, knows_id);
defer knows_edges.deinit();
// Count edges without allocating
const out_count = try store.countOutgoing(alice_id);
const in_count = try store.countIncoming(bob_id);
// Property updates use the stable edge ID through the database layer
try db.setEdgePropertyById(null, edge_id, "since", .{ .int_val = 2020 });
The C API exposes typed traversal with a caller-provided limit:
lattice_edge_get_outgoing_by_type(txn, alice_id, "KNOWS", 100, &edges);
lattice_edge_get_incoming_by_type(txn, bob_id, "KNOWS", 100, &edges);
For these APIs, limit == 0 means unlimited. The limit is applied while
collecting visible edge references, before edge type strings are materialized
for the result handle.
lattice_edge_scan(txn, edge_type_or_null, limit, &edges) walks native edge
identities once via the edge-ID index. It is intended for administrative work
such as index rebuilds, consistency checks, and export jobs, not for hot-path
graph expansion. Use node-local traversal for request-path graph walks.
Label Index
For queries like MATCH (n:Person), we need to find all nodes with a given label efficiently. The Label Index provides this.
LABEL_INDEX B+Tree:
Key: (label_id: u16, node_id: u64) - big-endian
Value: empty (existence only)
How It Works
When creating node Alice with labels [Person, Employee]:
Insert: (Person, Alice) → empty
Insert: (Employee, Alice) → empty
Query "all Person nodes":
Range scan: (Person, 0) to (Person, MAX)
Returns: Alice, Bob, Carol, ...
API
var index = LabelIndex.init(allocator, &label_tree);
// Add labels when creating a node
try index.addLabels(&[_]SymbolId{ person_id, employee_id }, node_id);
// Check if node has a label
if (index.hasLabel(person_id, node_id)) { ... }
// Remove a label from a node
try index.remove(person_id, node_id);
// Get all nodes with a label (allocates result slice)
const person_nodes = try index.getNodesByLabel(person_id);
defer allocator.free(person_nodes);
for (person_nodes) |node_id| {
// Process each Person node...
}
// Lazy iteration (memory-efficient for large result sets)
var iter = try index.iterNodesByLabel(person_id);
defer iter.deinit();
while (try iter.next()) |node_id| {
// Process one node at a time...
}
// Count nodes without allocating
const person_count = try index.countNodesByLabel(person_id);
Property Indexes
An explicit index on a label's (or a relationship type's) property lives in three B+Trees: a catalog of declarations, and one entry tree each for nodes and edges.
| Tree | Key | Value |
|---|---|---|
| Catalog | kind (1 node, 2 edge), scope id u16 BE, property id u16 BE | encoding: empty = digest, [1] = ordered, [2] = ordered and dense |
| Node / edge entries | scope id u16 BE, property id u16 BE, encoded value, entity id u64 BE | empty |
Indexes created by this release key values in an ordered encoding, whose
byte order is ORDER BY's order, so a range of values is a range of keys. A
label's index is also dense: every node with the label has an entry, the
ones without the property under 0xF0, after every value, where ORDER BY
puts nulls. So the index read forward or backward is the label's nodes in
ascending or descending order, nulls included; a node created without the
property costs one more key per such index, about 0.1 to 0.2 µs (100,000
nodes added to 100,000 with three such indexes: 3.0 to 3.2 µs a node with
indexes that leave them out, 3.5 µs with these). A
relationship type's index holds only the edges with the property, and an index
whose keys hold no nulls is used for ranges and equality only. The tags:
| Tag | Values | Bytes after the tag |
|---|---|---|
0x10 | lists, maps, vectors | SHA-256 digest (equality only) |
0x20 | byte arrays | as strings |
0x30 | strings | the first 128 bytes, 0x00 written 00 FF, then 00 00 if that was all of it or 00 01 if the value is longer |
0x40 | booleans | one byte |
0x50 | integers and floats | the largest double not above the value, as 8 bytes that sort like it (-0 as +0), then a u16 BE remainder for integers a double cannot hold |
0x51 | NaN | nothing; after every number |
0xF0 | null (property missing) | nothing; dense indexes only |
So 3 and 3.0 share a key, and an integer and a float compare exactly, as
the query engine compares them. A truncated string or a digest stands for
several values; lookups re-read the entity and compare, so neither can produce
a wrong row. Indexes created by 0.16.0 have an empty catalog value and key a
SHA-256 digest of the value: they answer equality only, and keep doing so, until
rebuilt. Database.upgradePropertyIndexes (lattice compact --upgrade-indexes) rebuilds each declaration whose catalog value is not the
current encoding for its kind (a node index created by a development build
between the two is ordered but not dense): it raises min_reader_version,
removes the declaration's entries, writes them again from the label's nodes or
the type's edges, then stores the new encoding in the catalog, all in one
step, so a crash leaves the old index or the new one.
Creating an ordered index raises the file header's min_reader_version to 4
before the first key is written, so 0.16.0, which would read the keys as
digests and find nothing, refuses to open the file. A file without one stays at
min_reader_version 3. The raise is not undone when the index is dropped.
Declarations are cached in memory (up to 32 per kind), so a write does not read
the catalog. A transaction's own staged nodes and edges are found by indexed
value through a per-transaction table (OverlayLookup), filled on the first
lookup for a declaration and kept up to date by later staged writes, so a
lookup inside a transaction that staged 100,000 nodes costs about 1 µs rather
than a walk of all of them.
How queries use these indexes is in Query Execution.
Putting It Together
A complete graph operation involves multiple B+Trees:
Creating node Alice:Person with name="Alice":
1. Symbol Table:
- intern("Person") → 1000
- intern("name") → 1001
2. Node Store:
- Allocate node_id = 1
- Serialize: [1 label: 1000][1 prop: 1001="Alice"]
- Insert: 1 → serialized_data
3. Label Index:
- Insert: (1000, 1) → empty
Creating edge (Alice)-[:KNOWS]->(Bob):
1. Symbol Table:
- intern("KNOWS") → 1002
2. Edge Store:
- Allocate edge_id = 1
- Insert traversal keys: (1, OUT, 1002, 2, 1) → empty and (2, IN, 1002, 1, 1) → empty
- Insert payload: 1 → serialized edge data and properties
- Update edge-ID key 0: next_edge_id = 2
Performance Characteristics
| Operation | Complexity | Notes |
|---|---|---|
| Create node | O(log n) | One B+Tree insert + label index inserts |
| Get node | O(log n) | Single B+Tree lookup |
| Delete node | O(log n) | One B+Tree delete |
| Create edge | O(log n) | Two traversal inserts + one edge-ID payload insert + next_edge_id update |
| Get edge | O(log n + k) | Prefix scan to edge ID, then payload lookup |
| Delete edge | O(log n) | Two traversal deletes + one edge-ID payload delete |
| Check label | O(log n) | Single B+Tree lookup |
| Remove label | O(log n) | Single B+Tree delete |
| All nodes with label | O(log n + k) | Range scan, k = result count |
| All edges from node | O(log n + k) | Range scan, k = edge count |
Where n = total items in the respective B+Tree.
Current Limitations
The stores described here have no notion of transactions. Isolation is provided above them by the database layer (a single writer plus per-transaction overlays; see Transaction Manager); this chapter only describes the underlying graph-storage structures.
- Property updates rewrite records: No in-place partial property update at the storage-record level
- No index from relationship type to edge. The header's sixteen tree roots
are all in use, and an index kept in the label tree would be read by 0.16.0
as labels and left stale by its writes, so every file with an edge would have
to be closed to 0.16.0; a prototype also cost 7% on edge creation. A pattern
that starts from a type,
()-[r:KNOWS]->(), walks the edge-ID index once instead (66 ms to 20 ms for a count over 1,000,000 edges). - The edge-ID index walks in a non-numeric order (its keys are little-endian), and that is the row order of a type-only pattern.
Future Enhancements
- Edge type index, if a file format change frees a tree root for it.
Summary
| Component | B+Tree Key | Purpose |
|---|---|---|
| Symbol Table (forward) | string | String → ID mapping |
| Symbol Table (reverse) | symbol_id | ID → String mapping |
| Node Store | node_id | Node data storage |
| Edge Store | (src, dir, type, tgt, edge_id) | Traversal keys |
| Edge ID Index | edge_id | Stable edge identity and property payload |
| Label Index | (label_id, node_id) | Label-based queries |
| Property Index Catalog | (entity_kind, scope_id, property_id) | Durable explicit index definitions |
| Node Property Index | (scope_id, property_id, encoded value, node_id) | Indexed node-property equality, range and prefix lookup |
| Edge Property Index | (scope_id, property_id, encoded value, edge_id) | Indexed edge-property lookup |
The graph storage layer transforms B+Trees into a full property graph database through careful key design, stable edge IDs, and a traversal/payload split for edges.
Vector Search
Overview
Lattice provides approximate nearest neighbor (ANN) search using the HNSW (Hierarchical Navigable Small World) algorithm. This enables semantic search over high-dimensional embedding vectors—a core requirement for AI/RAG applications.
Embedding Generation
Lattice uses a bring your own embeddings approach by default. You can:
- Generate embeddings externally and pass them directly
- Use the optional
EmbeddingClientto call HTTP embedding APIs
Option 1: Bring Your Own Embeddings
// You generate embeddings however you want
const embedding: []const f32 = your_embedding_function("Hello world");
// Insert directly into HNSW index
try hnsw_index.insert(doc_id, embedding);
Option 2: HTTP Embedding Client
The EmbeddingClient calls external HTTP endpoints to generate embeddings. It's disabled by default—you must explicitly create and configure it.
const lattice = @import("lattice");
// Ollama (local) - simplest config
var client = lattice.EmbeddingClient.init(allocator, .{
.endpoint = "http://localhost:11434/api/embeddings",
});
defer client.deinit();
// Generate embedding
const vector = try client.embed("Hello, world!");
defer allocator.free(vector);
Configuration Options
const config = lattice.EmbeddingConfig{
// Required: HTTP endpoint URL
.endpoint = "http://localhost:11434/api/embeddings",
// Model name (default: "nomic-embed-text")
.model = "nomic-embed-text",
// API format: .ollama (default) or .openai
.api_format = .ollama,
// Optional API key for authenticated endpoints
.api_key = null,
// Request timeout in milliseconds (default: 30000).
// Not currently enforced: the client does not read this field.
.timeout_ms = 30_000,
};
Supported API Formats
| Format | Request | Response |
|---|---|---|
.ollama | {"model": "...", "prompt": "..."} | {"embedding": [...]} |
.openai | {"model": "...", "input": "..."} | {"data": [{"embedding": [...]}]} |
Examples
Ollama (local)
var client = EmbeddingClient.init(allocator, .{
.endpoint = "http://localhost:11434/api/embeddings",
.model = "nomic-embed-text",
});
OpenAI
var client = EmbeddingClient.init(allocator, .{
.endpoint = "https://api.openai.com/v1/embeddings",
.model = "text-embedding-3-small",
.api_format = .openai,
.api_key = "sk-...",
});
Local OpenAI-compatible (llama.cpp, vLLM, etc.)
var client = EmbeddingClient.init(allocator, .{
.endpoint = "http://localhost:8080/v1/embeddings",
.model = "local-model",
.api_format = .openai,
});
HNSW Index
HNSW (Hierarchical Navigable Small World) is a graph-based algorithm for approximate nearest neighbor search. It achieves O(log n) search complexity with high recall.
How HNSW Works
- Upper layers have exponentially fewer nodes (sparse)
- Search starts at top layer, greedily descends
- Layer 0 uses beam search for final candidates
- Each node maintains bidirectional connections to neighbors
Configuration
const config = lattice.HnswConfig{
.dimensions = 384, // Required: vector length (1-4096)
.m = 16, // Connections per node (layers 1+)
.m_max0 = 32, // Connections at layer 0
.ef_construction = 200, // Search width during insert
.ef_search = 64, // Search width during query
.ml = 1.0 / @log(2.0), // Level multiplier, ≈ 1.4427 (the default)
.metric = .cosine, // Distance metric
};
| Parameter | Default | Description |
|---|---|---|
dimensions | none (required) | Vector length, 1 to 4096 |
m | 16 | Max connections per node on layers 1+ (higher = better recall, more memory) |
m_max0 | 32 | Max connections at layer 0 (typically 2×m) |
ef_construction | 200 | Beam width during insert (higher = better graph quality) |
ef_search | 64 | Beam width during search (higher = better recall, slower) |
ml | 1/ln 2 ≈ 1.4427 | Level multiplier; a new node's top layer is floor(-ln(U) × ml) |
metric | .cosine | Distance metric: .euclidean, .cosine, .inner_product |
With ml = 1/ln 2, about half of all vectors reach layer 1 or higher, a
quarter reach layer 2, and so on. (The HNSW paper suggests ml = 1/ln M, which
for M = 16 is ≈ 0.36 and puts about 6% of vectors above layer 0.)
m and m_max0 are capped at 64: neighbour lists are read into fixed 64-entry
buffers during insert and search, so init lowers a larger value to 64. With
m_max0 = 2 × m, that makes 32 the largest m that keeps the usual ratio.
What a database lets you choose. A database builds its index from its
configuration when the index is created: dimensions, metric, m (2 to 32,
with m_max0 = 2 × m) and ef_construction (1 to 4096), defaulting to cosine,
16, 32 and 200. In Zig these are DatabaseConfig.vector_dimensions,
vector_metric, vector_m and vector_ef_construction; the C API's
lattice_open_options_v5, the bindings and lattice create
(--vector-metric=cosine|euclidean|dot_product, --vector-m, --vector-ef-construction)
pass the same values.
The file's header records all five from the moment the index exists, and every
later open builds the index from what the file records, whatever the options say,
so a database with vectors opens, and recovers its log, without being told its
dimensions. An option that contradicts the file (a different dimension count,
metric, m or ef_construction) is refused with VectorConfigMismatch
(LATTICE_ERROR_CONFIG_MISMATCH) before anything is read, rather than reading the
pages with the wrong layout. None of them can be changed afterwards: m decides
the layout of the index's pages and the metric what its distances mean. To change
them, export the database and import it into one created with the new settings.
A file written by 0.16.0 has no such record. Its index can only be the one 0.16.0
built (cosine, 16, 32, 200), so the dimension count is read from its first vector
page, and the record is written at the first read-write open. An index whose metric
is not cosine, or whose m is not 16, marks the file as needing a newer reader,
and 0.16.0 refuses to open it.
The one setting exposed per query is ef_search, as the ef_search argument of
lattice_vector_search (0 means the default of 64) and the equivalent binding
parameters.
API Usage
const lattice = @import("lattice");
// `buffer_pool` is a *lattice.BufferPool set up by the caller.
// Initialize vector storage (pages are owned by the buffer pool; no deinit)
var vector_storage = try lattice.VectorStorage.init(allocator, buffer_pool, 384);
// Initialize HNSW index
var hnsw = lattice.HnswIndex.init(allocator, buffer_pool, &vector_storage, .{
.dimensions = 384,
.metric = .cosine,
.ef_search = 100,
});
defer hnsw.deinit();
// Insert vectors
try hnsw.insert(1, embedding1);
try hnsw.insert(2, embedding2);
try hnsw.insert(3, embedding3);
// Search for 10 nearest neighbors
const results = try hnsw.search(query_vector, 10, null);
defer hnsw.freeResults(results);
for (results) |result| {
std.debug.print("ID: {}, Distance: {d:.4}\n", .{ result.node_id, result.distance });
}
search(query, k, ef_override) returns up to k results ordered by
distance; pass a value for ef_override to change the beam width for one
query. The beam is never narrower than k: the search uses max(ef, k)
(capped at 65535), so asking for more neighbours than ef_search still returns
k of them.
The index itself accepts any f32 values, so that recovery can replay a log
written by an older release. The database rejects a vector with a NaN or
infinite component, whether stored or used as a query, with InvalidArgument
(LATTICE_ERROR_INVALID_ARG through the C API): such a value makes every
distance to it NaN or infinite and breaks the ordering the search relies on.
insert and remove are all or nothing. Every neighbour-list write records the
list's previous contents, and a failure part way (out of memory, a full buffer
pool, an I/O error) puts the lists, the node map entry, the entry point, the top
layer and the vector count back as they were.
Distance Metrics
| Metric | Formula | Best For |
|---|---|---|
.euclidean | √Σ(aᵢ - bᵢ)² | General purpose |
.cosine | 1 - (a·b)/(‖a‖‖b‖) | Text embeddings (normalized) |
.inner_product | -Σ(aᵢ × bᵢ) | When vectors are pre-normalized |
Everywhere outside the index itself the third metric is called dot_product:
DatabaseConfig.vector_metric = .dot_product, --vector-metric=dot_product,
lattice info, LATTICE_VECTOR_METRIC_DOT_PRODUCT, and the bindings' "dot_product",
VectorMetricDotProduct and DOT_PRODUCT. The HNSW index's own DistanceMetric keeps
the name .inner_product it had in 0.16.0. Smaller is nearer under all three, so
the inner product is negated, and its distances can be negative. For text
embeddings from most models (OpenAI, Cohere, etc.), use .cosine.
A database's search, Cypher's <=> (including <=> between two literal lists),
and the scoring of vectors a transaction has set but not yet committed all use the
metric the file records; a database without a vector index measures <=> with
cosine. Under .euclidean and .inner_product vectors are stored and read back as
given.
With .cosine, the index normalizes each vector before storing it and
normalizes each query, then computes the distance as 1 - a·b. The index's
copy of a vector is therefore its unit-length version, and it is the only copy
the file keeps: a committed vector reads back normalised (n.embedding in
Cypher, getNodeVectorInTxn in Zig). A vector a transaction has set but not yet
committed is scored the same way, normalised on both sides, so it ranks among
committed results on the same scale.
Vector Storage
Vectors are stored in pages managed by the buffer pool, separate from the HNSW graph structure.
Vector pages use a 4096-byte layout. Each starts with the common 8-byte page header, followed by a 16-byte vector header (all integers little-endian):
| Offset | Size | Field |
|---|---|---|
| 0–7 | 8 B | Common page header: page_type = 0x04 (vector_data), flags, reserved, checksum |
| 8–9 | 2 B | dimensions: u16 |
| 10–11 | 2 B | vector_count: u16 — records on this page |
| 12–15 | 4 B | bytes_per_vector: u32 — record size |
| 16–19 | 4 B | next_page: u32 — next vector page in the chain (0 if none) |
| 20–23 | 4 B | Layout marker: 0 = inline, 0x564F4631 ("VOF1") = overflow |
| 24 → | variable | Records |
Vectors up to 4096 dimensions are supported. Vectors that fit in one page use
the inline layout: each record is [vector_id: u64][f32 × dimensions], and a
page holds (4096 - 24) / (8 + 4 × dimensions) of them. That covers up to 1016
dimensions. Larger embeddings use a compact head record in the vector page:
[vector_id: u64][first_overflow_page: u32][reserved: u32]
The f32 payload is stored across linked overflow pages (page type overflow),
each with an 8-byte [next_page: u32][bytes_used: u32] header after the common
header, leaving room for 1020 floats per page. Common embedding sizes such as
1536, 3072, and 4096 dimensions therefore persist normally; they just span
multiple pages.
Vectors per page depends on dimensions:
- 384-dim (1544-byte record): 2 vectors/page
- 768-dim (3080-byte record): 1 vector/page
- 1536-dim (6144 bytes): head record plus 2 overflow pages
- 3072-dim (12288 bytes): head record plus 4 overflow pages
- 4096-dim (16384 bytes): head record plus 5 overflow pages
The graph itself is stored apart from the vectors:
- Neighbour lists live in connection-pool pages (page type
hnsw_layer). Nodes are grouped by their top layer, and each group's pages hold fixed-size slots with room form_max0neighbours at layer 0 andmat each layer above. - The node registry maps each vector ID to its top layer, its vector
location and its connection slot. It is kept in memory while the database is
open and written to a dedicated B+Tree (
hnsw_node_tree), together with the entry point and layer count, before every flush of the buffer pool: at each checkpoint, atsyncand close, and at the early flushes a large transaction triggers. So the file never holds vector pages newer than the registry that describes them. A save writes only the entries added, changed or removed since the last one (the whole registry after a rebuild). On open the registry is loaded from that tree and validated; if the tree is missing or fails validation, the index is rebuilt from the stored vectors. The old graph's connection pages are freed first and the rebuilt graph reuses them, so a rebuild does not grow the file. - Free vector records are kept in an in-memory list, built by one walk of the vector page chain the first time a store needs it, so storing a vector reuses a deleted record without scanning the chain.
Performance Characteristics
| Operation | Complexity | Notes |
|---|---|---|
| Insert | O(log n) | Builds graph connections |
| Search (k-NN) | O(log n) | Independent of k for small k |
| Delete | Local, plus an occasional full pass | Repairs the removed vector's neighbours (see below) |
| Memory | O(n × m × layers) | ~1KB per vector at m=16 |
Removing a vector, which includes replacing one, finds the nodes that link to it through its own neighbour lists. Each drops the link and, if that leaves room, takes the nearest of the removed node's other neighbours that passes the same diversity rule as neighbour selection. Links from nodes the removed one had pruned from its own lists cannot be found that way; those ids are remembered and dropped in one pass over every list before the next save, or sooner once they reach about 3% of the index, or before the same id is inserted again. Search skips ids that are no longer in the index, so a saved graph never names a missing one.
Tuning Guidelines
Through a database, ef_search is the only knob once the index exists; m and
ef_construction are chosen when it is created:
For higher recall:
- Increase
ef_search(e.g., 100-200)
For faster search:
- Decrease
ef_search(e.g., 32) - Accept lower recall
A k larger than ef_search widens the beam to k on its own, so there is no
need to raise ef_search just to get more results.
When you create the database, or build an HnswIndex directly, you can also
raise ef_construction (e.g., 400) for a better-connected graph, or raise m up
to 32 (with m_max0 up to 64; see Configuration).
Complete Example
This uses the index directly, below the database layer. Opening the
PageManager is left out; page_manager is a *lattice.PageManager.
const std = @import("std");
const lattice = @import("lattice");
pub fn main() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Setup storage (abbreviated): a 4 MiB buffer pool over an open PageManager
var buffer_pool = try lattice.BufferPool.init(allocator, page_manager, 4 * 1024 * 1024);
defer buffer_pool.deinit();
// Initialize embedding client (optional)
var embedder = lattice.EmbeddingClient.init(allocator, .{
.endpoint = "http://localhost:11434/api/embeddings",
});
defer embedder.deinit();
// Initialize vector storage and HNSW index
var vector_storage = try lattice.VectorStorage.init(allocator, &buffer_pool, 384);
var hnsw = lattice.HnswIndex.init(allocator, &buffer_pool, &vector_storage, .{
.dimensions = 384, // must match the embedding model's output
.metric = .cosine,
});
defer hnsw.deinit();
// Index some documents
const docs = [_][]const u8{
"Zig is a systems programming language",
"Rust focuses on memory safety",
"Go emphasizes simplicity and concurrency",
};
for (docs, 0..) |doc, i| {
const embedding = try embedder.embed(doc);
defer allocator.free(embedding);
try hnsw.insert(i, embedding);
}
// Search
const query_embedding = try embedder.embed("memory safe language");
defer allocator.free(query_embedding);
const results = try hnsw.search(query_embedding, 3, null);
defer hnsw.freeResults(results);
for (results) |result| {
std.debug.print("Doc {}: distance {d:.4}\n", .{ result.node_id, result.distance });
}
}
SIMD-Optimized Distance Functions
Distance calculations use Zig's @Vector for portable SIMD acceleration. This provides 4-8x speedup over scalar implementations for typical embedding dimensions (384, 768, 1536).
// All distance functions are SIMD-optimized
const dist = lattice.vector.distance.euclideanDistance(vec_a, vec_b);
const cos_dist = lattice.vector.distance.cosineDistance(vec_a, vec_b);
const ip_dist = lattice.vector.distance.innerProductDistance(vec_a, vec_b);
// Additional utilities
const dot = lattice.vector.distance.dotProduct(vec_a, vec_b);
const magnitude = lattice.vector.distance.norm(vec);
lattice.vector.distance.normalize(vec); // in-place
Implementation details:
- Processes 8 floats at a time (AVX-256 compatible)
- The dot product and squared Euclidean distance unroll four SIMD steps into four independent accumulators, so long vectors are not held to the latency of one chain of adds; fused multiply-add is not used
- Handles non-aligned remainder with scalar fallback
- Works on ARM NEON (128-bit, processed as 2×4)
Current Limitations
- Fixed index settings per database: the metric,
mandef_constructionare chosen when the index is created and cannot be changed for it; onlyef_searchcan be set per query. Changing them means exporting and importing into a new database. - Registry saved at flush: the node registry is written to
hnsw_node_treebefore each flush of the buffer pool, not on every insert. If it is missing or invalid on open, the whole graph is rebuilt from the stored vectors. - Cosine reads back normalised: the file keeps only the unit-length copy of each vector, so the original magnitude is not recoverable.
- Filtered search is exact or approximate by size: Cypher
<=>searches among the pattern's candidate nodes (Database.vectorSearchAmongInTxn). A set ofcountnodes withcount² ≤ ef_search × m_max0 × vectorsis measured node by node (exact); a larger one goes through the graph with the set as a filter (HnswIndex.searchFiltered), whose beam keeps only members as results and walks through the rest. The crossover is where the two measured the same at 10k and 100k vectors of 128 dimensions. A threshold with noLIMITstill doubleskuntil the farthest result passes it. - Single-threaded: No concurrent insert/search yet
Future Enhancements
- Concurrent access: Reader-writer locks for parallel search
- Product quantization: Compress vectors for larger datasets
- Predicate push-down: a
<=>predicate combined with others throughANDis evaluated row by row; those predicates could become the search's filter
Full-Text Search (BM25)
This document explains how Lattice's full-text search works, from text input to ranked results.
Overview
Full-text search allows you to find documents containing specific words or phrases, ranked by relevance. Lattice implements the BM25 (Best Match 25) ranking algorithm, the same algorithm used by Elasticsearch and other production search engines.
An index covers exactly one label and one property — Document.body, say. You
declare it once, and writing that property keeps it current. Sections 13 to 16
cover how a declaration is stored, how one set of trees carries many indexes, how
writes maintain them, and why the one-label-one-property shape is what lets a
query read the index instead of scanning.
The FTS system consists of five components:
1. Tokenizer
The tokenizer breaks text into searchable tokens.
What It Does
Given input text:
"The quick brown fox jumps over the lazy dog"
The tokenizer produces:
["quick", "brown", "fox", "jumps", "lazy", "dog"]
Notice "The", "the", and "over" are missing—they're stop words.
How It Works
The tokenizer decodes UTF-8. A word is a run of code points that are letters,
digits or combining marks in any script, plus _; spaces, punctuation, symbols
and emoji separate words, and so does any byte that is not valid UTF-8. Han
ideographs and hiragana are a word each, since those scripts do not separate
words with spaces. So Müller, москва and snake_case are one word each, and
東京 is two. On ASCII text the result is byte for byte what 0.16.0 produced.
Indexes built by 0.16.0 keep its ASCII-only splitting; see
Analysis is recorded per index.
The tokenizer returns each token's original text. Normalisation happens in one
function, normalizeTerm, which indexing, every query form, uncommitted-text
matching and highlighting all call with the same configuration:
- Lowercase Latin (including Latin Extended), Greek, Cyrillic and Armenian letters, and full-width ASCII.
- Fold accents when
remove_accentsis set (the default):café→cafe,Straße→strasse,æ→ae, Greek tonos and dialytika removed, and combining marks of decomposed text dropped. Folding never makes a word longer in bytes. - Stem when
use_stemmingis set (off by default), with the English Porter stemmer.
Words shorter than min_token_length (2) or longer than max_token_length (64)
bytes are dropped before normalisation, and stop words are compared against the
lowercased, accent-folded word before stemming.
Analysis is recorded per index
An index records how it analyses text (a version, whether accents are folded, whether words are stemmed, whether postings carry word positions, and the language) under a six-byte key in its own document-lengths scope when its first document goes in. From then on the record wins over the configuration, so a word is always looked up as the term it was stored as, even if the configuration changes between opens.
An index that has documents and no record was built by 0.16.0 or earlier. Its
terms came from the ASCII-only tokenizer, so it keeps that tokenizer
(ascii_only): every byte that is not an ASCII letter, digit or _ separates
words, terms are ASCII-lowercased, and there is no accent folding or stemming.
Its stored terms stay findable, and searching it behaves as it did. Once every
document has left the index, the next one records the new analysis. Dropping an
index clears its record with the rest of its keys, so dropping and declaring it
again rebuilds it with the new tokenizer; so does the rebuild that follows a
recovery that replayed the log.
No existing key or value changed, and 0.16.0 never reads the new key, so the index does not keep 0.16.0 out of a database this version wrote. (Other things do: see Format Versions. With the changefeed on, the first write does.) Where 0.16.0 can open the database, it splits non-ASCII words its old way, so it does not find non-ASCII words this version indexed.
Stop Words
Stop words are common words that add little search value. Lattice ships one
stop-word list: about 100 English words (the, and, is, a, to, of, in, that,
it, …), in src/fts/stopwords.zig.
The tokenizer config has a language field, and the list is looked up by
language, but every language currently returns the English list. Setting
.language = .german changes nothing.
Configuration
pub const TokenizerConfig = struct {
min_token_length: u8 = 2, // Skip tokens shorter than this (bytes)
max_token_length: u8 = 64, // Skip tokens longer than this (bytes)
lowercase: bool = true, // Compare stop words in lowercase
remove_accents: bool = true, // Fold accents ("café" -> "cafe")
remove_stop_words: bool = true, // Filter common words
use_stemming: bool = false, // Porter-stem terms when indexing and searching
language: Language = .english, // Every language uses the English stop words
ascii_only: bool = false, // 0.16.0 splitting; set by the index, not by callers
};
The database takes this from DatabaseConfig.fts_config.tokenizer, one setting
for every index it opens, and it applies only to indexes that have not yet
recorded their analysis. The C API, the bindings and Cypher do not expose it, so
outside Zig every new index folds accents and does not stem.
Porter Stemmer
The engine includes an English Porter stemmer, which reduces tokens to their root forms:
| Input token | Stemmed |
|---|---|
running | run |
connected | connect |
optimization | optim |
databases | databas |
With use_stemming set, a new or emptied index stores and looks up stemmed
terms, so run finds running; the setting is recorded in the index (see
above), so an index that already has documents keeps the analysis it recorded. It is off by default, and only a Zig caller can set it, through the
database's fts_config. Highlighting normalises through the same function, so
given the index's analysis (FtsIndex.analysis()) it marks the words search
matched.
For non-English languages the stemmer returns words unchanged.
Use normalizeAndStem() or normalizeAndStemWithLanguage() for manual stemming:
var buf: [64]u8 = undefined;
// English stemming
const en_stemmed = tokenizer_mod.normalizeAndStemWithLanguage("RUNNING", &buf, true, .english);
// en_stemmed = "run"
// German (no stemmer available, returns lowercased)
const de_stemmed = tokenizer_mod.normalizeAndStemWithLanguage("RUNNING", &buf, true, .german);
// de_stemmed = "running"
2. Dictionary
The dictionary maps tokens to integer IDs and tracks statistics.
What It Does
| Token | TokenId | DocFreq | PostingPage |
|---|---|---|---|
hello | 1 | 5 | 42 |
world | 2 | 3 | 43 |
database | 3 | 12 | 44 |
search | 4 | 8 | 45 |
What the TokenId is for
The dictionary entry's posting_page is what leads from a token to its
postings. Since 0.17.0 the token_id is the list's head page id, and every page
of the list carries it in its header. That stamp is what lets an append trust
the entry's tail_page: a tail is used only if it is a posting page carrying
the list's stamp, so a stale tail can never send an append into another list.
Lists written by 0.16.0 carry a counter value instead (it restarted at every
open, so it never identified anything) and take the stamp at their first
append.
Storage Format
The dictionary uses a B+Tree with:
- Key: Token string (e.g.,
"hello") - Value: DictionaryEntry (24 bytes)
| Field | Size | Offset |
|---|---|---|
total_freq | 8 B | 0 |
token_id | 4 B | 8 |
doc_freq | 4 B | 12 |
posting_page | 4 B | 16 |
tail_page | 4 B | 20 |
Fields are ordered largest-first to minimize internal padding (u64 requires 8-byte alignment).
| Field | Type | Description |
|---|---|---|
total_freq | u64 | Total occurrences across all documents (always 0 before 0.17.0) |
token_id | u32 | The list's head page, stamped on its pages (see above) |
doc_freq | u32 | Number of documents containing this token |
posting_page | PageId | First page of the posting list |
tail_page | PageId | Last page of the list, where the next append goes; 0 when unknown |
tail_page was padding before 0.17.0, and 0.16.0 writes it as 0 whenever it
updates an entry; the next append here then walks the list from its head once
and records the tail again.
Operations
Indexing a document reads each of its terms' entries once and writes it back
once, with the counts and the tail brought up to date. A term no document holds
any more is removed from the dictionary, so the term count (unique_tokens,
which counts the dictionary) and prefix and fuzzy expansion see only live terms.
3. Posting Lists
A posting list stores which documents contain a specific token.
What It Does
For the token "database" (TokenId 3):
| DocId | TermFreq | |
|---|---|---|
| 15 | 3 | document 15 contains database three times |
| 42 | 1 | |
| 89 | 7 | |
| 156 | 2 | |
| 203 | 1 | |
| … | … |
Page Layout
Each posting list page is 4096 bytes. This is the current (V2) layout:
| Region | Bytes | Contents |
|---|---|---|
PageHeader | 0–7 | page_type = fts_posting; page-header flag 0x01 marks the V2 layout |
PostingPageHeader | 8–31 (24 B) | see below |
| Skip-pointer area | 32–283 (252 B) | reserved; zero on pages written since 0.17.0 (see below) |
| Posting data | 284 → | varint encoded entries, see below |
Each entry is [doc_id: varint][term_freq: varint]. When the index stores
positions, the entry continues with [position_count: varint][position: varint] × position_count. Doc ids and positions are stored as absolute values, not as
deltas.
PostingPageHeader fields
| Field | Type | Meaning |
|---|---|---|
token_id | u32 | The list's head page id (a counter value on lists 0.16.0 wrote) |
num_entries | u32 | Postings held in this page |
next_page | u32 | Overflow page, 0 for none |
num_skip_pointers | u16 | 0 since 0.17.0 |
flags | u16 | 0x01 = entries carry positions (for phrase queries) |
data_start | u32 | Byte offset where posting data begins (284) |
data_end | u32 | Byte offset where posting data currently ends |
The older V1 layout has a 20-byte header without data_end and room for 16 skip
pointers. Posting data starts at byte 284 in both, so a V1 page is upgraded in
place the first time an entry is appended to it. Creating any posting page also
raises the file header's format_version and min_reader_version to at
least 2.
Varint Encoding
Document IDs and frequencies are stored using variable-length integers (varints) for compression:
| Value | Varint bytes | Encoded size | Fixed-width size |
|---|---|---|---|
| 127 | [0x7F] | 1 B | 8 B |
| 128 | [0x80, 0x01] | 2 B | 8 B |
| 16,383 | [0xFF, 0x7F] | 2 B | 8 B |
| 1,000,000 | [0xC0, 0x84, 0x3D] | 3 B | 8 B |
Encoding algorithm:
while value >= 0x80:
output byte = (value & 0x7F) | 0x80 // Low 7 bits + continuation flag
value = value >> 7
output byte = value // Final byte (no continuation)
Example: Encoding 300 (binary: 1 0010 1100)
300 = 0b100101100
Step 1: 300 >= 128, so:
output[0] = (300 & 0x7F) | 0x80 = 0x2C | 0x80 = 0xAC
300 >> 7 = 2
Step 2: 2 < 128, so:
output[1] = 2 = 0x02
Result: [0xAC, 0x02] (2 bytes instead of 8)
Overflow Pages
When a posting list exceeds one page, it chains to overflow pages:
Appending and Removing
An append goes to the list's last page, found from the dictionary entry's
tail_page, so it costs a page or two however long the list is. Until 0.17.0
an append walked the list from its head, so a word shared by many documents made
each new document cost time in proportion to that word's list.
Removing a document's entry rewrites the page it was on. If that page and the
next together fit in one page and encode positions alike, the next page's
entries move up and the next page is freed; a last page left empty is unlinked
and freed, and the tail moves back. A list left with no entries is freed with its
dictionary entry. Dropping or rebuilding an index frees every list its
dictionary names, and compact frees the lists of the single index releases
before 0.15.0 kept (keys no declared index can reach). Freed pages go to the
file's freelist; only free pages at the end of the file shrink it.
Skip Pointers
0.16.0 wrote skip pointers into the reserved area, and nothing read them usefully: they assumed a list in doc-id order, and posting lists are not kept in that order (an update removes a document's postings and appends the new ones at the tail, and a transaction commits its documents in hash order). Since 0.17.0 they are not written, a page rewritten by a removal or upgrade has its area cleared, and pages that still hold them read as before, since the posting data starts after the area either way.
Reading is batched: PostingIterator.next() decodes up to 128 entries per page
pin, rather than pinning the page once per entry.
4. Document Length Storage
BM25 scoring requires knowing each document's length. This is stored in a separate B+Tree:
| DocId | Length (tokens) |
|---|---|
| 1 | 150 |
| 2 | 45 |
| 3 | 892 |
| … | … |
Why store lengths?
BM25 penalizes long documents to prevent them from dominating results just because they contain more words. A 10,000-word document mentioning "database" once is less relevant than a 100-word document mentioning it once.
Statistics tracked:
total_docs: Total documents indexedtotal_tokens: Sum of all document lengthsavg_doc_length: Average tokens per document (for normalization)
A failure to write the statistics is returned to the caller; it used to be ignored, which could leave an index with no statistics and every later score computed against an empty corpus. The same tree also holds the index's analysis record (section 1).
A search looks up the lengths of all the documents it scores in one pass, sorted by key, with a cursor that seeks forward through the tree, so neighbouring keys share a descent instead of costing one each. A storage error while reading lengths fails the search rather than dropping the document.
5. BM25 Scoring
BM25 calculates a relevance score for each document.
The Formula
Score(D, Q) = Σ IDF(term) × TF_norm(term, D)
for each term in query Q
Where:
IDF (Inverse Document Frequency):
IDF(term) = log((N - df + 0.5) / (df + 0.5) + 1)
N = total number of documents
df = number of documents containing this term
Rare terms get higher IDF scores. If "quantum" appears in 5 of 10,000 documents, it's more significant than "the" appearing in 9,500.
TF_norm (Normalized Term Frequency):
TF_norm = (tf × (k1 + 1)) / (tf + k1 × (1 - b + b × (dl / avgdl)))
tf = term frequency in this document
k1 = saturation parameter (default 1.2)
b = length normalization (default 0.75)
dl = document length
avgdl = average document length
Parameters
| Parameter | Default | Effect |
|---|---|---|
k1 | 1.2 | Controls term frequency saturation. Higher = more weight to repeated terms |
b | 0.75 | Length normalization. 0 = no normalization, 1 = full normalization |
Scoring Example
Corpus: 1000 documents, average length 200 tokens
Query: "database optimization"
Document 42:
- Length: 150 tokens
- "database" appears 3 times
- "optimization" appears 1 time
Term: "database"
- doc_freq = 50 (appears in 50 docs)
- IDF = log((1000 - 50 + 0.5) / (50 + 0.5) + 1) = log(19.82) ≈ 2.99
- tf = 3
- dl/avgdl = 150/200 = 0.75
- TF_norm = (3 × 2.2) / (3 + 1.2 × (1 - 0.75 + 0.75 × 0.75))
= 6.6 / (3 + 1.2 × 0.8125)
= 6.6 / 3.975
≈ 1.66
- Score for "database" = 2.99 × 1.66 ≈ 4.96
Term: "optimization"
- doc_freq = 10 (rarer term)
- IDF = log((1000 - 10 + 0.5) / (10 + 0.5) + 1) ≈ 4.55
- tf = 1
- TF_norm = (1 × 2.2) / (1 + 1.2 × 0.8125) ≈ 1.12
- Score for "optimization" = 4.55 × 1.12 ≈ 5.10
Total Score for Document 42 = 4.96 + 5.10 = 10.06
6. Search Flow
Single-Term Search
Multi-Term Search (AND Semantics)
A query is split into distinct normalised terms, however many there are. A
document matches only if it contains every term, so a term that is not in the
dictionary at all means nothing matches, and a failed dictionary lookup or
posting read is an error rather than a term quietly left out. The rarest term's posting list
(lowest doc_freq) supplies the candidates, held in a hash map by doc_id. Every
other list is then read through once, rarest next, and each entry is matched
against the candidates by doc_id, so the result does not depend on the order the
lists are stored in. A term that matches no remaining candidate ends the search
early.
Every document that has all the terms is scored, and the best limit are kept
in a bounded heap (ties keep posting order). The answer is the true top K at any
limit. A single-term search keeps the best limit the same way. Document
lengths are looked up only for documents in every list.
Reading every list in full means an AND query costs about the sum of its terms' document frequencies, so a common term costs as much beside a rare one as on its own.
The query language
Since 0.17.0 every entry point takes the same query language, parsed once by
src/fts/query.zig: words side by side are required, OR (capitals) separates
alternatives and binds looser than the AND, -word and -"phrase" exclude,
"phrase" needs its words adjacent and in order, word* is a prefix, and
word~ / word~1 allow two / one edits. The guide's
query syntax has the table.
| Entry point | Query form |
|---|---|
Cypher x.prop @@ text, lattice_fts_search, search() | the language as written |
lattice_fts_search_fuzzy, searchFuzzy() | each plain word made fuzzy, and any one word enough |
searchWithMode(.@"or"), searchOr() | each required unit an alternative of its own |
"text" @@ "query" on a plain string | the language, matched against that text with the default analysis |
A parsed query is a list of branches; a branch is a list of required units
(term, phrase, prefix, fuzzy word) and exclusion groups. A query of plain words
goes straight to the AND search above. Otherwise each branch starts from its
plain terms through the AND search, intersects the other units' matches, removes
each exclusion group's, and the branches' scores add up; ranking and the limit
come last. Text a transaction has not committed is matched by the same parsed
query (QueryMatcher) and scored with the same BM25 and corpus statistics. The
sections below describe the individual forms.
OR Search
OR search returns documents matching any query term:
// Returns docs containing "mysql" OR "postgres" OR both
const results = try fts.searchOr("mysql postgres", 10);
// Or use explicit mode selection
const results = try fts.searchWithMode("mysql postgres", .@"or", 10);
NOT Search (Exclusions)
Prefix terms with - to exclude documents containing them:
// Find "database" docs that don't mention "mysql"
const results = try fts.searchWithMode("database -mysql", .@"and", 10);
// Multiple exclusions
const results = try fts.searchWithMode("database -mysql -oracle", .@"and", 10);
Exclusion is applied after the candidate search, and so are phrase
intersections. Every sub-search that is narrowed afterwards runs without a
limit, and ranking and the limit come last, so a document that survives the
narrowing is never cut beforehand for scoring below documents that do not
survive it. Only a lone term search, with no exclusions and no phrases, stops at
limit directly, which is the one case where that is exact.
searchWithMode splits each whitespace-separated run of the query with the
tokenizer, so foo-bar asks for both foo and bar (a - inside a word is a
separator, not an exclusion), and punctuation such as bread, butter is
separated rather than kept. An exclusion written as a phrase, -"a b",
removes the documents holding it in order, and needs stored positions as any
phrase does.
Phrase Search
Phrase search finds documents where terms appear adjacent and in order:
// Enable position storage in config
var fts = FtsIndex.init(allocator, &bp, &dict_tree, &lengths_tree, null, .{
.store_positions = true,
});
// Search for exact phrase
const results = try fts.searchPhrase("quick brown fox", 10);
Query: "quick brown fox" (phrase)
Document 1: "The quick brown fox jumps" ← MATCHES (adjacent: pos 0,1,2)
Document 2: "A quick red brown fox" ← NO MATCH (not adjacent)
Document 3: "The brown quick fox" ← NO MATCH (wrong order)
Positions count only the tokens that were kept, so stop words and too-short
words (The, A) take no position.
How it works:
-
Fetch the posting lists with positions:
Term Postings quickdoc 1 @ 0, doc 2 @ 0 browndoc 1 @ 1, doc 2 @ 2 foxdoc 1 @ 2, doc 2 @ 3 -
For each candidate document, check that the positions are adjacent:
Document Positions Adjacent? doc 1 quick@0,brown@1,fox@2Yes — 0+1=1 and 0+2=2, so it matches doc 2 quick@0,brown@2,fox@3No — 0+1=1 but brownis at 2
Every term of the phrase has to line up behind the same start: the search keeps,
per document, the positions of the first term that can still begin the phrase
and narrows them term by term. A phrase's own words go through the index's
tokenizer, so stop words in it are dropped the way indexing dropped them, and
"Bank of America" matches the text "Bank of America".
Note: Phrase queries need positions. store_positions is on by default
since 0.17.0 and is recorded in the index with its analysis when the first
document goes in, so it holds for the index's life. An index with no positions
(any index 0.16.0 built) answers a phrase with PhraseNeedsPositions
(LATTICE_ERROR_INVALID_ARG through the C API) rather than with its words in
any order; dropping and declaring it again stores them. One posting entry holds at
most a page's worth of positions; occurrences of a term beyond that still count
towards its frequency, but a phrase starting past that point in a document is
not found.
Quoted Phrase Syntax
You can also use quoted strings in searchWithMode() calls to detect phrase queries. (search() treats quotes as separators like any other punctuation.)
// These are equivalent:
const results1 = try fts.searchPhrase("quick brown", 10);
const results2 = try fts.searchWithMode("\"quick brown\"", .@"and", 10);
Combining phrases with terms and exclusions:
// Phrase + additional term (AND mode)
// Matches documents with "quick brown" phrase AND term "jumps"
const results = try fts.searchWithMode("\"quick brown\" jumps", .@"and", 10);
// Phrase + exclusion
// Matches documents with "quick brown" phrase but NOT containing "fox"
const results = try fts.searchWithMode("\"quick brown\" -fox", .@"and", 10);
// Multiple phrases
// Matches documents with both phrases
const results = try fts.searchWithMode("\"quick brown\" \"lazy dog\"", .@"and", 10);
// Phrase with OR mode
// Matches documents with "quick brown" phrase OR term "rabbit"
const results = try fts.searchWithMode("\"quick brown\" rabbit", .@"or", 10);
Single-word quotes:
Single words in quotes are treated as regular terms (since a one-word phrase is just a term):
// These are equivalent:
const results1 = try fts.search("database", 10);
const results2 = try fts.searchWithMode("\"database\"", .@"and", 10);
Fuzzy Search
Fuzzy search finds documents even when query terms contain typos. It uses Levenshtein (edit) distance to match terms within a configurable threshold.
const fuzzy = @import("fts/fuzzy.zig");
// Search with typo tolerance (max 2 edits)
const results = try fts.searchFuzzy("databse", .{
.max_distance = 2, // Allow up to 2 edits
.min_term_length = 4, // Only fuzzy-match terms >= 4 chars
}, 10);
defer fts.freeResults(results);
// Matches documents containing "database" (edit distance 1)
How it works:
Query: "databse" (typo)
↓
Scan dictionary for terms within edit distance 2:
- "database" (distance=1) ✓
- "datastore" (distance=3) ✗
↓
Search matching terms with distance penalty:
- Score("database") × penalty(1) = Score × 0.89
↓
Return ranked results
Each query word scores a document by its best expansion in that document,
not the sum of all of them, so a document holding two spellings near one word
("databases database" for "databse") does not outrank its own exact match. The
words' scores then add up, and a document needs to match only one word: fuzzy
search is OR across words. Words shorter than min_term_length are matched
exactly. Expanded terms are copied out of the dictionary's pages, so they stay
valid after the walk unpins them.
Distance penalty formula:
penalty = 1.0 - (distance / (max_distance + 1))²
Examples (max_distance = 2):
- distance 0: 1.00 (exact match)
- distance 1: 0.89
- distance 2: 0.56
Every match the search returns keeps part of its score, and a closer match
always more. Dividing by max_distance instead, as earlier releases did,
scored a match at the full distance 0: returned, but ranked with documents
that matched nothing.
Levenshtein distance counts the minimum single-character edits needed:
- Insertion: "helo" → "hello" (distance 1)
- Deletion: "hello" → "helo" (distance 1)
- Substitution: "hello" → "hallo" (distance 1)
Note: Transpositions ("recieve" → "receive") count as 2 edits in standard Levenshtein.
Prefix/Wildcard Search
Prefix search finds documents containing terms that start with a given prefix. Use * as a suffix wildcard.
const prefix = @import("fts/prefix.zig");
// Search for terms starting with "optim" (matches "optimize", "optimization", "optimizer")
const results = try fts.searchWithPrefix("optim*", .{
.min_prefix_length = 2, // Minimum prefix length (prevents "a*" explosion)
.max_expansions = 50, // Maximum terms to expand
}, 10);
defer fts.freeResults(results);
How it works:
Query: "optim*"
↓
Calculate range bounds: ["optim", "optin")
↓
B+Tree range scan to find matching terms:
- "optimization" ✓
- "optimize" ✓
- "optimizer" ✓
↓
Search all matching terms (like OR query)
↓
Return ranked results
Combining prefix with regular terms:
// AND semantics: documents must contain "systems" AND a term starting with "data"
const results = try fts.searchWithPrefix("systems data*", .{}, 10);
// Matches documents with both "systems" and "database"/"datastore"/"data"
Each query word counts once per document however many of a prefix's expansions
the document holds, so "zebra optim*" does not match a document containing
"optimize optimization" and no "zebra". The query is split into words the way the
tokenizer splits text (systems, is looked up as systems), words the tokenizer
would drop (stop words, single characters) are dropped, and a word with no
matches makes the result empty.
Constraints:
- Suffix wildcards only (
optim*), not prefix wildcards (*tion) - No middle wildcards (
da*base) - Minimum prefix length configurable (default 2 chars)
- Maximum expansions capped to prevent explosion
Search Highlighting
Search highlighting returns text snippets with matched terms marked, enabling UI display of search results with context.
const highlight = @import("fts/highlight.zig");
const text = "The database stores data efficiently for optimal performance.";
const query_terms = [_][]const u8{ "database", "data" };
const result = try highlight.highlight(
allocator,
text,
&query_terms,
.{ .use_stemming = false }, // TokenizerConfig
.{
.context_chars = 80, // Characters of context around matches
.max_snippets = 3, // Maximum snippets to return
.merge_distance = 40, // Merge snippets closer than this
.prefix_marker = "<em>", // Marker before matched terms
.suffix_marker = "</em>", // Marker after matched terms
.ellipsis = "...", // Added when text is truncated
},
);
defer highlight.freeResult(allocator, result);
// result.snippets[0].text = "The <em>database</em> stores <em>data</em> efficiently..."
// result.total_matches = 2
How it works:
Query terms: ["database", "data"]
Document: "The database stores data efficiently for optimal performance."
↓
Re-tokenize document with same config:
- "database" at offset 4 → stems to "databas" or "database"
- "data" at offset 20 → stems to "data"
↓
Match against query terms (stemmed comparison):
- Match found at positions 4-12 and 20-24
↓
Group matches into snippets with context:
- Single snippet with both matches (close together)
↓
Insert markers around matches:
- "The <em>database</em> stores <em>data</em> efficiently..."
With stemming:
const text = "The runners were running fast in the marathon.";
const query_terms = [_][]const u8{"run"}; // Already stemmed query
const result = try highlight.highlight(
allocator,
text,
&query_terms,
.{ .use_stemming = true }, // Enable stemming
.{ .prefix_marker = "**", .suffix_marker = "**" },
);
// "running" stems to "run" → match
// "runners" stems to "runner" → no match
// result.snippets[0].text = "The runners were **running** fast..."
Key design decisions:
- Re-tokenization approach: Document text is re-tokenized at query time (no storage overhead)
- Stemmed matching: Query terms are matched against stemmed document tokens
- Original text preserved: Markers wrap the original text, not stemmed forms
- Configurable markers: Default
<em>/</em>but customizable for any format - Snippet merging: Close matches combined into single snippets
Finding matches only (without snippets):
const matches = try highlight.findMatches(
allocator,
text,
&query_terms,
.{ .use_stemming = false },
);
defer highlight.freeMatches(allocator, matches);
for (matches) |match| {
// match.start = byte offset of match start
// match.end = byte offset of match end (exclusive)
const matched_text = text[match.start..match.end];
}
7. Indexing Flow
Nothing calls this directly any more. Writing an indexed property is what runs it, and section 15 covers how that happens. The mechanics below are unchanged: this is what one document costs whenever it is indexed.
Indexing one document
8. Data Structures Summary
In-Memory
| Structure | Purpose |
|---|---|
Tokenizer | Streaming text tokenization |
PostingIterator | Iterate posting list entries |
Bm25Scorer | Calculate relevance scores |
On-Disk (B+Trees)
| B+Tree | Key | Value |
|---|---|---|
| Dictionary | 4-byte scope prefix + token string | DictionaryEntry (24 bytes) |
| DocLengths | 4-byte scope prefix + DocId (8 bytes) | Length (4 bytes) |
| Reverse index | 4-byte scope prefix + DocId | Terms the document contributed |
| Index catalog | [kind, scope_id, property_id] | empty; the key is the record |
The scope prefix is what keeps one declared index out of another's way; section 14 explains it. The catalog shares its tree with the property indexes, under different kind discriminators.
On-Disk (Pages)
| Page Type | Content |
|---|---|
FTS_POSTING | Posting list entries (varint encoded) |
9. Limitations and Future Work
Current Limitations
- Stemming only from Zig -
use_stemmingstems new indexes, but only a Zig caller can set it; through the C API, the bindings and Cypher there is no stemming - English stop words only - The
languagesetting does not change the stop-word list, and the stemmer is English only - Old indexes keep ASCII tokenization - An index that held documents before this release keeps splitting on non-ASCII bytes until it is emptied, or dropped and declared again; there is no reindex command
- No grouping in queries - the query language has no parentheses, and a query of only exclusions is refused
- Unspaced scripts - Han and hiragana are indexed a character at a time; Thai, Lao and Khmer runs become one long term, and a term over 64 bytes is dropped
- A node and an edge index cannot share a name and property - see section 14
- One property per index - Searching several fields as one document means storing the combined text in a property and indexing that. The reasoning is in the design note: an index spanning
titleandbodywould maked.title @@ "x"match on body text, which is the confusion per-property indexes exist to remove. - Selectivity is per term, not per phrase - the estimate that chooses between two indexes is the rarest term's document frequency, which bounds an AND query correctly but says nothing about how often the terms occur together. Two predicates whose terms are individually common but jointly rare estimate as common.
- Prefix and fuzzy words walk the dictionary - a prefix expands to every term starting with it, and a fuzzy word compares against every term, so a short prefix or any fuzzy word costs in proportion to what it reaches
Implemented Features
Items marked (FtsIndex) are implemented in the component but not reachable through the database, the C API or Cypher.
- Phrase queries -
"quick brown fox"in any query, with position verification - Boolean queries - AND (default),
OR, and-term/-"phrase"exclusion, everywhere - Porter stemmer (English) - applied by indexing, search and highlighting when
use_stemmingis set (Zig only); also available asnormalizeAndStem() - Position indexing - on by default for new indexes, recorded per index
- Tail appends and page reclamation - appends go to the list's last page, and removals free and merge pages (section 3)
- Quoted phrase syntax -
"exact phrase"in every query - Fuzzy search - Levenshtein distance for typo tolerance via
searchFuzzy()andlattice_fts_search_fuzzy - Stop words - one English list
- Prefix/wildcard search -
optim*in any query expands to every matching term - Search highlighting (Zig module only) -
highlight()marks given terms;highlightQuery()marks what a parsed query matched, phrases only where they occur - Document deletion -
removeDocument()with reverse index properly cleans posting lists and stats - Per-property indexes - one index per label and property, declared and then maintained by writes (sections 13 to 15)
- Relationship indexes - the same over a relationship type and property
- Index seek as the access path - a full-text predicate reads the index instead of filtering a label scan (section 16)
- Corpus statistics on disk - document count and average length survive a reopen, so scores do not depend on what the session happened to index
- Unicode tokenization - words in any script, lowercasing and accent folding, with the analysis recorded per index (section 1)
Planned Features
- Multi-language stemmers - Snowball stemmers for German, French, etc.
10. The Index Component Directly
This is the engine component, wired up by hand. It is here to show what the
pieces above do together, not as an API to use: nothing outside the storage layer
constructs an FtsIndex, and indexDocument is reached by writing an indexed
property rather than by calling it.
For the API you would actually use, see Full-Text Search (@@) and the full-text search guide.
const std = @import("std");
const lattice = @import("lattice");
pub fn main() !void {
var gpa = std.heap.DebugAllocator(.{}){};
const allocator = gpa.allocator();
// Initialize storage (simplified)
var bp = try BufferPool.init(allocator, &pm, 64 * 4096);
var dict_tree = try BTree.init(allocator, &bp);
var lengths_tree = try BTree.init(allocator, &bp);
// Create FTS index with phrase query support (no reverse index tree)
var fts = FtsIndex.init(allocator, &bp, &dict_tree, &lengths_tree, null, .{
.store_positions = true, // Enable phrase queries
});
// Index documents
_ = try fts.indexDocument(1, "Introduction to database systems");
_ = try fts.indexDocument(2, "Advanced database optimization techniques");
_ = try fts.indexDocument(3, "Web development with JavaScript");
_ = try fts.indexDocument(4, "Database performance and MySQL tuning");
// Basic AND search (all terms must match)
const results1 = try fts.search("database optimization", 10);
defer fts.freeResults(results1);
// Returns doc 2 (contains both terms)
// OR search (any term matches)
const results2 = try fts.searchOr("mysql postgres", 10);
defer fts.freeResults(results2);
// Returns doc 4 (contains "mysql")
// NOT search (exclusions with -prefix)
const results3 = try fts.searchWithMode("database -mysql", .@"and", 10);
defer fts.freeResults(results3);
// Returns docs 1, 2 (contain "database" but not "mysql")
// Phrase search (exact sequence)
const results4 = try fts.searchPhrase("database systems", 10);
defer fts.freeResults(results4);
// Returns doc 1 (has "database systems" as adjacent phrase)
// Quoted phrase syntax (alternative to searchPhrase)
// Phrase "database optimization" + term "advanced"
const results5 = try fts.searchWithMode("\"database optimization\" advanced", .@"and", 10);
defer fts.freeResults(results5);
// Returns doc 2 (has phrase "database optimization" AND term "advanced")
// Fuzzy search (typo tolerance)
const results6 = try fts.searchFuzzy("databse", .{
.max_distance = 2,
.min_term_length = 4,
}, 10);
defer fts.freeResults(results6);
// Returns docs with "database" (edit distance 1 from "databse")
for (results1) |result| {
std.debug.print("Doc {}: score {d:.2}\n", .{ result.doc_id, result.score });
}
}
11. Serialization Pattern
All on-disk structures use extern struct with compile-time size assertions:
/// Good: Self-documenting, compile-time verified
pub const PostingPageHeaderV2 = extern struct {
token_id: TokenId,
num_entries: u32,
next_page: PageId,
num_skip_pointers: u16,
flags: u16,
data_start: u32,
data_end: u32,
pub const OFFSET: usize = @sizeOf(PageHeader);
comptime {
std.debug.assert(@sizeOf(PostingPageHeaderV2) == 24);
}
pub fn read(data: []const u8) PostingPageHeaderV2 {
return std.mem.bytesAsValue(
PostingPageHeaderV2,
data[OFFSET..][0..@sizeOf(PostingPageHeaderV2)],
).*;
}
pub fn write(self: *const PostingPageHeaderV2, data: []u8) void {
const dest = data[OFFSET..][0..@sizeOf(PostingPageHeaderV2)];
@memcpy(dest, std.mem.asBytes(self));
}
};
Why this pattern?
- No magic numbers - Field layout is defined by the struct, not manual offsets
- Compile-time verification -
comptimeblock catches size mismatches immediately - Self-documenting - Struct fields serve as documentation
- Consistent with codebase - WAL, PageHeader, FileHeader all use this pattern
Alignment considerations:
When structs contain u64 fields, use explicit padding and order fields largest-first:
pub const DictionaryEntry = extern struct {
total_freq: u64, // 8 bytes - largest first (requires 8-byte alignment)
token_id: u32, // 4 bytes
doc_freq: u32, // 4 bytes
posting_page: u32, // 4 bytes
_padding: u32 = 0, // 4 bytes - explicit trailing padding
comptime {
std.debug.assert(@sizeOf(DictionaryEntry) == 24);
}
};
13. Declared Indexes
An index covers one label and one property. Nothing is indexed until you say so.
try db.createNodeFtsIndex("Document", "body");
Declaring reads body from every node already carrying Document and indexes
it, so adding an index to a database full of documents makes them searchable
immediately rather than only affecting what arrives afterwards. That mirrors what
createNodePropertyIndex does, for the same reason: an index that only covers
future writes is a trap.
Where a declaration lives
Declarations go in the same B+Tree as the property index catalog, under their own kind discriminators:
| Kind | Meaning |
|---|---|
| 1 | node property index |
| 2 | edge property index |
| 3 | node full-text index |
| 4 | edge full-text index |
The key is [kind (1 byte), scope_id (2 bytes big-endian), property_id (2 bytes big-endian)] and the value is empty — the key is the whole record. scope_id is
a label for a node index and a relationship type for an edge one; both are symbol
ids from the same table the rest of the engine uses.
Sharing the catalog tree was free. The key already began with a kind byte, so
adding two more kinds needed no format change and no new tree. Big-endian is what
makes a range scan over one kind possible: [3] to [4] covers every node
full-text declaration and nothing else.
Why not multiple properties per index
Storing several properties as one document is easy. Asking for it is not. If an
index merged title and body, then WHERE d.title @@ "x" would match documents
whose body contained the term, and the property name would be lying — which is
the exact confusion per-property indexes exist to remove. Reusing property access
as the query syntax requires one property per index.
Somebody who wants several fields ranked as one document stores the combined text in a property and indexes that. The text is then visible in the database, where it can be read and rebuilt, instead of living only inside an index.
14. One Set of Trees, Many Indexes
Every declared index shares the dictionary, document-length, and reverse-index
trees. Without something separating them, a term indexed for title would be
found by a search of body.
Every key written for an index carries a four-byte prefix naming it:
[scope_id (2 BE), property_id (2 BE)] ++ the key the store wanted
So bread in Document.title and bread in Document.body are two different
keys in one tree, and a range over a prefix walks one index's terms and stops.
Unlike the catalog key, the prefix carries no kind byte. Labels and
relationship types are interned in the same symbol table, so a node index on
label X and an edge index on relationship type X over the same property
would get the same prefix and share entries: each would return the other's ids
and overwrite the other's document lengths, and dropping either would clear
both. Declaring the second of such a pair is therefore refused with
AlreadyExists. Giving edge indexes their own prefix would change the keys of
indexes already on disk, and there is no free prefix space for a kind that could
not collide with some node prefix. A database that declared both before the
check existed keeps sharing; dropping both and declaring again the one you keep
separates them.
Why a view rather than a prefix argument
The prefix is applied by a wrapper — ScopedTree — that the stores hold in place
of a raw B+Tree. The stores' key-building code did not change at all.
The alternative was passing a prefix into each place that builds a key, of which there are about a dozen across three files. Missing one would not fail to compile. It would write an entry the matching read could never find, or read another index's entries. One place to get right beats twelve places to remember.
The prefix arithmetic
Walking one index means ranging from its prefix to the next one. Computing "the
next prefix" has a trap: a prefix ending in 0xFF has to carry into the byte
before it. Incrementing the last byte alone wraps to zero, producing an upper
bound below the lower one, and the index reads as empty. That carry is a
function with its cases tested rather than arithmetic written inline twice.
Where the prefix comes off again
Reads strip the prefix before returning keys, because callers want the term. This matters more than it sounds: fuzzy search measures edit distance against the term text, so four bytes of index identity on the front puts every term far outside any sensible distance and nothing ever matches. The stripping lives in the iterator, next to the prefixing, so the two cannot drift apart.
15. Keeping Indexes Current
Writing an indexed property maintains the index. There is no separate indexing call, and nothing to forget.
Create, update, and delete all funnel through one function per entity kind, where an empty old state means a create and an empty new state means a delete. Eight call sites reach those two functions, which is eight fewer places that could each decide what a change means.
What is indexed
Only string properties. A number, a list, or an absent property contributes
nothing. Rendering 42 as "42" so a text search could match it would be a
different feature with different rules, and doing half of it silently would make
results hard to explain.
Unchanged text is left alone
An update whose indexed text did not change skips the index entirely. Without that, writing any property on an entity would reindex its longest indexed string, and the cost of an unrelated write would scale with how much text the entity happens to carry.
Recovery
Redo replays into the stores directly rather than through the write path, so nothing maintains the indexes while it runs — the same situation the property indexes are already in. After a redo, each declared index is cleared and rebuilt.
The clear works by scope prefix rather than by walking documents. An entity the redo deleted is no longer there to walk, so walking would leave its terms behind to keep matching. Deleting by prefix is a batched collect-then-delete, because the tree's iterator pins a leaf and holds a slot in it, which makes deleting during iteration unsafe; a fixed batch keeps memory flat rather than proportional to what is often the largest structure in the database.
Posting pages of a cleared index stay allocated. Nothing points at them once the dictionary entries naming them are gone, so it is wasted space rather than wrong data, and reclaiming it needs page reuse the store does not have yet.
16. Search as an Access Path
A @@ predicate is planned as the way into the data, not as a filter over a scan.
Why per-property indexing is what makes this possible
A Document.body index contains only Document nodes. The index is already
label-scoped, so reading it does the label scan's job and answers the text
question at the same time. The older design — one index spanning every node —
could not have done this: it had no idea which nodes carried which label, so it
could only ever filter a scan somebody else produced.
The measurement
Eight thousand documents, a query matching one of them:
| time | |
|---|---|
| the index lookup alone | 31 µs |
| scanning the label and keeping what the index named | 72 ms |
the same predicate under an AND, filtered per row | 216 ms |
The scan cost the whole corpus to answer a question the index had already answered. Seeking instead:
| before | after | |
|---|---|---|
@@ 'rare' | 72 ms | 105 µs |
@@ 'rare' AND … | 216 ms | 105 µs |
@@ 'common' AND … | 21.3 s | 320 ms |
Selective queries also stopped growing with the corpus — 65 µs, 80 µs, 105 µs from five hundred to eight thousand documents, against 3.9 ms, 17 ms, 72 ms before.
When it applies
Only in conjunctive positions: the whole WHERE, or a branch of an AND.
Under an OR the planner deliberately does not seek. The other branch can admit
entities the index never names, so seeking would silently drop rows. There is a
test asserting that an OR plans a label scan, because the reason is not visible
from reading the planner and the shape looks like a missed optimisation.
The predicate also has to name the entity the pattern is about. Where the variable is already bound by an upstream expand, the input decides which rows exist and the index can only filter them.
The filter that remains
What cannot be sought is still answered by evaluating @@ per row. That path
consults the index once per query rather than once per row, keyed on the
resolved index and the query text, and held for one execution.
Without it the filter was quadratic in the corpus: its cost against a scan grew 8.4x, 22.2x, then 152.1x as the corpus grew, and is now a flat 2.4x, 2.7x, 2.3x.
Reusing a search within one execution is the same assumption the scanning operators have always made — they search once when they open and use that result for every row they emit. The cache matches that granularity rather than inventing a stricter or a looser rule.
Choosing between two ways in
d.title @@ "the" AND d.body @@ "sourdough" offers two ways into the data, and
they are not equally cheap. Starting from a word most documents share means
reading the corpus to discard it; starting from a rare one means reading almost
nothing.
The dictionary already records, for every term, how many documents contain it. An AND query cannot match more documents than its rarest term appears in, so the minimum of those counts is a real upper bound rather than a guess — and a term absent from the dictionary gives zero, which is exact. Each candidate costs one B-tree lookup per term to estimate.
The choice is made when the query runs, not when it is planned, for two reasons. A query whose text arrives as a parameter has nothing to estimate at plan time. And a cached plan would carry a decision made against whatever the data looked like when it was first planned.
Choosing at execution is safe because the filter above the seek applies the whole condition regardless of which candidate was read, so the choice can only affect how much work is done, never which rows come back.
Candidates are confined to one label. The label the access path guarantees is the one whose filter the planner skips, and which candidate runs is not known until it runs; candidates spanning two labels would mean skipping a filter the chosen path does not satisfy. That was a real defect during development — a pattern asking for two labels returned entities carrying only one — and it survived two tests that passed for an unrelated reason before a negative control exposed it.
Measured on eight thousand documents, one matching row:
| query | before | after |
|---|---|---|
| rare predicate written first | 4.3 ms | 4.3 ms |
| common predicate written first | 244 ms | 4.2 ms |
The point is not only the 59x. It is that the two rows now agree: how the author ordered the predicates no longer decides what the query costs.
When the seek already answered the WHERE
MATCH (d:Doc) WHERE d.text @@ 'starter' RETURN d is planned as a seek on the
Doc.text index, and every row the seek emits matches. Planning the same predicate
again as a filter would run the whole search a second time and drop nothing, which
made the commonest full-text query pay for its search twice. When a MATCH's seek
has a single candidate search and the WHERE is that same search (same variable,
the index the filter would resolve, same query text or parameter), the planner adds
no filter. A seek that chose among several indexes at run time, a different query,
or another MATCH's WHERE still filters. On 2,000 documents with 663 hits this
took the query from 366 µs to 235 µs (busy machine).
The score in the row
The seek and the filter both store each hit's BM25 score in the row and mark the
slot as scored; giving the slot a new value clears the mark, so a score never
outlives the entity it was computed for. score(d) reads it: the best score among
the searches that matched for an OR, null when no single search scored d (no
@@ on it, or a seek that chose among indexes at run time). The mark goes through
WITH d but not WITH d AS e and not through an aggregation. ORDER BY score(d) LIMIT k sorts all the matches; it does not bound the search.
Disjunctions
Several @@ predicates on one variable joined by OR are planned as a single
operator that reads each index once and unions the results. A document found by
more than one takes its best score rather than a sum: two properties matching is
not evidence that either matched twice as well, and adding them would rank a
document matching both weakly above one matching a single property strongly.
Mixing kinds is refused. d.title @@ "x" OR r.note @@ "x" cannot be one union,
because one operator filters one slot and a slot holds a node or an edge. That
query still answers correctly, through the row filter.
12. File Reference
| File | Purpose |
|---|---|
src/fts/tokenizer.zig | Unicode word splitting, term normalization (case, accents, stemming), the 0.16.0 ASCII mode, language config; its case tables also serve Cypher's toLower and toUpper |
src/fts/stopwords.zig | English stop word list (used for every language) |
src/fts/dictionary.zig | Token → TokenId mapping via B+Tree, range iteration |
src/fts/posting.zig | Posting list storage with varint encoding, entry removal |
src/fts/scorer.zig | BM25 scoring, document length storage |
src/fts/index.zig | Main FtsIndex coordinator, boolean/phrase/fuzzy/prefix search |
src/fts/stemmer.zig | Porter stemmer algorithm (English), language routing |
src/fts/fuzzy.zig | Levenshtein distance, fuzzy term expansion |
src/fts/prefix.zig | Prefix/wildcard search, upper bound calculation |
src/fts/highlight.zig | Search result highlighting, snippet extraction |
src/fts/reverse_index.zig | doc_id → terms mapping for document deletion |
src/fts/catalog.zig | Declared indexes: kind, scope, property |
src/fts/scoped_tree.zig | Prefixing view that keeps declared indexes apart |
src/query/operators/fts.zig | Index seek and filtering operators |
Query Execution
Overview
Lattice executes Cypher queries using the Volcano iterator model—a pull-based execution engine where operators form a tree and data flows upward one row at a time. This design enables lazy evaluation, memory efficiency, and composable query plans.
The Volcano Iterator Model
Every operator implements four methods:
pub const Operator = struct {
vtable: *const VTable,
ptr: *anyopaque,
pub const VTable = struct {
open: fn (*anyopaque, *ExecutionContext) OperatorError!void,
next: fn (*anyopaque, *ExecutionContext) OperatorError!?*Row,
close: fn (*anyopaque, *ExecutionContext) void,
deinit: fn (*anyopaque, Allocator) void,
};
};
- open(): Initialize the operator, acquire resources (iterators, memory)
- next(): Return the next row, or
nullif exhausted - close(): Release resources (unpin pages, close iterators)
- deinit(): Free the operator itself
Pull-Based Execution
Data flows upward through the operator tree. The root operator "pulls" from its children:
When the executor calls root.next():
- Project calls Limit.next()
- Limit checks its count (returns null if the limit is reached), then calls Filter.next()
- Filter calls LabelScan.next()
- LabelScan returns a row for the next node id with the label, reading the label index a batch at a time
- Filter evaluates predicate—if false, pulls another row
- Limit counts the row and passes it up
- Project evaluates expressions, transforms row
Without aggregation, ORDER BY, SKIP and LIMIT are planned under the
projection, so they can still see variables the projection drops (RETURN n.name ORDER BY n.age). With aggregation they go on top, because they may refer to
aggregated values that only exist after grouping. RETURN DISTINCT splits them:
ORDER BY stays under the projection and its sort keeps every row, while SKIP
and LIMIT go above Distinct, so they count rows after duplicates are removed.
Lazy Evaluation
Rows are produced only when next() is called, and building, filtering and
projecting each row happens on demand: with LIMIT 10, evaluation stops after 10
matching rows. In a query that only reads, a label scan also reads its ids on
demand, so MATCH (n:Person) RETURN n LIMIT 1 reads one batch of the label index
rather than every Person. The other scans, and a label scan in a query that
writes, collect their ids when they open.
Rows and Slots
A Row is a fixed-size tuple flowing between operators:
pub const Row = struct {
slots: [16]SlotValue, // Variable bindings
distances: [16]f32, // Vector search distances
scores: [16]f32, // FTS relevance scores
populated: u16, // Bitmask of populated slots
measured: u16, // Slots whose distance a vector search set
scored: u16, // Slots whose score a full-text search set
};
measured and scored say which slots' distances and scores belong to the
entity now in the slot. Setting a slot clears both bits, so a distance or score
never outlives the node it was measured for, and projection carries them only for
an item that is the same variable in the same slot (WITH d, not WITH d AS e).
Slot Values
Each slot holds one of:
pub const SlotValue = union(enum) {
empty: void, // Unset
node_ref: NodeId, // Reference to a node (just the ID)
edge_ref: EdgeId, // Reference to an edge
property: PropertyValue, // Actual value (int, string, bool, etc.)
};
Why Slots Instead of Named Variables?
Performance. Looking up slots[3] is O(1). The planner assigns each variable to
a numbered slot. For (p:Person)-[r:KNOWS]->(f:Person) it allocates the
relationship's target node before the relationship itself:
| Pattern element | Slot |
|---|---|
(p:Person) | 0 |
(f:Person) | 1 |
[r:KNOWS] | 2 |
A row has 16 slots, so a query can bind at most 16 variables (including
internal ones the planner adds, such as a slot that holds an anonymous
relationship so a later expand can avoid reusing it), and RETURN or WITH can
take at most 16 items; more fails to plan with TooManyVariables.
A name keeps the slot it was first bound to for the whole query. WITH puts an
item named like an earlier variable back in that variable's slot, and new names
take slots no earlier scope used while any are left. If a name would ever need a
second slot, the plan is refused rather than run with expressions reading the
wrong slot. A null result (from UNWIND, WITH or an aggregate) is stored as a
bound null, so reading it gives null; only a slot that was never filled is an
"unbound variable" error.
The execution context maintains the mapping from names to slots for expression evaluation.
Lazy Materialization
Rows store references (NodeId, EdgeId), not full objects. Properties are fetched on-demand during expression evaluation. This avoids loading data that's never accessed.
A node property read (n.name) decodes just that property: the evaluator resolves
the key's id once per query, and Database.getNodePropertyByKeyInTxn answers from
the transaction's overlay when it holds the node and otherwise walks the stored
record to the one value. In a query that only reads, the evaluator also keeps the
last record it read, so n.a, n.b, n.c costs one B+Tree lookup. A storage error
during the read fails the query rather than reading as null. Relationship
properties take the same path (getEdgePropertyByKeyInTxn, which decodes only the
wanted value of the stored record, with a one-record cache in queries that only
read). type(r) reads only the relationship's endpoints and type, and labels(n)
only the node's label ids. properties() still decodes the whole record.
Operators
Scan Operators
AllNodesScan: Iterates every node in the database.
open(): Collect every node id visible to the transaction into a slice,
sorted, so rows come in id order (node keys are little-endian, so
the tree walk alone is not)
next(): Take the next id from the slice, set output slot
close(): Free the slice
LabelScan: Iterates nodes with a specific label.
open(): Query only reads: allocate a 256-id buffer and take the ids the
transaction's overlay gives the label
Query writes: collect every id carrying the label (label index, plus
the transaction's own changes) into a slice
next(): Streaming: refill the buffer from the label index after the last id
read, skip ids the overlay says lost the label, and merge in the
overlay's ids in id order
Collected: take the next id from the slice
Then set the output slot
close(): Free the buffer or the slice
A query that writes collects its ids up front so that nodes it creates, relabels or deletes while scanning cannot change which nodes the scan visits. Streaming relies on nothing else changing the overlay or the index during a read-only query, which holds because the C API runs one call per database handle at a time.
PropertyIndexScan: Used instead of a label scan when an explicit property
index covers an equality on the pattern's label (inline {k: v} or a WHERE
equality right after the MATCH). It evaluates the value once at open and
reads the matching ids from the index.
NodeIdSeek: Used when the WHERE right after the MATCH has, among
its ANDed conditions, id(n) = v, v = id(n) or id(n) IN list, where v
and list do not depend on the row (literals and parameters). It takes the
place of every other scan for that node, labelled or not. At open it evaluates
the value, takes every whole non-negative number in it as an id (so
id(n) = 3.0 finds node 3, as the comparison would), sorts and deduplicates
them, and keeps those that exist as the transaction sees them. The condition
stays in the WHERE and the pattern's labels are checked by LabelFilters,
so the seek only has to offer every node that could match. A WHERE with a
vector or full-text search keeps its own access path. Before it, such a query
read every node and filtered; now it reads only the nodes named.
IndexRangeScan (index_range_scan.zig): Used when no equality applies and
the WHERE right after the MATCH compares an indexed property of the
pattern's node with a value that does not depend on the row (<, <=, >,
>=, either way round, and STARTS WITH). The planner folds every such
conjunct on one property into one range and takes them out of the WHERE
filter (consumed_conjuncts, residualCondition). At open the scan evaluates
the bounds, turns them into a key range, and merges the index's entries with the
transaction's own nodes of the label that fall in it. It re-checks the consumed
conjuncts only where the key cannot decide: a string bound longer than the 128
bytes a key keeps. Like the label scan it streams 256 keys at a time in
read-only queries and collects its ids up front in queries that write. With no
range it can also read a whole label's index in order (property_order_scan),
which holds the nodes that lack the property too, after every value. It reads
forward for an ascending sort and backward, from the last leaf down, for a
descending one; backward, the index gives equal values highest id first, so
the scan collects each run of equal keys and returns it lowest id first, the
order a stable sort leaves a label scan's rows in. When the query sorts on
something the range does not read in order (WHERE n.w > 3 ... ORDER BY n.v),
the scan collects the range's ids and returns them in id order, so rows the
sort finds equal come as they would from a label scan and a LIMIT that cuts
through them keeps the same ones.
OrderedCutoff (same file): Placed under the Sort of ORDER BY n.p [SKIP s] LIMIT k when the scan below reads p's index in order. It passes rows through
and stops once it has passed s + k rows and the sort key moves past the last
of them, so the Sort sees only the rows that can be returned. The planner uses
it for a single MATCH pattern, an optional WHERE without a vector or
full-text search, and a RETURN that neither aggregates nor uses DISTINCT,
sorted first by a property of the scanned node, ascending or descending.
EdgeTypeScan (edge_type_scan.zig): Used for (a)-[r:T]->(b) (or
incoming) when a has no label, properties or earlier binding: one walk of the
edge-ID index, 256 edges at a time, keeping edges of the wanted types whose
start node exists, plus the transaction's staged edges. There is no index from
type to edge (see Graph Storage); this
replaces an expand from every node. Rows come in the edge-ID index's order.
When the one type named has an ordered property index and the WHERE or the
inline map compares that property with a value (=, a range or STARTS WITH), the planner uses IndexRangeScan over the type's index instead
(edge_range_scan), which fills the same three slots in the index's order. The
WHERE keeps the conditions and checks each row. A relationship read through
the index costs several times one found by the walk, so when it opens the scan
counts the range's keys, up to a fifth of the highest relationship id, and walks
the type with EdgeTypeScan instead when it gets there.
All of them produce rows with node references (EdgeTypeScan also fills the
relationship and the other node). None keeps a B+Tree iterator open between
next() calls: the streaming scans open and close their own range for each
batch, so no page stays pinned or latched between calls.
A property index created by this release keys a value by an encoding whose byte
order is ORDER BY's order, in which an integer and the float with the same
value share a key (see Graph Storage).
An index 0.16.0 created keys a digest of the type and bits, so an integer and the
equal float land under different keys; PropertyIndexScan looks up both forms
and merges them, so {age: 30} finds a node stored with 30.0, as a scan would,
and such an index is never used for ranges until it is rebuilt
(Database.upgradePropertyIndexes).
Filter Operator
Evaluates a predicate and passes through only matching rows.
fn next(self: *Filter, ctx: *ExecutionContext) !?*Row {
while (true) {
const row = try self.input.next(ctx) orelse return null;
const result = try self.evaluator.evaluate(self.predicate, row, ctx);
if (result.isTruthy()) {
return row;
}
// Predicate failed, try next row
}
}
Supports short-circuit evaluation for AND/OR.
LabelFilter checks a node's label through the label index
(Database.nodeHasLabelInTxn, which asks the transaction's overlay first)
instead of reading the whole node, and a storage error fails the query.
Project Operator
Transforms rows by evaluating expressions for each output column.
| Return item | Expression |
|---|---|
p.name | expr[0] |
p.age + 1 | expr[1] |
"literal" | expr[2] |
fn next(self: *Project, ctx: *ExecutionContext) !?*Row {
const input_row = try self.input.next(ctx) orelse return null;
self.output_row.clear();
for (self.items) |item| {
const value = try self.evaluator.evaluate(item.expr, input_row, ctx);
self.output_row.setSlot(item.output_slot, resultToSlotValue(value));
}
return self.output_row;
}
Expand Operator
Traverses edges from input nodes. This implements pattern matching like (a)-[r]->(b).
State:
source_slot = slot containing the source node
target_slot = slot to write target node
edge_slot = slot to write edge (optional)
edges = edge references for the current input (a slice)
current_input = row being expanded
next():
loop:
if edges has another edge ref:
output_row = copy input row
output_row[target_slot] = edge.target
output_row[edge_slot] = edge id (if requested)
return output_row
// Exhausted edges for current input, get next input
current_input = input.next()
if null: return null
source = current_input[source_slot]
edges = database.getOutgoingEdgeRefs[ByType]InTxn(txn, source[, type])
A relationship's types reach the expand as an EdgeConstraints value. With one
type the storage layer filters the edges; with several (-[:A|B]->) the operator
reads the node's edges and keeps those whose type is in the set. A type the
database has never seen matches nothing.
Within one MATCH, a relationship is used once. The planner lists every
relationship of the clause, and a single-hop relationship that a later one could
collide with (their type sets overlap, or either is untyped) keeps its edge in a
slot, hidden if it has no variable. Each later expand skips edges already held in
those slots. An undirected expand also skips a self-loop in its incoming half, so
the loop is returned once. When a later relationship could collide with a
variable-length one, the variable-length expand writes the ids of its path's
edges, as a list, into a hidden slot, and EdgeConstraints.usedEarlier skips an
edge found in such a list as it skips one held in an edge slot. The list is built
only when a later relationship needs it, in the row arena so that a row kept by
ORDER BY or collect() stays valid.
Inside a write transaction, the expand merges the stored edges with the
transaction's own. The transaction's overlay files each edge it creates under both
endpoints (edges_by_node), so expanding a node reads only that node's pending
edges, not every edge the transaction has touched; the check that refuses deleting
a node with relationships reads the same list. A transaction that holds no edge
changes, which is every read-only one unless a writer has committed since it
began, takes the stored edges as they come: no lookup in the overlay per edge and
no set of the ids already returned.
When the far end of the relationship is a node that is already bound, the expand keeps only edges that lead to it, and a bound node at the start of a pattern is checked against its labels and properties rather than scanned again.
VariableLengthExpand handles -[*min..max]-> patterns. It is a depth-first
search over a stack of frames that tracks the edges on the current path: an edge
already on the path is skipped, nodes may repeat, and every step whose length is
within the bounds emits a row, so a node reached by two paths is returned twice.
There is no hop cap; an unbounded pattern ends because a path cannot use more
relationships than exist, though the number of paths can grow exponentially on a
dense graph. Edge lists are read only for frames that can still extend. When the
target node carries labels, the planner adds a LabelFilter above the expand.
This is a one-to-many operator: one input row can produce multiple output rows.
Supports three directions:
outgoing:(a)-[r]->(b)— traverse outgoing edgesincoming:(a)<-[r]-(b)— traverse incoming edgesboth:(a)-[r]-(b)— traverse both directions
Limit and Skip
Limit: Returns at most N rows.
fn next(self: *Limit, ctx: *ExecutionContext) !?*Row {
if (self.returned >= self.count) return null;
const row = try self.input.next(ctx) orelse return null;
self.returned += 1;
return row;
}
Skip: Discards the first N rows.
fn next(self: *Skip, ctx: *ExecutionContext) !?*Row {
while (self.skipped < self.count) {
_ = try self.input.next(ctx) orelse return null;
self.skipped += 1;
}
return try self.input.next(ctx);
}
Sort Operator (Blocking)
Sort must see all input before producing any output—it's a blocking operator.
open():
for each input row:
evaluate the row's sort keys once and keep them beside the row
(an evaluation error fails the query)
with a bound: keep the row only if it is among the best SKIP + LIMIT
so far, in a bounded max-heap
order the kept rows by their keys, ties by arrival order
next():
return the next kept row
The planner hands Sort the SKIP and LIMIT that follow it, so ORDER BY ... LIMIT k over n rows costs n log k comparisons and k rows of memory. Sort still
reads all of its input, so writes below it happen. Ties keep input order, so the
result is the same as a stable sort of everything followed by SKIP and LIMIT.
The keys are compared by orderValues, a total order over all values: maps,
nodes, relationships, lists, paths, vectors, bytes, strings, booleans, numbers,
then null (typeRank). NULLS FIRST or NULLS LAST on a sort item puts nulls
where it says, whichever the direction. Nodes and relationships order by id. Integers and floats compare by exact
value (converting the integer to a float would round above 2^53), and NaN is
above every other number.
This breaks the streaming model but is necessary for ordering.
Vector Search Operator
The planner turns a WHERE of the form x.prop <=> $q or x.prop <=> $q < threshold (or <=; the query may also be a literal list) into a
VectorSearchWithInput placed over the pattern's scan. It does not replace
the scan:
open():
resolve the threshold (a literal or a parameter; null matches nothing)
if the input is a label scan of this same variable (openOverLabel):
read the scan only until it holds more nodes than measuring each
would pay for (Database.exactScanCount); a label that ends first is
measured node by node, a larger one is searched through the graph
with the label as the filter, and the rest of the scan is never read
otherwise read every input row, grouped by node; the nodes are the
candidates
k = what bounds the answer: SKIP + LIMIT, or 100 (DEFAULT_K) nodes
loop:
results = database.vectorSearchAmongInTxn(txn, query, k, ids = candidates)
(a few candidates: each measured; many: a graph search
that keeps only candidates as results)
stop when: with a LIMIT or neither bound, always (every result is a
candidate with at least one row);
with a threshold alone, the farthest result is beyond it;
or fewer than k came back
k = 2 * k
if fewer than k came back, measure the candidates the search did not return
next():
emit kept rows in distance order, storing each row's distance
The input rows are the candidates, so the pattern's label narrows the answer, and
a threshold query returns every candidate within it. < is strict and <= is
not. The LIMIT bound applies only when a RETURN with a LIMIT follows with no
DISTINCT or aggregation in between, and with no ORDER BY unless that ORDER BY
is one ascending <=> of this same search (or the alias of a RETURN item that is),
the order the search already returns its rows in. A set small enough to measure
(see Vector Search, limitation 4) is answered exactly; what
stays approximate is HNSW recall over a large set, and with that ORDER BY the
answer is the index's approximate top k, as it is under a plain LIMIT. The
property name in x.prop is not used to choose an index: a database has one
vector index. Distances are measured with the metric recorded for the index, and
the operator measures candidates the search did not return with the same metric.
The distance is stored in the row and marked as measured. The planner records each
vector search's variable, property and query (VectorQueries), and an x.prop <=> query elsewhere in the query written the same way returns the stored distance
instead of computing it again. (A leaf
VectorSearch operator, which emits the search results directly, also exists
in vector.zig, but the planner does not use it.)
FTS Operators
There are two, and which one the planner picks is the difference between reading an index and reading a corpus.
FtsIndexSeek is a leaf. It searches the declared index and emits one row per
hit, in score order. It has no input because it needs none: a Document.body
index holds only Document nodes, so seeking it does the label scan's job as well
as answering the text question.
fn open(self: *FtsIndexSeek, ctx: *ExecutionContext) !void {
self.results = try runSearches(self.database, ctx, self.searches, self.limit, self.allocator);
}
fn next(self: *FtsIndexSeek, _: *ExecutionContext) !?*Row {
const hit = self.results.?[self.current_index];
self.current_index += 1;
self.row.?.setSlot(self.output_slot, .{ .node_ref = hit.doc_id });
self.row.?.setScore(self.output_slot, hit.score);
return self.row;
}
FtsSearchWithInput filters rows somebody else produced, keeping those the index named. It is what runs when the entity is already bound by an upstream expand, so the input decides which rows exist and the index can only narrow them.
Both run their searches through one shared function, so they cannot come to
disagree about what a disjunction of @@ predicates means. Both store each hit's
BM25 score in the row and mark it as scored, which is what score(d) reads.
When the MATCH has a seek with a single search and its WHERE is that same
search (same variable, index, and query text or parameter), the planner adds no
FtsSearchWithInput for it: every row the seek emits already matches.
The full reasoning, including the measurements that motivated the seek, is in Full-Text Search, section 16.
Mutation Operators
Mutation operators modify the graph structure. Unlike read operators, they have side effects.
The snippets below are simplified; the real operators call Database methods
with the execution context's transaction.
CreateNode: Creates new nodes with labels and properties.
fn next(self: *CreateNode, ctx: *ExecutionContext) !?*Row {
const node_id = try ctx.storage.createNode(self.labels);
for (self.properties) |prop| {
const value = try self.evaluator.evaluate(prop.value, null, ctx);
try ctx.storage.setProperty(node_id, prop.key, value);
}
self.output_row.setSlot(self.output_slot, .{ .node_ref = node_id });
return &self.output_row;
}
DeleteNode: Removes nodes from the graph. With DETACH, also removes connected edges.
first next():
drain the input, collecting each target node once (null targets are skipped)
without DETACH: if any collected node still has a relationship
(Database.nodeHasRelationshipsInTxn), fail with NodeHasRelationships
before deleting anything; then Database.deleteNode each node
with DETACH: Database.detachDeleteNode each node
then: return the drained rows one at a time
The rule lives in the database, so lattice_node_delete refuses the same nodes and
lattice_node_detach_delete does what DETACH DELETE does. A refused DELETE
returns LATTICE_ERROR_HAS_RELATIONSHIPS through the C API, and a CREATE of a
relationship to a node deleted earlier in the query LATTICE_ERROR_NOT_FOUND, the
codes the direct calls return.
Draining first is what lets DELETE r, n work: the DeleteEdge below it in the
chain has removed every r before any node is checked. DeleteEdge treats a
relationship this statement already deleted as done, since an undirected match
lists each relationship from both ends.
SetProperty: Updates properties on nodes or edges.
MATCH (n:Person {name: "Alice"}) SET n.age = 31, n.city = "NYC"
fn next(self: *SetProperty, ctx: *ExecutionContext) !?*Row {
const row = try self.input.next(ctx) orelse return null;
const target = row.slots[self.target_slot];
const value = try self.evaluator.evaluate(self.value_expr, row, ctx);
// SET n.prop = NULL removes the property
if (value == .null_val) {
try ctx.storage.removeProperty(target, self.property_name);
} else {
try ctx.storage.setProperty(target, self.property_name, value);
}
return row;
}
SetLabels: Adds labels to nodes.
MATCH (n:Person {name: "Alice"}) SET n:Admin:Verified
RemoveProperty: Explicitly removes properties.
MATCH (n:Person {name: "Alice"}) REMOVE n.city
RemoveLabels: Removes labels from nodes.
MATCH (n:Person {name: "Alice"}) REMOVE n:Verified
The remaining mutation operators are CreateEdge, DeleteEdge,
SetPropertiesReplace (SET n = {...}), SetPropertiesMerge
(SET n += {...}), and MergeNode / MergeEdge for MERGE.
MergeNode evaluates the pattern's properties once (a null value is an
error), then takes candidates from a property index on one of the pattern's
labels when one exists, otherwise from the first label's index, otherwise from
every node. It keeps the candidates that carry every label and every property,
comparing as = does, and emits a row for each, applying ON MATCH to each. It
creates a node only when nothing matches. A label or property name the database
has never seen means nothing can match.
Operator Inventory
| File | Operators |
|---|---|
scan.zig | AllNodesScan, LabelScan, PropertyIndexScan, NodeIdSeek |
index_range_scan.zig | IndexRangeScan, OrderedCutoff |
edge_type_scan.zig | EdgeTypeScan |
source.zig | SingleRow (one empty row: the input of a query that starts with UNWIND or RETURN) |
filter.zig | Filter, LabelFilter |
expand.zig | Expand |
var_expand.zig | VariableLengthExpand |
cross_product.zig | CrossProduct (disconnected patterns) |
project.zig | Project |
aggregate.zig | Aggregate (count, count(*), sum, avg, min, max, collect) |
distinct.zig | Distinct |
limit.zig | Limit, Skip, Sort |
materialize.zig | Materialize (drains its input before mutations run, so a clause's reads finish before its first write and see the graph as it was when the clause began) |
unwind.zig | Unwind |
vector.zig | VectorSearchWithInput (and the unused leaf VectorSearch) |
fts.zig | FtsIndexSeek, FtsSearchWithInput |
optional.zig | Argument (the leaf a plan run once per input row starts from), Apply (OPTIONAL MATCH), Foreach, CallSubquery (CALL { ... }) |
subquery.zig | SubqueryHost, SubqueryPlan (EXISTS { }, COUNT { }, COLLECT { }, pattern predicates and pattern comprehensions, run by the expression evaluator for the row it is evaluating) |
union.zig | Union (UNION ALL; UNION puts a Distinct on top) |
path.zig | BindPath (a named path, p = (a)-[r]->(b)) |
shortest_path.zig | ShortestPath (shortestPath, allShortestPaths: breadth-first from both ends) |
procedure.zig | ProcedureCall (CALL db.labels(), db.relationshipTypes(), db.propertyKeys(), db.indexes()) |
mutation.zig | CreateNode, CreateEdge, DeleteNode, DeleteEdge, SetProperty, SetLabels, SetPropertiesReplace, SetPropertiesMerge, RemoveProperty, RemoveLabels, MergeNode, MergeEdge |
Expression Evaluation
The expression evaluator handles predicates and projections.
pub fn evaluate(expr: *const Expression, row: *const Row, ctx: *ExecutionContext) !EvalResult {
return switch (expr.*) {
.literal => |lit| evaluateLiteral(lit),
.variable => |v| evaluateVariable(v, row, ctx),
.property_access => |pa| evaluatePropertyAccess(pa, row, ctx),
.binary => |b| evaluateBinary(b, row, ctx),
.unary => |u| evaluateUnary(u, row, ctx),
.function_call => |f| evaluateFunction(f, row, ctx),
// ...
};
}
Supported Operations
Comparison: =, <>, <, <=, >, >=
Logical: AND, OR, NOT, XOR (with short-circuit evaluation)
Arithmetic: +, -, *, /, %, ^, unary -
String: CONTAINS, STARTS WITH, ENDS WITH, =~ (regular expression match)
List: IN
Null handling: IS NULL, IS NOT NULL, which always give true or false. Every
other operator follows three-valued logic: a comparison, arithmetic or string
operation with a null operand is null, NOT/AND/OR are Kleene (false AND null
is false, true OR null is true), and Filter keeps a row only when the predicate is
true
Functions (names are matched without regard to case):
- Graph and type:
id(),labels(),type(),properties() - Numeric and conversion:
abs(),toInteger(),toFloat(),toString(),coalesce() - String:
toUpper(),toLower(),trim(),replace(),substring(),split() - List:
size(),head(),last(),tail(),range() - Search:
score()
Each built-in function is described once, in builtin_functions in
expression.zig (name, argument counts, signature text). Semantic analysis checks
every call against it, so an unknown name or a wrong argument count is a semantic
error with its location before anything is planned, and a unit test keeps the
table and evaluateFunction in step. String functions count and cut in Unicode
code points and case-map with the simple one-to-one mappings the full-text
tokenizer folds with.
Aggregates (planned as an Aggregate operator): count(), count(*),
sum(), avg(), min(), max(), collect(). Every aggregate but count(*)
skips nulls. sum of integers is computed exactly in an i128 and must fit in
an i64; any float makes it a float. min and max compare values with the
same total order as ORDER BY, so they are defined over mixed types.
Regular expressions: =~ compiles its pattern with src/query/regex.zig into
a small program and runs it as a Pike VM, which follows every alternative at once,
so matching takes time proportional to the text length times the program size.
Each execution caches up to 32 compiled patterns. The supported syntax is listed
in that file; backreferences and lookaround fail the query.
Vector Search: <=> (vector distance operator)
// k-NN search with distance threshold
MATCH (c:Chunk) WHERE c.embedding <=> $query < 0.5 RETURN c
Full-Text Search: @@ (FTS match operator)
// BM25-scored full-text search
MATCH (d:Doc) WHERE d.text @@ $search RETURN d
MATCH (d:Doc) WHERE d.text @@ "neural networks" RETURN d
These operators are recognized by the planner and converted to specialized search operators that use the HNSW and FTS indexes.
For full-text search, an FtsIndexSeek reads the index instead of scanning,
but only in conjunctive positions — the whole WHERE, or a branch of an AND.
Under an OR the planner keeps the label scan on purpose, because the other
branch can admit entities the index never names and seeking would silently drop
them.
Vector search does not avoid the scan. The <=> pattern is recognised only when
it is the whole WHERE clause and its threshold is a number or a parameter; it
is then planned as VectorSearchWithInput over the label (or all-nodes) scan,
which searches among the scan's nodes only (see
Vector Search Operator). Any other <=> predicate is
evaluated by Filter, row by row and exactly.
Type Coercion
Numeric operations promote integers to floats when mixed:
42 + 3.14 → 45.14 (float)
Comparisons do not: an integer and a float compare by their exact values
(compareIntFloat), in =, < and the other comparisons, in ORDER BY, and in
MERGE. Keys for DISTINCT and grouping write a float that an i64 can hold
exactly as that integer, -0.0 as 0 and every NaN as one NaN, so the groups are
the classes = defines.
Null propagates through most operations, and comparisons follow Cypher's three-valued logic:
null + 1 → null
null = null → null (use IS NULL to test for null)
A WHERE keeps a row only when its predicate is true; false and null
both drop it.
The Query Planner
The planner transforms an AST into an operator tree by walking the query clauses.
Planning Algorithm
Simplified from QueryPlanner.plan in planner.zig:
pub fn plan(query: *Query) !Operator {
// q1 UNION [ALL] q2 ...: each single query planned on its own, under a
// Union (and a Distinct for UNION)
var current: ?Operator = if (query.unions.len == 0)
try planClauses(query.clauses)
else
try planUnion(query);
// EXISTS / COUNT / COLLECT subqueries and pattern predicates are planned
// over Argument leaves and hung from a SubqueryHost at the root
if (query.subqueries.len > 0) current = try hostSubqueries(query, current);
return current orelse error.InvalidQuery;
}
fn planClauses(clauses: []Clause) !?Operator {
var current: ?Operator = null;
for (clauses, 0..) |clause, i| {
current = switch (clause) {
// OPTIONAL MATCH, with its WHERE, becomes an Apply over a plan
// that starts from an Argument leaf
.match => if (clause.match.optional)
try planOptionalMatch(clause.match, whereAfter(i), current orelse singleRow())
// The following WHERE is passed in so an index can be chosen
else
try planMatch(clause.match, current, whereAfter(i)),
.where => try planWhere(clause.where, current),
// Also plans the ORDER BY / SKIP / LIMIT that follow it:
// underneath the projection, or on top if it aggregates
// (with DISTINCT, SKIP and LIMIT on top)
.return_ => try planReturnAndTrailing(clause.return_, current),
.order_by => try planOrderBy(clause.order_by, current),
.limit => try planLimit(clause.limit, current),
.skip => try planSkip(clause.skip, current),
.create => try planCreate(clause.create, current),
.delete => try planDelete(clause.delete, current),
.set => try planSet(clause.set, current),
.remove => try planRemove(clause.remove, current),
.with => try planWith(clause.with, current),
.merge => try planMerge(clause.merge, current),
.unwind => try planUnwind(clause.unwind, current),
.foreach => try planForeach(clause.foreach, current orelse singleRow()),
// CALL { ... }: run once per incoming row
.call_subquery => try planCallSubquery(clause.call_subquery, current orelse singleRow()),
// CALL db.labels() and the other catalog procedures
.call => try planCall(clause.call, current orelse singleRow(), standalone(i)),
};
}
return current;
}
Example: Simple Query
MATCH (p:Person) WHERE p.age > 30 RETURN p.name LIMIT 10
Produces:
Project([p.name → slot 0])
└── Limit(count=10)
└── Filter(p.age > 30)
└── LabelScan(label="Person", output=slot 0)
Example: Edge Traversal
MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.name, b.name
Produces:
Project([a.name → slot 0, b.name → slot 1])
└── LabelFilter(slot 1, label="Person")
└── Expand(source=0, target=1, type="KNOWS", dir=outgoing)
└── LabelScan(label="Person", output=slot 0)
Variable Binding
The planner allocates slots for variables. For (a)-[r]->(b):
| Variable | Slot | Kind |
|---|---|---|
| a | 0 | node |
| b | 1 | node |
| r | 2 | edge |
These bindings are registered in the ExecutionContext for expression evaluation.
Execution Context
Runtime state for query execution:
pub const ExecutionContext = struct {
allocator: Allocator,
row_arena: ArenaAllocator, // Fast row allocation
parameters: StringHashMap(PropertyValue), // Query parameters ($name)
variables: StringHashMap(u8), // Variable → slot mapping
node_store: ?*NodeStore, // Property lookups
symbol_table: ?*SymbolTable, // Property key resolution
database: ?*Database, // Mutations and searches
txn: ?*Transaction, // Transaction reads and writes go through
fts_cache: ?*FtsFilterCache = null, // Full-text results reused within one execution
};
Row Arena
Rows are allocated from an arena that's reset between queries. This avoids per-row allocation overhead:
// During query execution
const row = try ctx.allocRow(); // Fast bump allocation
// After query completes
ctx.resetRowArena(); // Frees all rows at once
Query Parameters
Parameters allow safe value injection:
MATCH (p:Person) WHERE p.age > $min_age RETURN p
try ctx.setParameter("min_age", .{ .int_val = 30 });
Operator Composition
Operators are composable—any operator can wrap any other:
// Filter wrapping Expand wrapping LabelScan
Filter
└── Expand
└── LabelScan
// Limit wrapping Sort wrapping Filter
Limit
└── Sort
└── Filter
└── ...
This enables flexible query plans without special-casing combinations.
Memory Management
Operator Lifecycle
1. Planner creates operators in a per-query arena
2. Executor calls open() on root (cascades down)
3. Executor calls next() repeatedly (rows flow up)
4. Executor calls close() on root (cascades down)
5. The query arena is freed, taking the operators with it
Every operator has a deinit() in its vtable, but Database.query() does not
need it: the operators, the plan and intermediate evaluation results all live in
the query's arena.
Resource Cleanup
Operators release what they acquired in open() from close(). For the scans
that is the id slice they collected:
fn close(ptr: *anyopaque, _: *ExecutionContext) void {
const self: *LabelScan = @ptrCast(@alignCast(ptr));
if (self.node_ids) |node_ids| {
self.database.allocator.free(node_ids);
self.node_ids = null;
}
}
Operators that do hold storage resources across calls must release them here, or pinned pages leak.
The executor closes the tree only after a successful open(). An operator that
drains its input while opening (Aggregate, Distinct, Sort, Materialize,
CrossProduct) therefore closes that input itself when the drain fails, so a
query that fails during open leaves nothing open behind it.
Future Optimizations
The current planner uses simple heuristics. Future improvements could include:
Predicate Pushdown
Move filters closer to scans:
Before: Filter(a.x > 10) → Expand → LabelScan
After: Expand → Filter(a.x > 10) → LabelScan
Cost-Based Index Selection
The planner already selects explicit property indexes for eligible inline and
immediately following WHERE equalities, ranges and prefixes, and for an
ORDER BY ... LIMIT in either direction. Its rule has no statistics: an equality first,
then a range on the property the query sorts by (read in order), then the first
indexed property with a range, then an ordered read for the sort; a range is
always preferred to the label scan. A future cost model could choose between
available label and property indexes using cardinality and selectivity
statistics instead.
Join Ordering
For multi-pattern queries, order joins by estimated cardinality.
Vectorized Execution
Process rows in batches instead of one-at-a-time for better cache utilization.
Database Query API
The Database.query() method provides the primary interface for executing Cypher queries. It orchestrates all components of the query pipeline.
Basic Usage
// Open database (returns *Database)
const db = try Database.open(allocator, "mydb.ltdb", .{ .create = true });
defer db.close();
// Create some data (null = no explicit transaction)
_ = try db.createNode(null, &[_][]const u8{"Person"});
_ = try db.createNode(null, &[_][]const u8{"Person"});
// Execute a query
var result = try db.query("MATCH (n:Person) RETURN n");
defer result.deinit(); // Always clean up results
// Process results
std.debug.print("Found {} rows\n", .{result.rowCount()});
for (result.rows) |row| {
for (row.values) |val| {
switch (val) {
.node_id => |id| std.debug.print("Node: {}\n", .{id}),
.string_val => |s| std.debug.print("String: {s}\n", .{s}),
.int_val => |i| std.debug.print("Int: {}\n", .{i}),
.null_val => std.debug.print("null\n", .{}),
else => {},
}
}
}
Result Types
/// A single value in a query result
pub const ResultValue = union(enum) {
null_val: void, // NULL
bool_val: bool, // true/false
int_val: i64, // integers
float_val: f64, // floating point
string_val: []const u8, // strings
node_id: NodeId, // node reference
edge_id: EdgeId, // relationship reference
bytes_val: []const u8, // byte strings
vector_val: []const f32, // vectors
list_val: []const ResultValue, // lists
map_val: []const MapEntry, // maps
};
/// A row in a query result
pub const ResultRow = struct {
values: []ResultValue, // One value per column
};
/// Complete query result
pub const QueryResult = struct {
columns: [][]const u8, // Column names from RETURN clause
rows: []ResultRow, // Result rows
allocator: Allocator,
pub fn deinit(self: *QueryResult) void; // Free all memory
pub fn rowCount(self: *const QueryResult) usize;
pub fn columnCount(self: *const QueryResult) usize;
};
Error Handling
The query() method returns QueryError on failure:
pub const QueryError = error{
ParseError, // Syntax error in Cypher
SemanticError, // Undefined variable, type mismatch
PlanError, // Query cannot be planned
ExecutionError, // Runtime error during execution
OutOfMemory,
};
Example error handling:
const result = db.query("MATCH (n RETURN n"); // Missing )
if (result) |res| {
var r = res; // deinit needs a mutable QueryResult
defer r.deinit();
// process results
} else |err| switch (err) {
QueryError.ParseError => std.debug.print("Syntax error\n", .{}),
QueryError.SemanticError => std.debug.print("Semantic error\n", .{}),
else => std.debug.print("Query failed: {}\n", .{err}),
}
query() keeps only the stage. queryDetailed() returns a QueryDetailedResult,
whose failure case is a QueryFailure: the stage, the message, a diagnostic
code ("DivisionByZero", "unknown_function", ...), the line, column and length
of the part of the query at fault, and a cause that says whether the query itself
failed (.query), the storage underneath it (.storage), or memory ran out
(.out_of_memory):
var detailed = try db.queryDetailed("RETURN 1/0");
defer detailed.deinit();
switch (detailed) {
.success => |res| { _ = res; },
.failure => |f| std.debug.print("{s}: {s}\n", .{ @tagName(f.stage), f.message }),
// execution: Division by zero: 1 / 0
}
Operators and the evaluator record the message and location through
ExecutionContext.fail at the point of failure, and executeParsed copies them
into the QueryFailure. The C API maps cause to LATTICE_ERROR_IO or
LATTICE_ERROR_OUT_OF_MEMORY, and the execution codes NodeHasRelationships and
NotFound to the codes lattice_node_delete and lattice_edge_create return;
any other failure is LATTICE_ERROR_INVALID_ARG (parse, semantic) or
LATTICE_ERROR (plan, execution). Planner refusals carry a detail saying what is
not supported, such as "CREATE needs a node at each end of a relationship".
Internal Pipeline
When you call db.query(cypher), the following happens:
1. normalizeCypher(cypher), then look it up in the query cache
├── hit: reuse the cached AST and variable bindings (skip 2 and 3)
└── miss: run 2 and 3, then store the result in the cache
2. Parser.init(allocator, cypher)
└── parser.parse() → AST (or ParseError)
3. SemanticAnalyzer.init(allocator)
└── analyzer.analyze(ast) → AnalysisResult (or SemanticError)
4. QueryPlanner.init(query_arena, storage_context)
└── planner.plan(ast, analysis) → Operator tree (or PlanError)
5. If no transaction was passed, the query writes, and the database is
writable: begin a read-write transaction
6. ExecutionContext.initWithStorage(...)
└── Register variable bindings from planner, attach the transaction
7. execute(query_arena, root_operator, context)
└── Pull rows through operator tree → executor.QueryResult
8. convertResult(exec_result, planner)
└── Transform to user-friendly QueryResult
9. Commit the automatic transaction (it is aborted if any step fails)
The query cache holds up to 128 entries by default (enable_query_cache,
query_cache_size). It caches parsed and analysed queries, not plans: every
execution is planned afresh, so planning decisions follow the current indexes
and data. Schema changes, such as creating or dropping an index, invalidate the
cache.
A prepared query takes a shorter path. Database.prepareCached parses and
analyses through the cache and returns the entry pinned; the C API keeps it on
the query handle, lattice_query_writes answers from its AST, execution runs it
through executePreparedDetailedInTxn (steps 4 to 9 above), and
lattice_query_free unpins it. A pinned entry survives cache clears and
eviction, and a prepared query run N times counts as one cache lookup, at
prepare. A query that does not parse still prepares, without an entry, and
executing it parses it and reports the error. With more than 128 prepared
queries open, new ones fall back to uncached parsing.
The automatic transaction is why a single write query is atomic. Only one read-write transaction may be open at a time, so a write query run while another writer is open fails rather than waits.
The StorageContext connects the planner to database storage:
const storage_ctx = StorageContext{
.node_tree = &self.node_tree, // B+Tree for nodes
.label_index = &self.label_index, // Label → NodeId index
.edge_store = &self.edge_store, // Edge storage
.symbol_table = &self.symbol_table, // String interning
.hnsw_index = ..., // Vector index, if enabled
.fts_index = ..., // Full-text index, if enabled
.database = self, // Transaction-aware reads and writes
};
Memory Management
- QueryResult owns all memory: Call
deinit()when done - Strings are copied: Safe to use after query components are freed
- Row arena: Internal rows use arena allocation, reset between queries
Files
| File | Purpose |
|---|---|
src/storage/database.zig | Database.query() API, QueryResult types |
src/query/executor.zig | Operator interface, Row, ExecutionContext |
src/query/expression.zig | Expression evaluator |
src/query/planner.zig | AST to operator tree transformation |
src/query/cache.zig | Parsed-query cache |
src/query/operators/scan.zig | AllNodesScan, LabelScan, PropertyIndexScan |
src/query/operators/filter.zig | Filter, LabelFilter |
src/query/operators/project.zig | Project operator |
src/query/operators/expand.zig | Edge traversal |
src/query/operators/var_expand.zig | Variable-length traversal |
src/query/operators/aggregate.zig | Aggregation |
src/query/operators/vector.zig | HNSW k-NN search |
src/query/operators/fts.zig | Full-text search |
src/query/operators/limit.zig | Limit, Skip, Sort |
src/query/operators/mutation.zig | CREATE, DELETE, SET, REMOVE, MERGE |
src/query/operators/*.zig | Others: see Operator Inventory |
Benchmarks
Every number on this page was measured through the public C API
(include/lattice.h against a ReleaseFast liblattice), the way an application or
a binding meets the database, with the options a user gets by default unless a row
says otherwise. The program is tests/benchmark/capi_bench.c; the commands that
produce these tables are under Reproducing.
| Version | 0.17.0 (release/0.17.0 at 75de895), ReleaseFast |
| Machine | Apple M5, 10 cores, 24 GB, internal SSD, macOS 26.5 |
| Date | 2026-11-13 |
| Defaults | write-ahead log on; sync mode full (the log is fsynced on every commit; plain fsync, not F_FULLFSYNC); 100 MB page cache; changefeed keeps every event; automatic checkpoint every 1,000 log frames |
| Load | one thread; nothing else measuring or building, desktop applications open (load average about 2) |
Each row ran several times (five unless it says otherwise), each run a fresh process on a fresh database. A figure is the median of the runs; the range in brackets is the lowest and highest run. Within a run, p50 and p99 are taken over every timed operation. Times are wall-clock.
Writes
A commit here is everything from lattice_begin to the return of
lattice_commit: the log record is written and fsynced, so the transaction
survives a crash once the call returns. A node is lattice_node_create with a label
and two properties (an integer and a short string).
| Operation | p50 | p99 | p99.9 | Throughput |
|---|---|---|---|---|
| Create one node, one commit | 44 us [44–45] | 70 us [61–74] | 1.4 ms [0.2–1.9] | 18,900/s [15,600–21,600] |
| Create one edge (100K nodes present), one commit | 44 us [42–46] | 67 us [58–78] | 1.1 ms [0.2–3.0] | 15,400/s [8,200–22,600] |
20,000 commits per run. About one commit in a few hundred also runs an automatic checkpoint (every 1,000 log frames), writing the pages the log changed into the database file; those, and the disk's own occasional stalls, are the p99.9. The slowest single commit in a run ranged from 2 ms to over 200 ms, from run to run and in 0.16.0 as well, so it is not given as a figure; throughput, which is the mean, moves with it.
Batched: N nodes or edges per transaction, the rate counting every commit (the time to close the database is not included).
| Transaction size | Nodes/s | Time per transaction | Edges/s (100K nodes) |
|---|---|---|---|
| 10 | 130,000 [117,000–144,000] | 63 us | |
| 100 | 284,000 [274,000–295,000] | 0.28 ms | |
| 1,000 | 332,000 [320,000–337,000] | 2.4 ms | 247,000 [245,000–248,000] |
| 10,000 | 351,000 [345,000–353,000] | 27 ms | 252,000 [244,000–254,000] |
Other settings
These rows change one setting from the defaults, and are labelled so.
| Operation | Setting | p50 | p99 | Throughput |
|---|---|---|---|---|
| Create one node, one commit | sync_mode = normal | 6.4 us [6.3–6.5] | 14 us [14–15] | 102,000/s [86,000–116,000] |
| Nodes in transactions of 1,000 | sync_mode = normal | 339,000/s [328,000–341,000] |
normal hands each commit to the operating system without waiting for the disk:
it survives the process being killed, and a power cut can lose the last commits
(see Durability). Once a transaction holds a
thousand rows the fsync no longer shows.
Bulk load
1,000,000 nodes, then 2,000,000 edges between random pairs of them, in transactions of 10,000, then close (three runs).
| Settings | Total | Nodes | Edges | File | Peak memory |
|---|---|---|---|---|---|
| Defaults | 34.4 s [34.3–35.0] | 3.5 s | 30.9 s | 500 MB | 175 MB |
| No log, changefeed off, 1 GB cache (the bulk-load recipe) | 7.9 s [7.8–8.0] | 1.1 s | 6.3 s | 364 MB | 1.1 GB |
The recipe gives up crash safety for the load (an interrupted load is started again from its source) and the changefeed's record of it; the file is smaller because the changefeed holds no events.
Point lookups
100,000 nodes, each with an indexed integer uid. The database was written,
closed and reopened, and every node read once before timing, so the pages are in
the cache: these are warm reads. Uniformly random nodes.
| Operation | p50 | p99 |
|---|---|---|
lattice_node_get_property inside an open read transaction | 0.22 us | 0.24 us |
| Begin a read transaction, read one property, commit | 0.34 us | 0.36 us |
Cypher MATCH (n:Person {uid: $uid}) RETURN n.name (prepared once) | 2.3 us | 2.5 us |
| The same, prepared and freed on every call | 2.4 us | 2.7 us |
Cypher MATCH (n) WHERE id(n) = $id RETURN n.name (prepared once) | 1.1 us | 1.3 us |
A Cypher row is what a binding's query call does: bind the parameter, begin a
read transaction, execute, read every row, free the result, commit. The two
property-read rows are timed 100 and 10 calls at a time, so their percentiles are
of those groups' means. Run-to-run ranges were within 5% for every row.
Graph traversal
A graph of Person nodes with 5 outgoing KNOWS edges each to uniformly random
other nodes. Each query starts at a random node found through the uid index and
returns a count; the prepared query runs as in the lookups above. "Paths" is the
mean count returned, which is the work the query did.
| Query | 10K nodes, 50K edges: p50 | p99 | 100K nodes, 500K edges: p50 | p99 | Paths |
|---|---|---|---|---|---|
(a {uid: $uid})-[:KNOWS]->(b) RETURN count(b) | 2.5 us | 5.4 us | 4.8 us | 7.2 us | 5 |
two hops, count(c) | 4.4 us | 6.6 us | 8.8 us | 12 us | 25 |
two hops, count(DISTINCT c) | 5.3 us | 5.7 us | 6.7 us | 7.3 us | 25 |
three hops, count(d) | 14 us | 16 us | 21 us | 30 us | 125 |
-[:KNOWS*1..5]->(b) RETURN count(b) | 472 us | 499 us | 600 us | 661 us | 3,904 |
lattice_edge_get_outgoing (C API, read transaction included) | 0.63 us | 0.75 us | 0.75 us | 1.0 us | 5 |
A variable-length pattern enumerates paths, one at a time, so its cost follows the number of paths (here 5 + 25 + 125 + 625 + 3,125), not the number of nodes reached: about 0.12 to 0.15 us per path. See Variable-Length Paths.
Full-text search
Documents of 50 words drawn from a 5,000-word vocabulary with a Zipf distribution
(a few words very common, most rare), indexed by a declared full-text index on
Doc.text as they were written (transactions of 1,000). Searches ask
lattice_fts_search for the top 10 by BM25, with query words chosen uniformly
among the 20th to the 2,000th most frequent, so a query word appears in between
about 0.3% and 27% of the documents.
| 10,000 documents | 100,000 documents | |
|---|---|---|
| One word: p50 / p99 | 8.5 us / 103 us | 104 us / 1.2 ms |
| Two words (both required): p50 / p99 | 9.0 us / 70 us | 78 us / 0.70 ms |
| Indexing rate | 29,800 docs/s | 28,200 docs/s |
| File size | 36 MB | 172 MB |
Ranking reads every posting of the query's words, so a search costs in proportion to how many documents contain them: the p99 is the common words, which at 100,000 documents match tens of thousands. The file holds the text, the index (with word positions, for phrase queries), and the changefeed's record of every write.
Vector search
128-dimensional vectors, cosine distance, the default index (m 16,
ef_construction 200, ef_search 64), top 10. The vectors are clustered (one
centre per thousand vectors, at least ten, plus Gaussian noise of 0.1 per
dimension, normalised); each query is a stored vector plus noise of 0.05 per
dimension. Recall@10 is against an exact search over 200 queries. Vectors were
inserted with lattice_batch_insert, 1,000 per transaction; the searches ran in a
fresh process after reopening, 1,000 timed searches after 100 warm-up ones (three
runs per scale, one at 1M).
| Vectors | Insert rate | Search p50 | p99 | Recall@10 | File | Memory |
|---|---|---|---|---|---|---|
| 1,000 | 3,800/s | 35 us | 42 us | 100% | 1.2 MB | 3 MB |
| 10,000 | 2,800/s | 66 us | 73 us | 98.6% | 11 MB | 13 MB |
| 100,000 | 1,830/s | 122 us | 192 us | 98.3% | 108 MB | 108 MB |
| 1,000,000 | 224/s | 1.34 ms | 3.1 ms | 95.6% | 1,074 MB | 185 MB |
"Memory" is what opening the database and running the searches added to the process's footprint (the figure Activity Monitor shows). It follows the file until the file outgrows the 100 MB page cache, which bounds it. Run-to-run ranges were within 5% at 1K to 100K; the 1M row is one run.
The default cache is the limit at a million vectors. Once the file outgrows the 100 MB cache (at about 100,000 vectors), searches read pages back from the operating system and inserts slow down steeply: building 250,000 vectors, the rate fell from 1,500/s over the first 90,000 to 400/s by 230,000, where with a 2 GB cache it held at about 1,450/s throughout. With the cache sized to the file (one run each):
| Vectors | Cache | Build | Insert rate | Search p50 | p99 | Recall@10 | Memory |
|---|---|---|---|---|---|---|---|
| 250,000 | 100 MB (default) | 6.0 min | 693/s | ||||
| 250,000 | 2 GB | 2.9 min | 1,425/s | ||||
| 1,000,000 | 100 MB (default) | 75 min | 224/s | 1.34 ms | 3.1 ms | 95.6% | 185 MB |
| 1,000,000 | 2 GB, searching the default build | 0.21 ms | 0.46 ms | 95.6% | 1.1 GB | ||
| 1,000,000 | 2 GB, built and searched | 17.7 min | 939/s | 0.22 ms | 0.58 ms | 92.6% | 1.1 GB |
The two 1M builds hold the same vectors but are different graphs (an HNSW node's
level is random), and their recall at the default ef_search differs by three
points: at this scale, treat recall@10 at ef_search 64 as about 93–96% on this
data, and use 128 where the last points matter. Opening the 1M database took 4.0 s
with the default cache and 1.2 s with the larger one.
ef_search
Mean latency and recall@10 for other ef_search values (lattice_vector_search's
argument; 0 means the default, 64).
| ef_search | 10,000: mean | recall | 100,000: mean | recall | 1,000,000: mean | recall |
|---|---|---|---|---|---|---|
| 16 | 28 us | 92.0% | 55 us | 90.7% | 0.71 ms | 72.5% |
| 32 | 44 us | 97.0% | 86 us | 96.3% | 1.05 ms | 87.7% |
| 64 (default) | 67 us | 98.6% | 123 us | 98.3% | 1.54 ms | 95.6% |
| 128 | 100 us | 98.9% | 180 us | 98.5% | 2.0 ms | 98.4% |
| 256 | 154 us | 98.9% | 266 us | 98.5% | 2.5 ms | 98.5% |
The 1M column is with the default 100 MB cache. Recall stops rising at about
98.5–99% on this data: past ef_search 128, a larger search list finds nothing
more.
Developer benchmarks
zig build benchmark, vector-benchmark, graph-benchmark, sqlite-benchmark,
storage-benchmark and fts-benchmark remain for working on the engine. They call
internal Zig paths directly, some with the log off, the graph ones over an
in-memory adjacency cache that queries, the C API and the bindings never read, and
the vector one against the HNSW index without the database around it. Their
figures are not comparable to the tables on this page and are not published.
Earlier versions of this page quoted those programs (a 0.13 us node lookup, a 0.65 us node creation, 0.83 ms vector search at 1M, an optimisation history of the vector index). Those were measured on an Apple M1, on older releases, by that method; they are withdrawn rather than carried forward.
Reproducing
From the repository root, on an idle machine (Python 3 and the system SQLite are needed; nothing else):
zig build capi-benchmark # every table above but the 1M rows (~15 min)
zig build capi-benchmark -- --suite vector-1m # the 1M-vector row (~80 min; a 1 GB file, then a 2 GB cache)
zig build capi-benchmark -- --suite vector-cache # the 250K builds and the 1M build with a 2 GB cache (~30 min)
zig build capi-benchmark -- --list # what each suite runs
zig build capi-benchmark -- --suite core --json now.json # keep every run's numbers
Each row prints its median and range; --json keeps every run. One workload can be
run by hand, for example
zig-out/bin/capi-bench commit_node --db /tmp/x.db --ops 5000; it prints one
RESULT line.
To compare two versions with the same program, build it against the other checkout and compare the saved runs:
python3 tests/benchmark/capi_bench.py build-against ../latticedb-0.16.0 --out /tmp/cb-0160
python3 tests/benchmark/capi_bench.py --bin /tmp/cb-0160 --suite core --json old.json
zig build capi-benchmark -- --suite core --json new.json
python3 tests/benchmark/capi_bench.py compare old.json new.json
Competitive Analysis
This page keeps two kinds of figure apart.
- Measured here. LatticeDB and SQLite, on the same machine, over the same generated data, each through its own public C API with comparable durability settings, by the same program. These are the only comparative numbers this project stands behind.
- Cited from others. Figures other projects and authors published for their own systems, on their own hardware and data. They were never measured here and are not comparable to each other or to LatticeDB; they are listed for orientation, with their sources, in a separate section and never in one table with ours.
Measured here: LatticeDB and SQLite
LatticeDB 0.17.0 and SQLite 3.51.0 (the system library of macOS 26.5), Apple M5,
2026-11-13, zig build capi-benchmark -- --suite core --suite sqlite. Both keep a
write-ahead log and fsync it on every commit (LatticeDB's default; SQLite with
journal_mode=WAL, synchronous=FULL), neither asks the drive to flush its cache
(fullfsync off on both), and both have a 100 MB page cache. SQLite runs prepared
statements; reads run inside BEGIN/COMMIT, as LatticeDB's run inside a read
transaction. Medians of five runs.
The data is the same on both sides: Person rows or nodes with an indexed integer
uid and a short name, and 5 KNOWS edges out of each to random others (a
knows(src, dst) table indexed on src for SQLite).
| Workload | LatticeDB | SQLite |
|---|---|---|
| One insert, one commit: p50 | 44 us | 42 us |
One insert, one commit, normal / synchronous=NORMAL: p50 | 6.4 us | 9.8 us |
| Inserts in transactions of 1,000 | 332,000/s | 1,840,000/s |
Lookup by indexed uid, 100K: p50 | 2.3 us (Cypher) | 3.0 us |
| 1 hop, 10K nodes: p50 | 2.5 us | 2.5 us |
| 2 hops, 10K nodes: p50 | 4.4 us | 5.4 us |
| 3 hops, 10K nodes: p50 | 14 us | 14 us |
| Paths of 1 to 5 hops, 10K nodes (3,904 paths): p50 | 472 us | 1,038 us |
| 1 hop, 100K nodes: p50 | 4.8 us | 3.6 us |
| 2 hops, 100K nodes: p50 | 8.8 us | 8.9 us |
| 2 hops, distinct end nodes, 100K: p50 | 6.7 us | 18 us |
| 3 hops, 100K nodes: p50 | 21 us | 29 us |
| Paths of 1 to 5 hops, 100K nodes (3,905 paths): p50 | 600 us | 1,361 us |
The hop queries are MATCH (a:Person {uid: $uid})-[:KNOWS]->()-[:KNOWS]->(c) RETURN count(c) and the like against joins of knows on itself; the 1-to-5 row is
-[:KNOWS*1..5]-> against a recursive CTE with UNION ALL. Both count the same
paths (SQLite's walk may reuse an edge, which Cypher's may not; that differs by one
path in 3,905). The single-commit p50s are within each other's run-to-run spread
(SQLite's runs ranged 39–50 us, LatticeDB's 44–45 us); 20,000 commits a run.
Read this plainly: for one to three hops from an indexed starting point, an indexed SQLite join is as fast as LatticeDB's Cypher. LatticeDB is about twice as fast enumerating longer paths, and SQLite inserts rows several times faster than LatticeDB creates nodes (a LatticeDB node writes a node record, a label index entry, two property records and changefeed events, where SQLite writes a row and an index entry). See LatticeDB vs SQLite for when each is the better choice.
Earlier editions of this page compared SQLite with LatticeDB's in-process Zig traversal over an adjacency cache, with LatticeDB's log off and SQLite doing more work per query (deduplication, a type filter). Queries, the C API and the bindings never use that cache, so those rows (including the depth-limited "2,819x") are withdrawn.
Cited from others
Collected for this documentation between December 2025 and August 2026 and not re-checked since; each figure is the source's own, for its own system, hardware, data and settings. None was measured here. LatticeDB's own figures are on Benchmarks.
Point lookups
| System | Published figure | Source |
|---|---|---|
| RocksDB (in-memory workload) | 0.14 us | RocksDB wiki |
| SQLite (in-memory) | ~0.2 us | Turso blog |
| SQLite (WAL, on disk) | 3 us (p90) | marending.dev |
| Neo4j (server) | 28 ms (p99) | Memgraph comparison |
Vector search, 10 nearest neighbours at about 1M vectors
| System | Published figure | Type | Source |
|---|---|---|---|
| FAISS HNSW (single thread) | 0.5–3 ms | Library | FAISS wiki |
| Weaviate | 1.4 ms mean, 3.1 ms p99 | Server | Weaviate benchmarks |
| Qdrant | ~1–2 ms | Server | Qdrant benchmarks |
| Milvus + SQ8 | 2.2 ms p99 | Server | VectorDBBench |
| pgvector HNSW | ~5 ms at 99% recall | Extension | Jonathan Katz |
| LanceDB | 3–5 ms | Embedded | LanceDB blog |
| Chroma | 4–5 ms mean | Embedded | Chroma docs |
| Pinecone P2 | ~15 ms including network | Cloud | Pinecone blog |
| sqlite-vec (brute force) | 17 ms | Extension | Alex Garcia |
These were measured mostly on public datasets (SIFT, GloVe and the like) at recalls the sources chose; LatticeDB's vector figures are on synthetic clustered vectors, so even a figure at the same scale is not a comparison.
Graph traversal
| System | Published figure | Source |
|---|---|---|
| Kùzu (archived October 2025) | 19 ms, 2-hop, 100K nodes | The Data Quarry |
| Neo4j | 10 ms, 1M nodes | Neo4j blog |
Full-text search
| System | Published figure | Source |
|---|---|---|
| SQLite FTS5 | under 6 ms | SQLite Cloud |
Rows that earlier editions gave without a source (Elasticsearch "1–10 ms", Tantivy "10–100 us") are removed.
Building from Source
LatticeDB is written in Zig with no external dependencies beyond the C library it
links. (The SQLite comparison benchmarks also need the system sqlite3 headers.)
Prerequisites
- Zig 0.16.0 (the version used by CI and release workflows)
Clone and Build
git clone https://github.com/jeffhajewski/latticedb.git
cd latticedb
zig build # build everything
Build Targets
zig build # Build and install everything: static and shared library, CLI, header, lattice.pc
zig build lib # Compile the static library only (installs nothing to zig-out)
zig build cli # Build and install the CLI only
zig build shared # Build and install the shared library, header and lattice.pc for bindings
Optimized Builds
zig build -Doptimize=ReleaseSafe # Release build with safety checks
zig build -Doptimize=ReleaseFast # Optimized release build
Building Language Bindings
Python
# Build the shared library first
zig build shared
# The Python bindings use ctypes to load the shared library
cd bindings/python
pip install -e .
TypeScript
# Build the shared library first
zig build shared
# Build the TypeScript bindings
cd bindings/typescript
npm install
npm run build
Go
zig build shared
cd bindings/go
go test -tags repolocal ./... # repolocal links against include/ and zig-out/lib
Java
zig build shared
cd bindings/java
mvn test # JDK 21+ and Maven; compiles the JNI bridge
Project Structure
src/
├── core/ # Core types and utilities
├── storage/ # B+Tree, page management, WAL
├── vector/ # HNSW index, vector operations
├── fts/ # Full-text search, tokenizer
├── graph/ # Node, edge, label and property-index storage
├── query/ # Cypher parser, planner, executor
├── stream/ # Durable streams and the graph changefeed
├── transaction/ # Transaction manager, WAL payloads
├── concurrency/ # Locking, latches
├── api/ # C API bindings
└── cli/ # CLI tool
include/
└── lattice.h # C API header
bindings/
├── python/ # Python bindings
├── typescript/ # TypeScript/Node.js bindings
├── go/ # Go bindings
└── java/ # Java bindings (JNI)
conformance/
└── go/ # Engine conformance suite, run against the C API
Running Tests
LatticeDB's test suite covers unit tests (including multi-threaded concurrency tests of the latches, locks and transactions, in tests/unit/concurrency_test.zig), integration tests, crash recovery tests, fuzzing, binding tests, an engine conformance suite, and benchmarks.
Test Commands
zig build test # Run unit tests
zig build integration-test # Run integration tests
zig build crash-test # Run crash recovery tests
zig build fuzz # Run fuzz tests once (add -- --fuzz to fuzz continuously)
zig build shared # Build shared library used by bindings
Benchmarks
zig build benchmark # Core operation benchmarks
zig build vector-benchmark -- --quick # Vector benchmarks (1K/10K/100K, ~7 min)
zig build vector-benchmark # Full vector benchmarks including 1M (~70 min)
zig build graph-benchmark -- --quick # Graph traversal benchmarks
zig build sqlite-benchmark # LatticeDB vs SQLite
zig build fts-benchmark # Repeated-term FTS indexing
zig build stress # Stress tests
zig build benchmark-build # Compile every benchmark without running (CI does this)
Test Structure
tests/
├── unit/ # Unit tests for individual modules
├── integration/ # End-to-end integration tests
├── fuzz/ # Fuzzing targets for parser and serialization
├── crash/ # Crash recovery and power-loss tests (see below)
├── container/ # Linux package/shared-library smoke tests
└── benchmark/ # Performance benchmarks
Testing Standards
- Fuzzing is mandatory for the parser and serialization code
- Crash recovery tests simulate a crash in-process. Some copy the database and its log while a handle is still open, which is what a killed process leaves; some reset the file to an earlier state (for example truncating it to its header page) so that reopening has to recover from the write-ahead log; some build the state a crash part way through a flush leaves. No test kills a real process.
- Power loss is tested by simulation, described below.
- CI enforces coverage only for the Python binding (
--cov-fail-under=85); the TypeScript binding runsnpm run test:coverage. There is no Zig coverage tooling.
Power-Loss Tests
A process kill leaves every write the process made, synced or not. A power cut does more: it loses what was not synced, can keep later writes while losing earlier ones, can tear a write at a sector boundary, and can lose the name of a file whose directory was not synced. The crash suite tests that with a simulated disk:
FaultVfs(src/storage/fault_vfs.zig) is an in-memory filesystem that records every create, delete, write, truncate, file sync and directory sync.DiskModelreplays a prefix of that record and cuts the power. Synced data and synced names survive. Each unsynced change survives in one of four styles: all of it, as a process kill leaves it; a prefix in order with the last write torn; any subset in any order; or any subset of 512-byte sectors, with truncations possibly lost and file lengths possibly grown with zeroes. A name created or removed since its directory was last synced comes back old or new at random.Database.openWithVfs(Zig API only) opens a database on anyVfs, treated as a disk, journal included, so the harness runs the same engine as a file on disk.tests/crash/ldur_power.zigruns a seeded random workload through the Zig API against a model of what the database should hold: labelled nodes, properties including values in overflow pages, edges and their deletion, node deletes, a property index, a full-text index, vectors, rolled-back transactions, explicit syncs and checkpoints, reopens, and optionally a log removed while the database is closed. It notes where each commit returned, then cuts the power before and after every sync and at random points, opens each result and checks it:- the contents are exactly the state after some whole number of transactions, no
fewer than had been acknowledged at the cut (in
normalsync mode, no fewer than had been acknowledged when the log was last synced), and at most one more; - node and edge counts agree with scans, every edge's ends exist, adjacency agrees with the edges, the label, property and full-text indexes agree exactly with the graph, and every vector is reachable by search;
- every fifth cut is followed by a second cut during that recovery, which must reach the same state.
- the contents are exactly the state after some whole number of transactions, no
fewer than had been acknowledged at the cut (in
zig build crash-test runs five configurations: the default sync mode over the
graph and a property index; overflow values with transactions over several log
frames; normal sync mode; vectors with a full-text index; and a log removed while
the database was closed. Together they take about a minute and a half of CPU in a
debug build. For a longer search, environment variables control the harness:
| Variable | Effect |
|---|---|
LDUR_SEEDS=<n> | Run each configuration at three times the size, over n more seeds |
LDUR_SEED_BASE=<n> | First of those seeds (default 100) |
LDUR_SEED=<n> | Rerun the configurations at one seed |
LDUR_ONLY_CUT=<n> | Run only one cut |
LDUR_VERBOSE=1 | Print each cut |
LDUR_KEEP_GOING=1 | Count failures instead of stopping at the first |
LDUR_SEEDS=4 zig build crash-test
The harness does not reach everything. lattice check, backup, restore and
replication use the filesystem directly rather than the Vfs, deserialize writes
a temporary file directly, and the workload drives the Zig API, not the C API,
Cypher or streams.
TypeScript Binding Tests
cd bindings/typescript
npm test
Python Binding Tests
cd bindings/python
uv run --extra dev pytest tests -q
Go, Java and Conformance Tests
cd bindings/go && go test -tags repolocal ./...
cd bindings/java && mvn test
cd conformance/go && go test ./... # needs PKG_CONFIG_PATH pointing at an installed lattice.pc
Release Checks
Before tagging a release, validate version consistency and the binding smoke paths:
python3 scripts/bump_version.py --check <version> --strict-lockfile
zig build test
zig build integration-test
zig build shared
cd bindings/typescript && npm test -- --runInBand
Releasing
Use scripts/prepare_release.sh as the supported release entry point. It wraps
the repository-wide version bumper, optional lockfile refresh, consistency
checks, and tests. (dist/bump-version.sh is an older script that also bumps,
commits, tags and pushes; do not use it.)
Patch Release Flow
scripts/prepare_release.sh 0.17.0
Then, before committing:
- Promote
docs/release_notes_next.mdtodocs/release_notes_0.17.0.md, covering every change since the last tag (git log v0.16.0..origin/main), and resetrelease_notes_next.mdto the empty template. - Rewrite the "What's new" caption and cards in
website/index.htmlby hand. The bumper only moves the heading and the release-notes link.
Then commit everything the bumper changed, tag the release commit, and push:
git diff
git status --short --branch
git add build.zig build.zig.zon src/main.zig src/api/c_api.zig include/lattice.h \
bindings/ examples/ conformance/ book/src/api/c.md website/index.html docs/
git commit -m "Release v0.17.0"
git tag -a v0.17.0 -m "LatticeDB 0.17.0"
git push origin main
git push origin v0.17.0
Pushing the tag runs .github/workflows/release.yml, which builds the release
and publishes to PyPI and npm. Those versions cannot be reused, so be sure
before you push it.
prepare_release.sh also accepts --tag and --push-tag, but they run before
anything is committed, so they tag the commit before the version bump. Do not
use them; tag by hand after committing as above.
Version Sources
scripts/bump_version.py is the canonical version updater/checker. It updates
and validates:
- native source and C header versions:
build.zig,src/main.zig,src/api/c_api.zig,include/lattice.h - the Zig package manifest version:
build.zig.zon - Python metadata:
bindings/python/pyproject.toml,bindings/python/src/latticedb/__init__.py,bindings/python/uv.lock - TypeScript metadata and fallback version:
bindings/typescript/package.json,bindings/typescript/package-lock.json,bindings/typescript/src/index.ts - example and conformance dependency pins for Go and TypeScript
- the C API version example in
book/src/api/c.md - the Java binding version:
bindings/java/pom.xml - the version shown on the website:
website/index.html
Before pushing a release tag, run:
python3 scripts/bump_version.py --check 0.17.0 --strict-lockfile
The GitHub release workflow runs the same strict check before building or publishing artifacts.
Validation
For a normal release, keep the default scripts/prepare_release.sh test run
enabled. It runs zig build test and the Python and TypeScript binding tests; the
TypeScript tests need the shared library, which the script does not build, so run
zig build shared first. For a fuller manual validation, use:
zig build test
zig build integration-test
zig build crash-test
zig build shared
cd bindings/python && uv run --extra dev pytest tests -q
cd bindings/typescript && npm test -- --runInBand
Storage changes that affect durability, page layout, large values, recovery, or bindings should also run the relevant crash, container, or regression repro tests before tagging.
Contributing
Contributions to LatticeDB are welcome.
Getting Started
- Fork the repository on GitHub
- Clone your fork and create a branch
- Make your changes
- Run the test suite:
zig build test - Submit a pull request
Development Setup
git clone https://github.com/YOUR_USERNAME/latticedb.git
cd latticedb
zig build test # Verify everything builds and passes
Code Style
- Follow existing Zig conventions in the codebase
- All allocation goes through explicit allocator parameters
- Fail fast: detect and report corruption, don't hide it
- Keep the C API as the contract: all bindings wrap
include/lattice.h(Java through a JNI bridge). If you change the C API, update every binding — Python, TypeScript, Go and Java — in the same branch.
Testing
All changes should include appropriate tests:
- Unit tests for new functions or modules
- Integration tests for end-to-end behavior changes
- Fuzz tests for parser or serialization changes
- Crash tests for durability-related changes
Run the full test suite before submitting:
zig build test
zig build integration-test
CONTRIBUTING.md in the repository has the full development setup.
Pull Requests
- Keep PRs focused on a single change
- Include a clear description of what changed and why
- Ensure all tests pass
- Add tests for new functionality
Reporting Issues
File issues on GitHub with:
- A clear description of the problem
- Steps to reproduce
- Expected vs actual behavior
- LatticeDB version and platform