Create bm25 indexes, tune segment sizes and BM25 parameters (k1, b), monitor parallel builds, and inspect pages.
This is the multi-page printable view of this section. .
Usage & Hybrid Search
- 1: Indexing & Maintenance
- 2: Querying & Scoring
- 3: Filtered Search & Prefiltering
- 4: Hybrid Search (BM25 + VectorChord)
- 5: BM25 & Block-WeakAnd Internals
Learn how to build, tune, and query vchord_bm25 indexes in production:
Run Top-K Block-WeakAnd queries, understand negative BM25 scores, and tune bm25_limit.
Combine WHERE predicates with BM25 ranking using post-filtering, pre-filtering, and partial indexes.
Fuse sparse BM25 lexical search with VectorChord dense vector search via Reciprocal Rank Fusion (RRF) and ColBERT.
Deep dive into the Okapi BM25 formula, 1-byte fieldnorm quantization, delta-bitpacking, and Block-Max WAND.
1 - Indexing & Maintenance
vchord_bm25 provides the bm25 index access method and the explicit bm25_ops operator class. The SQL handler is bm25_amhandler in 0.4.0 and _bm25_amhandler in 0.3.x.
Creating a bm25 Index
Stable Releases (v0.1 – v0.3, bm25vector)
Next-Gen main Branch (tsvector)
In the main branch, bm25_ops operates on tsvector and supports index-level storage parameters (options, limit, and prefilter):
Storage Parameter (WITH (...)) |
Type | Default | Range | Description |
|---|---|---|---|---|
options (k1) |
float (in TOML) |
1.2 |
1.2 – 2.0 |
Term frequency saturation parameter . Higher values increase the weight of repeated occurrences of a term within a document. |
options (b) |
float (in TOML) |
0.75 |
0.0 – 1.0 |
Document length normalization parameter . 0.0 disables length normalization; 1.0 fully normalizes by document length relative to . |
limit |
int |
0 |
0 – 65535 |
Default Top-K search limit stored on the index (used when session GUC bm25.limit has its default source, after RESET). |
prefilter |
bool |
false |
true / false |
Default prefilter behavior stored on the index (can be overridden per session via bm25.prefilter). |
You can dynamically update limit or prefilter on an existing index with ALTER INDEX:
Automatic Tokenization Triggers (v0.1 – v0.3)
When using pg_tokenizer, you can keep your bm25vector column automatically synchronized on INSERT and UPDATE:
Using a Custom Model Trigger (One-Step Helper)
create_custom_model_tokenizer_and_trigger creates a custom model, a tokenizer, backfills existing rows, and attaches an automatic BEFORE INSERT OR UPDATE trigger:
Using a Standard PL/pgSQL Trigger with Pretrained Models
If you use a pretrained model (such as llmlingua2 or bert_base_uncased), create a standard trigger function:
Segment Architecture: Growing vs. Sealed Segments (v0.1 – v0.3)
Internally, vchord_bm25 organizes index tuples into two segment states:
- Growing Segment: Newly inserted tuples (
INSERT/UPDATE) are appended to the growing segment for fast write throughput without re-compressing entire posting lists. - Sealed Segment: When the growing segment exceeds
bm25_catalog.segment_growing_max_page_sizepages (default4096pages, ~32 MB), it is sealed into an immutable, read-only segment with delta-bitpacked 128-document blocks, precomputed block-max upper bounds, and term document frequency statistics.
Parallel Index Build & Progress Monitoring
Index creation supports PostgreSQL parallel maintenance workers and reports live build progress via pg_stat_progress_create_index across three phases:
initializingscanning tablewriting index structures
Inspecting Index Pages (v0.3.0)
Version 0.3.0 provides bm25_page_inspect(index regclass, blkno int) to inspect the internal metadata and page headers of a bm25 index:
Index Constraints & Limitations
- Single-Column Only: A
bm25index can only be created on a singlebm25vector(ortsvector) column. Multicolumnbm25indexes are not supported. - No Unlogged Tables:
UNLOGGEDtables are not supported by thebm25access method (ambuildemptyraisesUnlogged indexes are not supported). - Forward Scan Direction Only:
bm25index scans only support forward (ASC) scan direction on<&>.
2 - Querying & Scoring
Basic Top-K Query Syntax
To run an index-accelerated Top-K BM25 search, use the <&> operator in the ORDER BY clause together with to_bm25query:
Why to_bm25query Requires the Index Name
Unlike vector distance operators (where the distance between two vectors depends only on the two vectors themselves), the BM25 score of a document depends on corpus-wide statistics stored inside the BM25 index:
- Total number of documents in the corpus ()
- Average document length across the corpus ()
- Document frequency of each query token ()
Passing the index ('documents_embedding_bm25'::regclass) into to_bm25query(...) allows the standalone scoring function (search_bm25query / _bm25_evaluate) to read corpus statistics from the index even when PostgreSQL evaluates <&> in the SELECT projection list or during a brute-force sequential scan.
Understanding Negative BM25 Scores
By design, <&> returns negative BM25 scores:
- PostgreSQL’s index access method API (
amcanorderbyop) only supportsORDER BY <operator> ASCfor index-ordered scans. - Because higher BM25 scores mean better relevance, returning $-\text{BM25}(D, Q)$ places the most relevant documents first when sorted in default ascending (
ASC) order. - Never use
ORDER BY embedding <&> to_bm25query(...) DESC—PostgreSQL cannot use the forwardbm25index scan forDESCordering and will either fall back to a full scan or raise a scan direction error.
Tuning bm25_limit vs SQL LIMIT
Because Block-WeakAnd maintains a bounded Top-K min-heap during the index scan to aggressively prune non-competitive posting blocks, the index scanner needs to know (the maximum number of candidates to collect) when the scan begins.
In v0.1.0 – v0.3.0: bm25_catalog.bm25_limit
The GUC bm25_catalog.bm25_limit (default 100, range -1 to 65535) controls the maximum number of Top-K documents returned by the bm25 index scan:
Special values of bm25_catalog.bm25_limit:
| Value | Behavior |
|---|---|
1 – 65535 |
Uses Block-WeakAnd to compute and return up to bm25_limit top-scoring documents (default 100). |
0 |
Immediately returns 0 rows. |
-1 |
Disables Block-WeakAnd Top-K pruning and performs a full brute-force scan over all matching postings in the index. |
In main: bm25.limit and Index limit Reloption
In the main branch, the effective limit is determined in priority order:
- An explicitly set session GUC
bm25.limit, including zero. - Otherwise, the index storage parameter
WITH (limit = ...).
Both defaults are zero; set a positive limit before searching. Explicit zero errors and does not fall back. RESET "bm25.limit" restores the index default.
Settings from postgresql.conf, ALTER DATABASE, ALTER ROLE, or client startup options also override index reloptions. RESET restores that configured default; it falls back to the index only when the GUC source returns to the built-in default.
Always ensure bm25_catalog.bm25_limit (or bm25.limit) is greater than or equal to the LIMIT in your SQL query. If your SQL query specifies LIMIT 200 while bm25_limit is 100, the index scan will stop after yielding 100 rows.
Verifying the Query Plan with EXPLAIN
Use EXPLAIN (ANALYZE, BUFFERS) to confirm that PostgreSQL is using Index Scan using ... on documents:
To force a sequential scan + exact brute-force evaluation (useful for verifying recall or debugging), disable the index scan temporarily:
3 - Filtered Search & Prefiltering
Real-world applications frequently combine full-text BM25 ranking with structured relational filters (such as category_id = 5, tenant_id = 'acme', or date ranges). vchord_bm25 supports three strategies for filtered BM25 search.
1. Post-Filtering vs. Pre-Filtering
When you execute a query with a WHERE clause and ORDER BY embedding <&> to_bm25query(...) LIMIT K:
There are two ways vchord_bm25 can evaluate the WHERE predicate:
Post-Filtering (enable_prefilter = false)
- The
bm25index runs Block-WeakAnd over the entire corpus and returns the global Top-bm25_limitcandidates (e.g., Top 100). - PostgreSQL fetches those 100 heap tuples and applies
WHERE category = 'database'. - Caveat: If only 3 of the global Top-100 documents have
category = 'database', the query returns only 3 rows even if hundreds of other'database'documents exist with slightly lower BM25 scores!
Pre-Filtering (enable_prefilter = true)
When pre-filtering is enabled, vchord_bm25 checks heap visibility and evaluates filter acceptability before pushing candidate documents into the Block-WeakAnd Top-K heap:
- Non-matching documents never enter the Top-K heap and never raise the Block-WeakAnd pruning threshold .
- The index scan continues until it finds documents that both match the
WHEREfilter and have the highest BM25 scores among all matching rows.
Enabling Pre-Filtering
In v0.2.2 – v0.3.0:
In main branch:
2. Partial BM25 Indexes for High-Selectivity Partition Keys
If you frequently filter by a small set of known partition keys (for example, status = 'published' or specific tenant_id values), you can create partial bm25 indexes:
When querying a partial index, reference the partial index’s name in to_bm25query and include the matching WHERE condition:
Choosing the Right Filtering Strategy
| Filter Selectivity | Recommended Strategy | Why |
|---|---|---|
| High selectivity (50%–100% rows match) | Post-filtering (enable_prefilter = false) with slightly higher bm25_limit |
Avoids heap fetches during the inner WAND loop; global Top-100 easily contains 10+ matching rows. |
| Medium selectivity (5%–50% rows match) | Pre-filtering (enable_prefilter = true / bm25.prefilter = true) |
Guarantees exact Top-K recall over filtered rows without scanning irrelevant postings. |
| Fixed tenant / status subset | Partial bm25 index (CREATE INDEX ... WHERE ...) or table partitioning |
Smaller index size, dedicated corpus IDF statistics, and zero wasted checks on other partitions. |
4 - Hybrid Search (BM25 + VectorChord)
Modern retrieval pipelines combine dense vector search (vchord, which captures semantic similarity) with sparse lexical BM25 search (vchord_bm25, which captures exact keyword, identifier, and rare-term matches). Because both extensions run natively inside PostgreSQL, you can execute end-to-end hybrid search in a single SQL query with zero external orchestration.
Schema Setup for Hybrid Search
Method 1: Reciprocal Rank Fusion (RRF) in Pure SQL
Reciprocal Rank Fusion (RRF) combines rankings from multiple retrieval systems without requiring score calibration between L2/cosine distance and BM25 scores:
where is a smoothing constant (typically ).
Method 2: Hybrid Retrieval + ColBERT Late-Interaction Reranking
For even higher accuracy, you can retrieve candidate documents using vchordrq (dense) + vchord_bm25 (lexical) and rerank the union of candidates in PostgreSQL using VectorChord’s @# (max_sim) multivector ColBERT operator:
See our engineering deep dives Supercharge Vector Search with ColBERT Rerank in PostgreSQL and Hybrid Search with Postgres Native BM25 and VectorChord for full BEIR benchmark comparisons of Dense + BM25 + ColBERT reranking inside PostgreSQL.
5 - BM25 & Block-WeakAnd Internals
This page details the exact scoring equations and data structures implemented in vchord_bm25 (crates/bm25/src/bm25.rs and src/algorithm/block_wand.rs).
1. Okapi BM25 Scoring Formula
Given a document and a query with query term frequencies and document term frequencies , vchord_bm25 computes:
Inverse Document Frequency ()
where:
- is the total number of indexed documents in the table.
- is the number of documents containing token (document frequency).
Saturated Term Frequency ()
where:
- is the term frequency of token in document .
- is the quantized document length (total token count in ) decoded from its 1-byte
fieldnormID. - is the average document length across all indexed documents.
- (default
1.2) controls term frequency saturation. - (default
0.75) controls document length normalization.
2. 1-Byte Fieldnorm Quantization (FIELDNORM_TO_LENGTH)
Storing a 32-bit float or integer length for every document and computing floating-point division for every scored posting would consume excessive memory bandwidth and CPU cycles. Instead, vchord_bm25 quantizes document length into a single byte (u8, 0..=255) using the 256-entry FIELDNORM_TO_LENGTH lookup table:
- Exact for short documents (
0–40tokens): Values0..=40map 1:1 to exact token counts. - Logarithmically stepped for longer documents (
41–255): Steps widen progressively (e.g.,42, 44, 46, ...up to2,013,265,944tokens). - 256-Entry Precomputed Score Cache: Because
fieldnormhas only 256 possible values,vchord_bm25precomputes the denominator term for all 256 possible document lengths once per query term:
Scoring a candidate posting during scan execution reduces to a single table lookup and one division:
3. Posting List Compression & Block-WeakAnd (Block-Max WAND)
Fixed 128-Document Blocks with Delta-Bitpacking
For each term in a sealed segment, the inverted list of (doc_id, term_frequency) pairs is partitioned into fixed blocks of 128 documents and compressed with Delta-Bitpacking:
- Document IDs within a block are sorted in ascending order and stored as deltas (), bitpacked using the minimum bit width required by the largest delta in the block.
- Each block header stores the last document ID in the block (for fast shallow seeking) and the Block-Max TF / Fieldnorm pair $(\text{tf}{\max}, \text{fn}{\min})$ that achieves the highest possible BM25 contribution inside that 128-document block.
Block-WeakAnd Top-K Pruning Loop
During an ORDER BY vec <&> to_bm25query(...) LIMIT K scan:
flowchart TD
A["Sort query term cursors by current doc_id"] --> B["Accumulate upper-bound max_score across cursors\\nuntil sum > current Top-K threshold θ (Pivot Document)"]
B --> C{"Sum of Block-Max scores\\nat Pivot > θ ?"}
C -- "No (Prune Block!)" --> D["Skip entire 128-doc block\\nwithout decoding postings"]
C -- "Yes" --> E{"All leading cursors\\naligned at Pivot doc_id?"}
E -- "No" --> F["Advance leading cursor to Pivot doc_id"]
E -- "Yes" --> G["Decode block & evaluate exact BM25 score\\nUpdate Top-K min-heap and raise θ"]
D --> A
F --> A
G --> A- Pivot Selection: Query term cursors are ordered by their current
doc_id. Starting from the first cursor,vchord_bm25sums each term’s global upper-boundmax_scoreuntil the cumulative sum exceeds the current -th best score threshold in the Top-K min-heap. The cursor where the sum crosses defines the pivot document. - Block-Max Refinement: Without decompressing any posting block,
vchord_bm25shallow-seeks each cursor up to the pivot’s 128-document block and sums the tighter per-block upper bounds (block_max_score). - Fast Block Skipping: If the sum of
block_max_scorevalues is , no document in the current block intersection can possibly enter the Top-K results—the scanner immediately jumps past the block without decoding document IDs or frequencies. - Exact Evaluation: Only when the block upper bound exceeds and cursors align on
pivot_docdoesvchord_bm25decode the block, verify visibility/deletion bitmap (and optional prefilter), compute the exact BM25 score, and update the Top-K heap.