B-tree and Hash Secondary Indexes
CREATE INDEX ... USING btree (the default) and USING hash on plain columns become entries in the engine-wide SecondaryIndexRegistry. Despite the name, the wired structure is a hash map plus an ordered map held in memory, not an on-disk B-tree. The on-disk B+tree in src/index/btree_persistent/ and the in-memory BTreeIndex exist but nothing in SQL uses them. See Overview for how index choice works.
The wired secondary index
Data structure
Each SecondaryIndexEntry holds:
| Field | Purpose |
|---|---|
map |
HashMap<String, Vec<Vec<u8>>>: value bucket to row keys, for equality and IN
|
always |
Row keys whose value cannot be bucketed; always returned as candidates |
ordered |
BTreeMap from an order key to row keys, for ranges |
range_always |
Row keys whose value has no order key; always returned for ranges |
gin_terms, gin_always, fts_sources, fts_always
|
Used by GIN and full-text entries (see GIN) |
column |
Indexed column |
dirty |
Set when the entry must be rebuilt |
rebuilt_at |
When the entry was last rebuilt, compared with a transaction's snapshot |
(source: src/storage/mod.rs, SecondaryIndexEntry)
The index covers only the leading column of a multi-column index. Test secidx_coercions_and_multicolumn_leading covers this. (source: src/query/engine.rs, execute_create_index, secidx_coercions_and_multicolumn_leading) Indexes with a WHERE predicate (partial indexes) and expression indexes get no secidx entry and are not used for lookups, except that a partial or expression UNIQUE index is still enforced. (source: src/query/engine.rs, execute_create_index, backfill_unique_index)
Equality buckets
secondary_bucket turns a value into a bucket string. Values that compare equal in SQL must land in the same bucket; values that cannot be bucketed safely go to always. (source: src/query/engine.rs, secondary_bucket)
| Value | Bucket |
|---|---|
| Integers, booleans, integral decimals, strings that parse as integers |
n: prefix with the integer |
| Other decimals |
d: prefix |
| Floats, JSON, arrays, vectors |
always (no bucket) |
| UUID | U: |
| Date | D: |
| Timestamp | T: |
| Time | t: |
| Bytes that are not UTF-8 |
B: and hex |
| UTF-8 bytes | Same bucket as the equal string |
NULL |
Not indexed |
(source: src/query/engine.rs, secondary_bucket)
try_secondary_index_candidates handles col = const and col IN (...) in a top-level AND. It returns nothing (falling back to other paths) for citext columns, for OR, and for float literals. (source: src/query/engine.rs, try_secondary_index_candidates) Text comparison rules differ by dialect; test secidx_text_lookup_case_rules_per_dialect covers this. (source: src/query/engine.rs, secidx_text_lookup_case_rules_per_dialect)
Tests: secidx_equality_and_in_match_brute_force_exactly, secidx_column_projections_match_brute_force, secidx_and_conjunct_filters_exactly, secidx_non_accelerated_paths_unaffected. (source: src/query/engine.rs, those tests)
Range lookups
secondary_order_key produces a sortable byte key: 0x01 followed by the big-endian i64 with its sign bit flipped for integers, or 0x02 followed by the bytes for text. Any other value goes to range_always. (source: src/query/engine.rs, secondary_order_key, ORDKEY_INT, ORDKEY_TEXT)
try_secondary_range_candidates serves <, <=, >, >= and BETWEEN on the leading column. It counts the rows in range first. Up to 1024 candidates it always uses the index; above that it uses the index only if the count is under 1/40 of the table, because a code comment records a range of 32k candidates on 200k rows taking 53 ms through the index against 2.2 ms for a scan. (source: src/query/engine.rs, try_secondary_range_candidates, RANGE_INDEX_MIN_CANDIDATES)
Not verified: no test was found that runs a range-only predicate through the index and compares it to a full scan. secidx_and_conjunct_filters_exactly mixes a range with an equality conjunct.
Build and maintenance on write
| Event | Effect |
|---|---|
| First query after start, or a query on a dirty entry |
rebuild_secondary_entry_locked scans the whole table under the entry's mutex |
INSERT (autocommit) |
Incremental add |
UPDATE, DELETE, upsert, INSERT ... SELECT
|
Entry marked dirty |
| Transaction commit | Entries for touched tables marked dirty |
(source: src/query/engine.rs, rebuild_secondary_entry_locked, secondary registry insert and dirty-marking hooks) Tests: secidx_backfill_insert_delete_update, secidx_inside_transaction_and_after_commit, test_secondary_index_sees_updates_inside_and_after_transaction. (source: src/query/engine.rs, those tests)
A rebuild is O(rows) and holds the entry mutex, so the first query after a write-heavy burst pays for a full scan. (source: src/query/engine.rs, rebuild_secondary_entry_locked)
Not verified: no benchmark or status entry measures rebuild latency on large tables.
Concurrency and transactions
The registry is shared by all engines on one storage; each entry has its own mutex. (source: src/storage/mod.rs, SecondaryIndexRegistry) Inside a transaction, equality lookups use the index only if the entry was rebuilt before the transaction's snapshot, so the index does not show rows the snapshot should not see. Range, GIN and full-text paths are skipped inside a transaction. (source: src/query/engine.rs, try_secondary_index_candidates, try_secondary_range_candidates)
Unique indexes
UNIQUE indexes are stored separately under __catalog__:uqindex:{table} and enforced on write. try_unique_index_lookup and the composite-unique check serve equality on unique keys. (source: src/query/engine.rs, append_unique_index_def, try_unique_index_lookup) Tests: secidx_unique_index_keeps_enforcement_and_accelerates, upsert_on_conflict_via_unique_index. (source: src/query/engine.rs, those tests)
Unwired B-tree structures
BTreeIndex (in memory)
A RwLock<BTreeMap<Vec<u8>, Vec<RecordId>>> with a unique variant and a composite-key builder. (source: src/index/btree.rs, BTreeIndex) Tests: test_btree_basic, test_btree_delete, test_btree_scan, test_unique_btree, test_composite_key. (source: src/index/btree.rs, tests)
Not wired: only IndexManager::create_btree_index creates one, and nothing calls it. (source: src/index/mod.rs, IndexManager::create_btree_index)
Persistent B+tree
src/index/btree_persistent/ is a page-based B+tree:
| Item | Value |
|---|---|
| Page size | 8192 bytes (DEFAULT_PAGE_SIZE) |
| Maximum key size | 1024 bytes (MAX_KEY_SIZE) |
| Maximum inline value | 2048 bytes (MAX_INLINE_VALUE_SIZE) |
| File magic |
BTREEIND (BTREE_MAGIC) |
| Page checksum | CRC-32 per page (crc32fast) |
| Buffer pool | LRU, 1024 pages by default |
| Write-ahead log entries |
Insert, Delete, Update, SplitLeaf, SplitInternal and others, replayed by BTreeRecovery
|
(source: src/index/btree_persistent/page.rs, src/index/btree_persistent/file.rs, src/index/btree_persistent/buffer_pool.rs, src/index/btree_persistent/wal_entries.rs, src/index/btree_persistent/recovery.rs)
It stores one value per key (a 16-byte RecordId), and its Index::delete removes by key and ignores the record id, so it cannot hold duplicate keys for a non-unique index. (source: src/index/btree_persistent/mod.rs, Index impl)
Tests in tree.rs include test_insert_and_get, test_delete, test_scan, test_many_inserts, test_inserts_with_splits and test_persistence; file.rs, page.rs, wal_entries.rs, recovery.rs and buffer_pool.rs have their own unit tests. (source: src/index/btree_persistent/tree.rs, tests)
Not wired: only IndexManager::create_persistent_btree_index and the test-only PhysicalPlanner reach it. (source: src/index/mod.rs, create_persistent_btree_index; src/plan/physical_planner.rs, get_persistent_btree_index)
The module comment describes it in quality terms that this page does not repeat; no test runs it under SQL load.