Secondary indexes
How raftdb-index stores candidate keys, why a lookup returns a superset, how the table keeps indexes in step, and how the lsm engine stores them.
raftdb-index depends only on raftdb-doc (the Value type) and has no unsafe code. It is a candidate generator: it narrows a query to a list of record positions, and the executor decides the answer.
What is stored#
A set of (key u64, slot u32) pairs. slot is the position of a record in the collection (the value of the raftdb-store index); key summarises the field's value.
Kind::Ordered(numbers):IntandTsby value (v ^ 1<<63),F64by IEEE total order (negatives inverted, sign bit flipped). Equality and ranges are slices of a sorted array.-0.0and0.0get different keys; NaN is not indexed.Kind::Hash(any scalar): a 64-bit multiply-fold hash of a type tag plus the value's bytes. Equality only. Strings use this, because an 8-byte prefix key would put everyuser:0000...key in one bucket. Containers are not indexed.
A document that lacks the field has no key and is not in the index.
Candidates, not answers#
Different types can share a key (the integer 3 and the timestamp 3) and hashes can collide, so a lookup returns a superset. The caller runs the real filter on every candidate with strict no-coercion typing (raftdb-exec), which keeps the typing rules in one place. The index may over-report but never misses.
Layout: 12 bytes per entry#
- Run: two parallel sorted arrays
keys: Vec<u64>andslots: Vec<u32>, so a binary search touches only the keys. - Overlay: pairs added and tombstones removed since the run was built, in two
BTreeSets. Lookups merge the run slice, minus tombstones, with the overlay range. - Merge: when the overlay exceeds 1/16 of the run and 1,024 entries it is merged into a new run in one pass (a merge-join over sorted sets). Tuning this took 2 M entries from 64 ms to 21 ms to 17 ms.
Contract with the table: insert(key, slot) once per document value and remove(key, slot) before a changed value is inserted. Neither checks the run, so inserting a pair twice returns it twice and removing an absent pair leaves a harmless tombstone. When compaction renumbers the records the index is rebuilt (Index::build).
In the in-memory table#
create_index(field, ordered) on raftdb-db is logged as an INDEX record and built from the data. Entries are not persisted: every index is rebuilt from the data when the table opens, and checkpoints rewrite the definitions. candidates(&Plan) walks Plan::required_leaves, asks each usable index for positions and returns the smallest list. A comparison is usable when the index can represent every value that could match: an ordered index takes =, <, <=, >, >= and $in with numeric literals; a hash index takes = and $in with any scalar literal; anything else scans. A random test (9,000 writes, deletes and rewrites over 150 keys, so compaction happens) compares index-assisted answers with full scans; it found a real bug on its first run, a stale position after a compaction-triggered rebuild, now fixed.
Full-text indexes (D133)#
A third kind, outside raftdb-index: create_text_index(field, options) on raftdb-db builds a raftdb-text index over the string in a top-level field, logged as a FULLTEXT record and, like the others, rebuilt from the data at open and after a compaction. It answers the filter operator $text (match, phrase, prefix, contains) exactly, not as candidates, so matching_slots(&Plan) treats an indexed $text condition as satisfied and runs only the rest of the filter on the hits. Records written since the index last built a segment (at most 256) are kept in a small "dirty" set and checked by the scan, so a query sees every earlier write. drop_index / drop_text_index remove an index (a DROP_INDEX record).
Full-text indexes through the server (D137)#
The server creates, drops and lists them: the binary request TextIndex and HTTP POST | GET | DELETE .../indexes with "kind":"fulltext". The in-memory engine uses the raftdb-db index above; an lsm table keeps one raftdb-text index per shard in memory (rebuilt from the rows at open, definition stored with the table and in the replication log) and reads the candidate rows of a $text condition when they are at most about 3 % of the rows (else it scans); the whole filter runs on them, so the rows are those of a scan. Measured, 60,000 rows of 40 words: a rare word 41 -> 0.4 ms (memory) and 69 -> 0.4 ms (lsm). SQL Server's CREATE FULLTEXT INDEX and PostgreSQL's GIN index on to_tsvector('simple', col) make these indexes.
In lsm tables#
The entries live inside the engine, as keys of the form [2] field id, index key, primary key; they are built from the existing rows when the index is created, kept in step by every write and copied to replicas of either engine. The index is used only when it points to at most about 3 % of the rows (D48). The helpers index_key, plan_ranges and the INDEX log record are shared with raftdb-db.
Measured#
raftdb-bench index, 2 M pairs, 10 per value, one core:
| Metric | Result | Target |
|---|---|---|
| Size | 12.00 bytes per entry | at most 13 |
| Equality lookup (about 10 matches) | 2.23 M/s | at least 2 M/s |
| Range scan (a tenth of the index) | 372 M entries/s | at least 100 M/s |
| Update (remove plus insert, merges included) | 1.44 M/s | at least 1 M/s |
The lookup margin is thin, about 10 %.
Not supported yet#
Multi-field and nested-path indexes, array-element indexes, index-only counts, ORDER BY through an ordered index, choosing between indexes by estimated selectivity beyond "smallest candidate list", dropping an index through the server, full-text indexes in lsm tables, and persisting the run (or the full-text image) to avoid the rebuild at open.