Repository navigation
Conversation
An order-preserving lossy encoding of a non-negative integer into a single byte (after Lucene's SmallFloat): values below 80 are exact, larger ones keep their 4 most significant bits, inputs above 2^24 - 1 saturate to 255. It is used to store the per-row document length (token count) for BM25 scoring.
The per-class memoryUsageBytes bookkeeping of the text index build and analysis classes was unused and easy to leave stale when new members are added. Remove it from the posting list encoders, builders and the analyzer; the granule overrides now throw NOT_IMPLEMENTED.
Add the experimental `enable_scoring` text index argument (gated by the MergeTree setting `allow_experimental_text_index_scoring`). An index created with it is written in the new `v3_with_scoring` serialization version and additionally stores: - the exact per-row term frequencies of every token, embedded into the posting lists: one bitpacked `(tf - 1)` block after each row-id block (an all-ones block is elided to a single zero-width byte), raw and embedded postings append them as VarUInts after the row ids; - the per-row document lengths, quantized to one `SmallFloat` byte each, in a new segmented `.dl` substream; - the per-part collection statistics (number of documents, total sum of document lengths, `.dl` segment offsets) in the index header; - the per-segment and per-block block-max upper-bound inputs (min doc-length byte, max saturating `(tf - 1)`) for future WAND/MaxScore pruning. The merge of text indexes streams the term frequencies through the k-way postings merge and rebuilds the merged `.dl` stream and statistics. Scoring requires a posting list codec (`bitpacking`) and a tokenizer where a document length is meaningful (`ngrams`, `array` and `sparseGrams` are rejected). Also fixes calls of the removed method `encode` (now `serializeTo`) of `SegmentedPostingListCodec` in gtests.
The BM25 kernel (BM25Kernel.h) holds the collection statistics, the smoothed IDF, and a per-term weight with a 256-entry length-norm cache keyed by the SmallFloat doc-length byte, so the per-row contribution is a few flops without divisions by decoded lengths. PostingListScoringCursor extends PostingListCursor: it decodes the per-block term-frequency sub-payload next to the row-id deltas and exposes the per-block/per-segment block-max upper-bound inputs. DocLengthsCursor lazily reads the segmented .dl substream and serves the SmallFloat doc-length byte of a row. Two scorers walk the cursors over a window of rows: a per-token union walk (correct under arbitrary predicate composition) and a joint leapfrog intersection walk (used under the global All search mode).
The Float32 virtual column `_bm25_score` holds the BM25 relevance score of a row, computed by the direct read from a text index created with `enable_scoring = 1`. It requires a `hasToken`/`hasAnyTokens`/ `hasAllTokens` predicate on the column of exactly one scoring text index and the setting `allow_experimental_bm25_score_column`. The plan optimization that rewrites text-search predicates for the direct read attaches the column to the scoring index's read task after validating the query shape (predicates must be evaluated by the index, one scoring index only). Before the pipeline is built, a query-global BM25 state is prepared: one parallel pass over the parts' text index granules accumulates the collection statistics and per-token document frequencies into per-token weights (the scoring tokens are stamped onto the index condition when it is created in `buildIndexes`, so granules deserialized by any analysis pass already carry term frequencies). The text index reader then fills the column per mark from scoring cursors: the union scorer under arbitrary predicates, the leapfrog intersection scorer under the global All mode. Rows of parts without a scoring read task (e.g. reads via `SELECT *` with `asterisk_include_virtual_columns`) are zero-filled. Reads on parts with rows hidden by a lightweight DELETE or pending lightweight updates are rejected, because the stored statistics would be stale. The TopK dynamic filtering is disabled for such queries: the prewhere it inserts would break the plan shape the direct-read optimization expects (the skip-index TopK path is kept).
A merge takes a source part's text index as is only when the copy contains every substream the merged index writes. An older copy (e.g. one without the `.dl` doc lengths while the index definition now has `enable_scoring = 1`) cannot be merged from the index files, because the document lengths of its rows are unknown; such an index is rebuilt from the source rows instead.
Skip the automatic parallel replicas optimization for queries that read `_bm25_score`: replicas cannot see the query-global BM25 statistics of the whole part set. Explicitly enabled parallel replicas keep working, including the row-count estimation pass: the estimation deserializes granules before the plan optimization that attaches the score column runs, and reuses them safely because the scoring tokens are stamped onto the index condition at its creation.
|
Workflow [PR], commit [774f54f] Summary: ❌
AI ReviewSummaryThis PR adds experimental Findings❌ Blockers
💡 Nits
Final Verdict❌ Not ready to merge. The remaining issues are not cosmetic: they can silently return scores from the wrong corpus, preserve semantically stale text-index files across attach/merge/mutation paths, and leak row-policy-hidden data through |
Two unit tests in the text index tests failed the `arm_tidy` build: - `gtest_text_index_postings_deserialization.cpp`: the argument comment `/*has_term_frequencies=*/` did not match the parameter name `enabled_scoring` of `IPostingListCodec::decode` (`bugprone-argument-comment`). - `gtest_bitpacking_tf_elision.cpp`: use of `long long` instead of `Int64` (`google-runtime-int`), and a cast of an already computed `size_t` sum to a wider type (`bugprone-misplaced-widening-cast`). The operands are now cast individually. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117519&sha=08464c3cde3ad904cc5fb312668c7fb5539d9114&name_0=PR&name_1=Build%20%28arm_tidy%29 ClickHouse#117519 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RRrmiEdqant5PxEZXzmq5e
The `Check internal links and anchors` job failed because `textindexes.mdx` linked to `/reference/settings/merge-tree-settings/allow-experimental#allow_experimental_text_index_scoring`, and the anchor does not exist yet: the settings pages under `docs/reference/settings/` are autogenerated from the `DECLARE` doc strings, and the section for the newly added `MergeTree` setting `allow_experimental_text_index_scoring` appears only after the documentation autogeneration workflow runs. Link to the page without a fragment instead. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117519&sha=08464c3cde3ad904cc5fb312668c7fb5539d9114&name_0=PR&name_1=Docs%20check%20%28Mintlify%29 Pull request: ClickHouse#117519 Co-Authored-By: Claude Opus 5 <[email protected]>
The guard disabling the dynamic top-k filter when `_bm25_score` is in the read set was conservative: the direct read from the text index composes with the `__topKFilter` prewhere as-is. The pass that rewrites text-search predicates already merges the header-converting expression step of `tryOptimizeTopK` into the filter above the scan, a prewhere without text functions does not block the rewrite of that filter, and the reader chain executes index-read steps before prewhere steps, so `_bm25_score` is filled by the text index reader before `__topKFilter` consumes it. The filtering cannot skew the scores because the BM25 global statistics are collected from whole parts before reading starts. The threshold prewhere is the only top-k acceleration available for `_bm25_score` (a virtual column has no minmax skip index) and pays off well: rows that do not match the text predicate score 0, so once the top-k heap fills, the running threshold drops them before the payload columns are read (8 ms vs 74 ms on a 1M-row table with a wide column in a local check). Co-Authored-By: Claude Fable 5 <[email protected]>
| } | ||
| } | ||
|
|
||
| bm25_score_task_it->second.bm25_score_state = buildBM25State(*prepared_parts, index_read_tasks, reader_settings, context); |
There was a problem hiding this comment.
Explicit parallel replicas are still treated as supported, but buildBM25State(*prepared_parts, ...) runs before any replica coordination and every replica builds that state from its own local snapshot. createLocalParallelReplicasReadingStep just copies the local prepared_parts, and the explicit-parallel-replicas test here only covers the fully in-sync case, so a lagging replica that misses part P2 would score rows from P1 against corpus P1 while another replica scores its rows against P1 + P2. That makes the final ranking depend on replica assignment rather than query semantics. I think _bm25_score needs to reject all parallel-replica reads until the initiator can build and distribute one shared BM25 state for the coordinated snapshot.
Build profile diff (arm_release)Commit See the job log for details. |
`deserializeHeaderPrefix` now stops after `num_docs` and `sum_doc_length`. The doc-lengths segment size and offsets are read in `deserializeHeader`, right before the sparse index. `buildDocLengthsAndStats` in the text index merge switches to the prefix, so it no longer deserializes the sparse index of every source segment just to sum `sum_doc_length`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
CI randomizes `query_plan_max_limit_for_top_k_optimization` over `[0, 1, 10, 100, 1000, 100000]`. When it lands on `1`, `optimizeTopK` bails out because the test's `LIMIT 3` exceeds the setting, so `__topKFilter` never appears in the plan and the two `EXPLAIN` guards return `0` instead of `1`. Query results were unaffected. Pin the setting to its default, as other top-K tests already do. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117519&sha=4648a502d0d728f3d8add344f3b57ad401d695d7&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 Related: ClickHouse#117519
Resolve conflicts with the blocked positions layout of the text index (ClickHouse#111550): - `TextIndexHeader` and `MergeTreeIndexTextParams` carry `positions_codec`; the header writes it right after `has_positions` and before `has_scoring`. - `TokenPostingsInfo` stores `position_bytes` instead of `position_cardinality`, and both write paths encode positions with `TextIndexBlockedPositionsCodec`. - `MergeTextIndexesTask` decodes the positions of a source once its postings cursor is exhausted, pairing them with the pre-remap row ids captured by the cursor, because the blocked layout addresses positions by posting rank. - `MergeTreeReaderTextIndex::readAllPostingsForToken` uses the scoring-aware `readPostingsBlock` signature. Related: ClickHouse#117519
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…gments The temporary segments of the index materialization hold the doc lengths of their own rows only, while the row ids stay absolute within the part. `SegmentedPostingListCodec::encodeBlock` indexed the doc lengths by the absolute row id when computing the block-max `min_dl_byte`, reading past the end of the array in the second and later segments. Carry the row id of the first doc length in `PostingListBuildContext` and index the doc lengths by `row_id - doc_lengths_first_row_id`. The granule builder and the writable granule derive it from `num_docs - doc_lengths.size()`, the convention the segment merge already uses. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Resolve conflicts with ClickHouse#121976 (streaming merge of text index positions): take `PositionsMerge` from master and drop the per-source capture of pre-remap row ids (`captureRowIdsForPositions`, `readAndAppendPositions`, `flushPositions`); keep the BM25 term-frequency path of `PostingsMergeQueue` alongside the positions source tracking. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…gs change `textIndexValidator` ignored the `attach` flag, so a table with a scoring index failed to load after `allow_experimental_text_index_scoring` was turned off. The experimental gate is now checked only on `CREATE` / `ALTER`. A scoring index without an explicit `posting_list_codec` took the codec from the `text_index_posting_list_codec` table setting, so `ALTER TABLE ... MODIFY SETTING text_index_posting_list_codec = 'none'` made the stored index definition invalid and the table failed to load. A scoring index now requires an explicit `posting_list_codec` argument on `CREATE` / `ALTER`. Related: ClickHouse#117519 (comment) Related: ClickHouse#117519 (comment) Related: ClickHouse#117519 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- Rename `05333_bm25_scoring_failed_predicates` to `05333_bm25_scoring_unmatched_predicates`: the style check rejects test names containing 'fail'. - `05029_bm25_scoring_errors`: cover the DDL-time rejection of `scoring = 'bm25'` with `posting_list_codec = 'none'` and with a tokenizer that does not support scoring. - `05045_text_index_scoring_with_phrase_search`: compare the scores after the merge with an index built from the same rows without a merge, instead of checking `bm25() > 0`. - `05047_bm25_scoring_automatic_parallel_replicas`: check that the automatic parallel replicas optimization collects no dataflow statistics for a query computing `bm25`, against a query it supports. - Docs: describe the `BAD_ARGUMENTS` exception on parts with lightweight deletes or pending lightweight updates, the per-shard statistics of `Distributed` queries, and that `bm25` does not use automatic parallel replicas. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117519&sha=092473c78d4328af54dc1883711ab882a8ef4095&name_0=PR Related: ClickHouse#117519 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Replace the parallel per-column vectors `is_score_column`, `score_match_column` and `filled_with_score` of `MergeTreeReaderTextIndex` with one `ScoreLeaf` per score column holding the positions of its score and match columns, paired once in the constructor. A single `filled_with_score` flag per column remains for the posting-list paths to skip both columns of a leaf. Also drop `ScoreLeaf::can_match` (an unmatched predicate already has no cursors) and the redundant reset of the scoring cursors in `setIndexGranule` (every caller after construction runs `resetCursors` first). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Move the preparation of the query-global BM25 state (the check for parts with a lightweight `DELETE` or pending patches, and `buildBM25State`) into its own method, so `initializePipeline` only calls it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`bm25()` was rejected in a `WHERE` or `PREWHERE` condition, so there was no way to filter by the score: also `HAVING` and `QUALIFY` without aggregation and an outer `WHERE` over a subquery failed, because they end up in the same filters. Now the function can be used in `WHERE`, `PREWHERE`, `HAVING`, `QUALIFY`, `GROUP BY`, aggregate and window functions, `ORDER BY` and `LIMIT BY`, also through a subquery or a `WITH` alias. It is still rejected above a `JOIN` or an aggregation. A condition calling `bm25()` adds nothing to the score and is removed from the conjunctions masking the scores (`removeBM25Conditions`), so the score does not depend on itself. The DAG computing the score outputs it only under the names of the calls in the steps above it, which pass it through. A `PREWHERE` calling `bm25()` without a scoring predicate gets the score computed ahead of it from the `WHERE` filter (`addBM25ScoreToPrewhere`). The score of a row depends on the statistics of all parts the query reads, so a condition on it must not be kept in the query condition cache: `bm25` is not deterministic across queries, and the read with such a condition disables the cache, because the rewritten `PREWHERE` no longer calls `bm25`. `tryOptimizeTopK` now looks for the sort column in the filter below the expression when the expression only passes it through, so `ORDER BY bm25() LIMIT n` keeps the dynamic top-k filter when the `WHERE` condition calls `bm25`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The cached path of `addDocumentsFromLowCardinality` added the tokens of a repeated dictionary value to `num_processed_tokens` only, so such rows reached `incrementCurrentRow` with `tokens_in_current_row` = 0. Their stored document length and `sum_doc_length` were too small, and `bm25` scores were wrong. ClickHouse#117519 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`IMergeTreeIndex::getAllSubstreamsInPart` probed `getSubstreams` of the current definition. After a text index was redefined without `scoring = 'bm25'` (or without positions), a part could still hold `.dl` (or `.pos`), and a mutation rebuilding the index hardlinked the stale file with its checksum into the new part. Probe `getPotentialSubstreams` instead, which also covers the legacy minmax `.idx`, so the minmax override is removed. ClickHouse#117519 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`PForPostingListBlockCodec::skipBlock` decoded the skipped block into a 512-byte `scratch` member. Every token encoder of the index build owns a block codec, so the scratch buffer was allocated and zeroed for every large token, although it is used only on the decode path. The size of a PFor block follows from its header, so `PFor::skipBlocks` computes it without decoding the values, and the `scratch` member is removed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| if (part->hasLightweightDelete() || (mutations_snapshot && !mutations_snapshot->getPatchesForPart(part).empty())) | ||
| { | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, | ||
| "Cannot compute bm25(): part '{}' has rows hidden by a lightweight DELETE " |
There was a problem hiding this comment.
bm25() now rejects both lightweight deletes and pending lightweight updates, but this message only tells the user to run ALTER TABLE ... APPLY DELETED MASK or OPTIMIZE TABLE ... FINAL. For the update half of this guard, the public docs point users to ALTER TABLE ... APPLY PATCHES, so a query that fails because of pending patches gets the wrong remediation from the server itself. I think this exception text needs to mention APPLY PATCHES as well, or be specialized by condition.
| ) AS multi_part ON one_part.id = multi_part.id | ||
| ORDER BY one_part.id; | ||
|
|
||
| SELECT '-- lightweight delete: scoring is rejected while the part carries a deleted-rows mask'; |
There was a problem hiding this comment.
hasLightweightDelete() half of the guard. The same public contract also rejects pending lightweight updates via mutations_snapshot->getPatchesForPart(part), but there is no UPDATE ... / ALTER TABLE ... APPLY PATCHES case anywhere in the bm25 stateless suite. If that branch regresses, the docs will still claim the behavior even though we never test it.
| if (!format) | ||
| return false; | ||
|
|
||
| for (const auto & substream : index.getSubstreams()) |
There was a problem hiding this comment.
canMergeTextIndexFromIndexFiles currently treats "same substream set" as compatibility, but same-name text-index redefinitions can keep exactly the same .idx/.dct/.pst/.dl shape while changing the indexed semantics. getDeserializedFormat only validates physical layout and required-column types, so after DROP INDEX idx + ADD INDEX idx ... with a different tokenizer / preprocessor / postprocessor / indexed expression, an attached old part still passes this check and background merges will preserve postings built under the old semantics. That can silently return wrong matches and wrong bm25() scores. I think this needs a semantic-compatibility check here (or a forced rebuild unless the stored definition matches exactly), not just a substream-presence check.
`FilterStep` strips the aliases below its condition, so with `query_plan_merge_filters = 0` the condition `score > 1` pushed down into a subquery is a filter step of its own named `greater(__table1.score, 1_UInt8)` right over `bm25()`. `replaceBM25NodesWithInputs` rebuilt it under a name derived from its new arguments, `greater(bm25(), 1_UInt8)`, and the rebuilt step threw `NOT_FOUND_COLUMN_IN_BLOCK` for its filter column. The same renaming in the replacement by the assembled score broke a condition on the score that is also a column of the result, even with the default settings. `replaceNodes` gets `keep_names`, and both replacements of `bm25` keep the names of the outputs. ClickHouse#117519 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| /// writes. An older copy (e.g. no `.dl` while the index now has `scoring = 'bm25'`) is rebuilt from the rows instead. | ||
| static bool canMergeTextIndexFromIndexFiles(const IMergeTreeIndex & index, const IMergeTreeDataPart & part) | ||
| { | ||
| auto format = index.getDeserializedFormat(part, index.getFileName()); |
There was a problem hiding this comment.
getDeserializedFormat is also the read-time materialization gate, and it still only rejects missing files or required-column type drift. After DROP INDEX idx + ADD INDEX idx ... with the same name and ATTACH PARTITION, an old text index written under a different tokenizer / preprocessor / indexed expression still passes here, so direct-read planning, MergeTreeReaderTextIndex, trivial-count, and bm25() can all query postings built under the old semantics even before any merge rewrites the part. I think same-name reuse needs a semantic-definition check here too (or a hard refusal until the index is materialized again), not just physical-layout compatibility.
… condition `MergeTreeIndexConditionText` no longer has state written after its construction. The direct-read optimization used to register the virtual columns and the `bm25` score columns on the unsubstituted condition, and the per-part conditions saw the score columns only through `TextIndexScoringQueries` shared by all conditions of the template. Now `IndexReadTask` holds the search query of each virtual column and the scoring tokens, and every consumer takes them from the task: `MergeTreeReaderTextIndex`, `BM25GlobalStatsBuilder`, `optimizeTrivialCountFromTextIndex` and the analysis of text index granules, which gets the task through `filterMarksUsingIndex` and `MergeTreeIndexReader::read`. The term frequencies are decoded only for the scoring tokens instead of all tokens of a query computing `bm25`. `replaceToVirtualColumn` and `registerScoreVirtualColumn` become the const `tryGetVirtualColumnName` and `getScoreVirtualColumnName`. The condition always owns a clone of the index tokenizer. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| @@ -4165,7 +4166,7 @@ void updateIndicesToRecalculateAndDrop(std::shared_ptr<MutationContext> & ctx) | |||
| /// all skip-index types. This both detects archive_dirty for drop-only mutations and yields | |||
There was a problem hiding this comment.
This cleanup only teaches the mutation path about the extra .dl files; it still does not teach it when a same-name text index must be rebuilt rather than hardlinked forward.
After DROP INDEX idx + ADD INDEX idx ... with a different tokenizer / preprocessor / indexed expression, an attached old Wide part can enter updateIndicesToRecalculateAndDrop with all of the current fast-path predicates false: materialized_indices is empty for an unrelated mutation, the part is full Wide storage, the index is not packed, and its old files are still checksum-resolvable. In that case need_recalculate stays false and the later hardlink branch at src/Storages/MergeTree/MutateTask.cpp:3032 preserves the old .idx/.dct/.pst/.dl files byte-for-byte into the new part.
So the same-name redefinition bug is no longer confined to the original attached part or to non-row-reducing merges: a harmless ALTER TABLE ... UPDATE other_col = ... can mint a brand-new part whose text index still encodes the old semantics. I think this path needs the same semantic-compatibility gate as the read/merge paths, or it should force a rebuild whenever the source part's stored definition does not exactly match the current index definition.
| { | ||
| auto & result = getAnalysisResult(); | ||
|
|
||
| /// Before any pool or processor copies the settings: both build the PREWHERE steps and must agree on them. |
There was a problem hiding this comment.
getAnalysisResult() is already available here, but prepareBM25State still validates and builds against *prepared_parts, i.e. the pre-analysis snapshot. A part that partition / primary-key / skip-index pruning removed completely can therefore still skew N, df, and avgdl and even trip the lightweight-delete / pending-patch rejection, which contradicts the PR contract that collection stats come from “the parts the server reads”. I think this should use the deduplicated part set from result.parts_with_ranges instead.
Extracted from ClickHouse#117519, which builds BM25 scoring on top of it. Mechanical changes: - Rename `MergeTreeIndexTextPostingListCursor.{h,cpp}` to `PostingListCursor.{h,cpp}` and `FlatPostingsPtr` to `PaddedPODArrayPtr`, defined in `IPostingListCodec.h`. - Replace `MergeTreeIndexTextParams::positions` with the bool `enable_positions`. - Replace the `skip_postings` arguments of `deserializeTokenInfo` and `deserializeDictionaryBlock` with `with_postings` without a default, and `MergeTreeIndexDeserializationState::skip_postings_deserialization` with `text_index_read_postings`. - Make `loadHeader` and `matchTokens` free functions, extract `makeIndexIdForCaches`, `skipVarUInts` and `readVarUInts`, and make `serializeTokensAndPostings` a plain function. - Take `std::span<const uint32_t>` in the posting list block codecs. - Capture the index in the condition factory of the vector similarity index instead of a raw pointer to it. - Remove the unused `IndexReadTask::is_final`. Keep the search queries of the virtual columns of a text index in `IndexReadTask` instead of the condition: `MergeTreeIndexConditionText` is no longer modified after construction. `replaceToVirtualColumn` becomes the const `tryGetVirtualColumnName`, `getSearchQueryForVirtualColumn` is removed, and `MergeTreeReaderTextIndex` and `optimizeTrivialCountFromTextIndex` take the queries from the read task, which `createMergeTreeReaderIndex` now receives whole. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A part may hold a substream of a skip index that the current definition does not write, e.g. the `.pos` of a text index created with `support_phrase_search = 1` and redefined without it while the part was detached. `getAllSubstreamsInPart` probed only `getSubstreams`, so a mutation that rebuilds the index did not see the stale `.pos` and hardlinked it into the new part. It now probes `getPotentialSubstreams`, which also covers the legacy minmax `.idx`, so the override of `MergeTreeIndexMinMax` is removed and the function is no longer virtual. Extracted from ClickHouse#117519. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Resolve conflicts with ClickHouse#124595 and adapt the BM25 code to its refactoring: `IndexReadTask` keeps the search query in `IndexReadTask::Column`, `TextIndexDAGReplacer` builds `IndexReadTasks` directly (including the score columns), and `createReadTasksForTextIndex` takes the tasks. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`ReadFromMergeTree::computesSortColumnForTopK` runs in the first optimization pass, before the text index read tasks exist, so it predicts that the direct read will compute `bm25`. Only a text index created with `scoring = 'bm25'` can compute it, so check the index parameters instead of accepting any text index. Also minor formatting in `MergeTreeIndexText`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…engths with `scoring = 'bm25'` A text index with the experimental argument `scoring = 'bm25'` (MergeTree setting `allow_experimental_text_index_scoring`) is written in the `v3_with_scoring` format: - per-row `(tf - 1)` blocks after the row-id blocks of the posting lists (`bitpacking` and `pfor`), and after the row ids of raw and embedded postings, with the `HasTermFrequencies` flag of the token; - block-max inputs (min `SmallFloat` document length, max saturated `(tf - 1)`) per segment and per packed block; - the `.dl` substream with one `SmallFloat` document length per row and the marks of the part; - the collection statistics (number of rows, sum of document lengths) in the header. Inserts, merges and the materialization of the index carry the scoring data. The existing readers skip the term frequencies. The scoring requires a posting list codec set in the index definition and a tokenizer that supports it. Extracted from ClickHouse#117519. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…coringCursor` `MergeTreeIndexGranuleText::readPostingsBlock` can decode a block into `ScoringPostings` (row ids with their term frequencies), cached in the postings cache as a separate kind. The analysis of a granule decodes the single-block postings of the tokens in `IndexReadTask::scoring_tokens` this way. `PostingListScoringCursor` extends `PostingListCursor` with the term frequencies and the block-max inputs. Extracted from ClickHouse#117519. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
In `WHERE` and `PREWHERE` the direct read replaces `termFrequency` on the column of a text index with `scoring = 'bm25'` by a `UInt32` virtual column that `MergeTreeReaderTextIndex` fills from the term frequencies of the index. The condition of the index looks up its token outside of the RPN, so it analyzes all tokens of the condition and never skips a part on it. A part whose index has no scoring data throws `BAD_ARGUMENTS`. Extracted from ClickHouse#117519. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…engths with `scoring = 'bm25'` A text index with the experimental argument `scoring = 'bm25'` (MergeTree setting `allow_experimental_text_index_scoring`) is written in the `v3_with_scoring` format: - per-row `(tf - 1)` blocks after the row-id blocks of the posting lists (`bitpacking` and `pfor`), and after the row ids of raw and embedded postings, with the `HasTermFrequencies` flag of the token; - block-max inputs (min `SmallFloat` document length, max saturated `(tf - 1)`) per segment and per packed block; - the `.dl` substream with one `SmallFloat` document length per row and the marks of the part; - the collection statistics (number of rows, sum of document lengths) in the header. Inserts, merges and the materialization of the index carry the scoring data. The existing readers skip the term frequencies. The scoring requires a posting list codec set in the index definition and a tokenizer that supports it. `mergeTreeTextIndex` returns the term frequencies in the virtual column `term_frequency`, which exists for an index with `scoring = 'bm25'`. Reading it from a part whose index has no scoring data throws `BAD_ARGUMENTS`. Extracted from ClickHouse#117519. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Adds Okapi BM25 relevance scoring to text indexes: a new index argument
scoring = 'bm25'that stores the scoring data, and a new functionbm25that ranks the rows matched by the text-search predicates of a query.Closes: #92097
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added experimental BM25 relevance scoring for text indexes. A text index created with the argument
scoring = 'bm25'additionally stores per-row term frequencies and document lengths. The new functionbm25([k1[, b]])returns the BM25 score for row of a query that filters withhasToken,hasAnyTokensorhasAllTokenson the indexed column, for exampleSELECT id, bm25() FROM tab WHERE hasAnyTokens(body, 'clickhouse is blazingly fast') ORDER BY bm25() DESC LIMIT 10. The score follows the boolean structure of the filter. The on-disk format and the SQL syntax are experimental and may change.Implementation details:
(tf - 1), so the commontf == 1case is all zeros. Term frequencies are written as a separate block after row IDs using the same block codec (pfor,bitpacking). Scoring is not supported with thenonecodec..dlsubstream. It holds one byte per row: the token count of the row encoded withSmallFloat, an order-preserving lossy encoding that is exact below 80, keeps 4 significant bits above, and saturates at2^24 - 1. The substream is uncompressed and gets the marks of the part, so scoring reads it like aUInt8column, only for the granules being read.(tf - 1), which are the inputs of a per-block score upper bound. They are written and read back, but not used for pruning yet.bm25()is exposed. It is replaced by the expression that consists of virtual columns during plan optimization. Virtual columns with score are filled for each predicate inMergeTreeReaderTextIndex(hasAnyTokens,hasAllTokens,hasToken), and assembled into the final score with considering the boolean structure of theWHEREclause.Limitations
bm25.Distributedquery each shard scores with its own statistics.Workflow [PR]
Sync PR [sync-upstream/pr/117519]