Sparse vectors
(term id, weight) pairs beside the dense vector, with an exact sparse query and an optional inverted index.
Writing sparse vectors
A document can carry a sparse vector beside its dense one: a list of (term id, weight) pairs, such as BM25 or SPLADE output. It is optional per document, and nothing is declared per namespace. Term ids must not repeat and weights must be finite; at most 65,535 terms per document.
# Term ids come from your own vocabulary; here 1 = "rust", 2 = "python", 3 = "vector".
ns.upsert(
[
{"id": "d1", "vector": [1, 0], "sparse": [(1, 0.9), (3, 0.4)]},
{"id": "d2", "vector": [0, 1], "sparse": [(2, 1.2)]},
{"id": "d3", "vector": [1, 1], "sparse": [(2, 0.3), (3, 1.1)]},
{"id": "d4", "vector": [0, 0]}, # sparse is optional per document
]
) let doc = |id: &str, terms: Vec<(u32, f32)>| Document {
id: id.into(),
vector: vec![0.0],
attrs: None,
sparse: Some(terms),
};
ns.upsert(vec![doc("cats", vec![(1, 2.0), (2, 1.0)]), doc("dogs", vec![(3, 2.0)])]).await?;Sparse queries
query_sparse is exact and standalone: the score is the dot product, and the hit’s distance is its negation, so best first still means lowest. Ties are broken by id. It takes a filter like a dense query, and shadowing across segments and the tail works the same way: the newest copy of a document wins.
hits = ns.query_sparse([(3, 1.0), (2, 0.5)], top_k=3)
for hit in hits:
# distance is the negated dot product, so best first still means lowest.
print(hit.id, round(-hit.distance, 3)) let hits = ns.query_sparse(&vec![(1, 1.0), (2, 1.0)], 5, &SparseQueryOptions::default()).await?;
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].id, "cats");
assert_eq!(hits[0].distance, -3.0);Inverted index
index_sparse builds an inverted index per segment (sparse-idx-<n>.bin), so a query reads only its own terms’ postings instead of every sparse vector. The answer is the same with or without it.
# Fold the log into a segment and give it an inverted index; answers stay the same.
ns.compact()
print(ns.index_sparse()) ns.compact(&CompactionOptions::default()).await?;
let report = ns.index_sparse(&IndexSparseOptions::default()).await?;
assert_eq!(report.indexed, 1);Format level
A batch with a sparse vector is written as WAL version 4 (5 with a key), which needs the namespace at WAL level 5. New namespaces start there; an older one needs upgrade_wal_format(5), which is a Rust call.
