Vector search in Delva: exact, filtered nearest neighbors next to your JSON
Most retrieval prototypes end up with two databases. One holds the chunks and their metadata, the other holds the embeddings, and glue code keeps them in step: two writes per chunk, two ways to fail halfway, and the metadata copied into the vector store's payload so it has something to filter on. For a service that runs on one machine and owns its data, that's a lot of moving parts for a nearest-neighbor lookup.
Delva 0.4.0, released last week, takes the other route. Vector search is now part of the embedded JSON store itself (experimental for now): the embedding stays in the document, the store keeps a float32 copy in a vector index that shares the same log, snapshots and crash guarantees as everything else, and a search can be narrowed with the same document filters as any other query.
This post looks at it from the vector-database side: what it does, the design choices behind it (above all, exact search instead of an approximate index), what it costs, and where it stops.
The short version
A store gets a vector field when it's created: the path of the embedding, its dimensions, and the metric.
@OptIn(ExperimentalDelvaApi::class)
fun main() {
val options = CreationOptions(excludedKeys = setOf("embedding"))
.withVectorField(VectorField("$.embedding", dimensions = 768, metric = VectorMetric.COSINE, required = true))
JsonStore.create(Path.of("data/chunks"), options).use { store ->
val db = store.blocking()
// {"source":"doc-17","chunk":3,"text":"…","embedding":[0.0123,-0.441,…]}
db.insert(chunkJson)
val query = VectorQuery(embed("how do I rotate the signing keys?"), k = 5)
.withDocumentFilter(DocumentFilter.compile("@.source == 'doc-17'"))
db.search(query).use { result ->
for (hit in result) println("%.4f %s".format(hit.distance, hit.readJsonAsString()))
}
}
}
embed is your model. Delva doesn't compute embeddings, and that's deliberate: the model is the part of a retrieval system you change most, and the store shouldn't care which one you picked. It only insists that every vector in a store comes from the same one.
There's no separate collection, no payload schema and no sync job. The chunk is a JSON document, its metadata is searchable the way every Delva key is, and its vector is one more thing the insert indexes, atomically with the rest.
Exact search, on purpose
The vector-database world runs on approximate nearest-neighbor indexes: HNSW graphs, IVF partitions, product quantization. They exist for a good reason. At tens of millions of vectors, comparing the query with every vector is out of the question, so you trade a little recall for orders of magnitude in latency.
That trade has a cost people tend to discover late. Recall becomes a knob (ef_search, nprobe) that you tune, measure against a ground truth you have to compute separately, and re-tune as the data drifts. Results can change when the index is rebuilt. Deletes leave holes in a graph that need repair. And none of it is visible in the API: a query returns some neighbors, and whether they're the right ones is a statistical statement.
Delva's vector search is exact. Every candidate's vector is compared with the query, so the result is the true k nearest, recall 1.0 by definition. Ties are broken by document id, so the same store and the same query always give the same answer, in the same order. There's no build step, no index-time parameter to get wrong, and nothing to rebalance.
The reason that's viable is scale. An embedded store holds what one application owns: thousands to a few hundred thousand chunks, not a web crawl. At that size a linear scan over contiguous float32 is bound by memory bandwidth, and memory bandwidth is plentiful. A top 10 on one Windows machine, with the vector index in the OS page cache:
| Vectors | Dimensions | Vector index | All | 1% filter | 10% filter | All, mmapReads |
|---|---|---|---|---|---|---|
| 10,000 | 384 | 15 MiB | 8.8 ms | 1.7 ms | 6.1 ms | 3.6 ms |
| 100,000 | 384 | 148 MiB | 75 ms | 5.4 ms | 49 ms | 41 ms |
| 10,000 | 768 | 30 MiB | 14 ms | 0.7 ms | 4.3 ms | 7.5 ms |
| 100,000 | 768 | 296 MiB | 156 ms | 5.8 ms | 56 ms | 78 ms |
| 10,000 | 1,536 | 59 MiB | 32 ms | 1.0 ms | 4.8 ms | 15 ms |
| 100,000 | 1,536 | 590 MiB | 280 ms | 5.9 ms | 50 ms | 149 ms |
Two columns in that table matter more than the rest, and they're the filtered ones.
Filtering is the hard part, and here it's the easy part
Ask anyone who has run vector search in production what hurts, and filtered search comes up quickly: "the five nearest chunks, but only from this tenant / this document / this date range".
Approximate indexes handle it badly in one of two ways. Post-filtering asks the index for the nearest k, then drops the ones that don't match. With a selective filter, most of them don't, and you get two hits when you asked for ten, or you over-fetch by a factor you have to guess. Pre-filtering inside a graph index restricts the traversal to matching nodes, but a graph built for the whole dataset falls apart when most of its nodes are off limits: the remaining ones aren't connected well enough to navigate, and recall drops off a cliff exactly when the filter is most selective. Production systems paper over this with heuristics that fall back to brute force below some selectivity threshold.
Delva gets to avoid all of that, because it already has an inverted index over every key–value pair. A vector search with a document filter runs as a merge of two streams, both in document-id order:
- the candidates, produced by the filter's index terms (
@.source == 'doc-17'is a lookup, not a test run against every document), and - the vector index, sorted by document id.
Each stream seeks to the other's current id, leapfrogging past everything in between, so vectors of documents that aren't candidates are skipped rather than read. The result is the true k nearest among the documents the filter accepts, and never fewer than k when that many exist. No over-fetching, no recall cliff.
Look at the table again: at 100,000 vectors of 1,536 dimensions, an unfiltered search takes 280 ms and a 1% filter takes 5.9 ms. In a graph index, a selective filter is the worst case. Here it's the best one.
Parts of a filter that the index can't answer, say a comparison between two fields, are tested by reading the document. Delva does that lazily: the residual filter runs only for a candidate whose distance would currently enter the top-k heap. Since the filter depends only on the document, the answer is identical to testing every candidate, but documents too far away to matter are never read.
And as with every other Delva query, explain tells you how a search will run before you run it:
println(db.explain(query)) // VectorQueryPlan(2 vectors, 'source' == 'doc-18', reads documents)
A filter with no index terms at all would mean testing every document, and is rejected with NEEDS_SCAN unless you pass ScanPolicy.ALLOW_SCAN, the same rule JSONPath searches follow. An unfiltered vector search is never rejected: comparing every vector is what it means.
When the filter value comes from a user, bind it instead of concatenating it. A DocumentFilterTemplate such as @.source == ${source} takes the value as a literal, so no source name can change what the filter tests.
The numerics, done carefully
Distance code is the part of a vector store nobody reads, and the part where small sloppiness becomes "why is this result NaN" six months later. Delva's choices:
- Storage is float32. Each number in the JSON is converted from its decimal text to the nearest float32, round half to even. Nine significant digits reproduce any float32 exactly, and the document itself reads back byte for byte as it was inserted.
- Arithmetic is double. The product of two floats is exact in a double, and no sum of 4,096 of them overflows or underflows there. Each distance is rounded to float once, at the end. A distance is never NaN, and
-0is0. - Cosine costs the same as a dot product. The vector's sum of squares is computed once at insert and stored beside it, so every metric is a single pass over the vector. That removes the usual reason to normalize vectors yourself and switch to dot product for speed: use the metric your model was trained for. (For unit-length vectors, which many models produce, all three rank alike anyway.)
- The inner loop is unrolled by eight with independent accumulators, so the CPU keeps eight additions in flight instead of one dependency chain waiting on itself, and the query is converted to doubles once per search rather than once per vector. There's no SIMD yet: that waits for the JDK's Vector API to leave incubation, rather than shipping a library that depends on an incubator module.
The metrics are COSINE (1 − cos θ, from 0 to 2), DOT_PRODUCT (the dot product negated, so smaller is still nearer) and EUCLIDEAN (the true distance, not its square, so a maxDistance threshold means what it says).
Bad vectors never get in. A value at the vector path that isn't an array of exactly the field's dimensions, contains something that isn't a number, or holds a number too large for a float32 is rejected with INVALID_VECTOR, with the path and the offset of the offending element. So is an all-zero vector under cosine, since it has no direction. A serializer bug that writes 767 numbers fails loudly at insert, not quietly at query time.
A real index, not a sidecar
The vector index is built the way Delva's other indexes are: an in-memory memtable for recent inserts, immutable sorted segments on disk, merged newest-first at read time and compacted together with the rest. Its blocks are small, 8 KiB, so a selective filter reads little per vector, and a full scan reads ahead 64 KiB at a time so it still makes few I/O calls.
Because it's part of the same machinery, it inherits the guarantees everything else has:
- Atomic with the document. After a crash, a chunk is there with its vector, or absent with it. There's no window where the vector store has a chunk the document store doesn't.
- Snapshot reads. A search sees the store as of its start; a concurrent insert or delete doesn't tear it.
- Versioning.
replaceandupsertgive the new version its own vector, or none. - Readers beside the writer. A secondary process, which takes no lock and never writes, can run vector searches on a live store.
- Scrubbing.
verifychecks the vector index and reports damage asVECTOR_INDEX.
A search reads only the vector index; a hit's document is read when you read the hit, so pulling the five nearest chunks' text doesn't touch the other 99,995. Cancelling a search stops it within a few hundred vectors.
Keeping a store of embeddings small
Embeddings are bulky, and JSON makes them bulkier. Four habits matter, all measured on 10,000 chunks of 768 dimensions:
| Numbers | Vector key | JSON | Stored | Index | Inserts/s |
|---|---|---|---|---|---|
| float32, shortest | excluded | 9.5 KB | 4.0 KB | 58 B | 1,370 |
| float64, 17 digits | excluded | 16.2 KB | 8.0 KB | 59 B | 1,520 |
| float32, shortest | indexed | 9.5 KB | 4.0 KB | 22.8 KB | 750 |
Exclude the embedding's key from the inverted index. Delva indexes every value by default, and an indexed array of 768 numbers is 768 postings nobody will ever search for. The last row shows the price: 22.8 KB of index per chunk instead of 58 bytes, and half the insert rate.
Write the numbers short. Float.toString writes the shortest text that reads back as the same float32. A serializer that widens to double first writes up to 17 digits and nearly doubles the document for no gain in precision, since the store reads float32 either way.
One document per chunk. A document holds at most one vector, so store each chunk with a reference to its source. A filter then finds a source's chunks, and replace swaps one chunk without rewriting the others.
One model per store. Vectors from different models, or different versions of one, aren't comparable, and when their dimensions match nothing would stop a search from comparing them anyway. The vector field is fixed at creation, so a new model means a new store, which is the right discipline for a re-embed regardless.
On top of the document, the vector index costs about 4 bytes per dimension. The open store also keeps about 40 bytes of heap per 8 KiB block of vector index, which no option bounds: from 1,024 dimensions up each vector fills a block of its own, so a million vectors of 1,536 dimensions hold about 40 MB.
Where it stops
The limits, plainly:
- Scale. Exact search grows linearly with the vectors it compares. It suits stores of up to about 100,000 vectors where 0.1–0.3 seconds per unfiltered search is fine, and larger stores whose searches are filtered. Past that, it's too slow.
- One vector per document, up to 4,096 dimensions;
kup to 10,000, returned in one result without a cursor. - Experimental. The API is marked
@ExperimentalDelvaApi, and a store with a vector field uses format version 2, which earlier versions of Delva refuse. The whole library is pre-1.0.
The roadmap has the next steps in a deliberate order. First, scans over vectors quantized to 8-bit integers, a quarter of the bytes, with the shortlist rescored in float32. Only after that, an approximate index: vectors partitioned around centroids trained on the data as it arrives, stored in segments like the other indexes, and held to a recall threshold against exact search. That ordering is the point of starting exact: when the approximate index comes, it has an oracle to be measured against from day one.
From the shell
The delva command line on main, shipping with the next release, speaks vectors too:
delva init ./data/chunks --vector-field '$.embedding' --vector-dimensions 768 --vector-metric cosine
delva search vector 42 -n 5 # the chunks most like chunk 42
delva search vector query.json --where "@.source == 'doc-17'" --max-distance 0.3
Passing a document id uses that document's own vector, which makes "more like this" a one-liner for debugging retrieval quality.
Try it
Add app.oreshkov.delva:delva:0.4.0 to a Kotlin project on JDK 22+. The repo's delva-examples module has EmbeddingSearch, a complete chunk store with filtered search; it uses seeded random unit vectors, so it needs no model to run:
./gradlew :delva-examples:runEmbeddingSearch
The guide covers the feature with its sizing numbers, and SPEC §11 has the exact semantics, down to rounding. If you run it on a real embedding workload, I'd like to hear where it holds up and where it doesn't, especially the filter shapes your retrieval actually uses.
New to Delva? Start with the introduction: an embedded JSON database for Kotlin that indexes everything.