Skip to content

Text index: seek the dictionary to the matching block range for anchored LIKE patterns - #120495

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:text-index-dictionary-scan-narrowing
Sep 19, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:text-index-dictionary-scan-narrowing

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120457

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Speed up LIKE, ILIKE, startsWith and endsWith evaluated by a text index dictionary scan (use_text_index_like_evaluation_by_dictionary_scan): the scan now seeks the sorted dictionary to the block range an anchored pattern can match, and tests a block's tokens for the pattern's mandatory literal in one pass instead of running the matcher on every token.

Description

A pattern evaluated by dictionary scan read every dictionary block of the part and called the matcher once per token. Two facts were unused: the dictionary is sorted and the sparse index stores each block's first token, and every compiled pattern carries a mandatory literal match tests first.

Follow-up item 2 at MergeTreeIndexConditionText.cpp:1536 (item 3 is #116585's). #114613 has the same primitive wired only to JSON paths.

Two mechanisms:

  1. Per pattern, the token-key range it can match (Prefix -> the prefix range, Exact -> a point range, anything else declines) becomes merged half-open block intervals. Prefix/Exact are byte comparisons, since the constructor demotes a case-insensitive anchored literal to General, and that is the order the dictionary is sorted in, so ILIKE never narrows. A prefix sorting below the whole dictionary now reads 0 blocks.
  2. A block's tokens are filtered by each pattern's literal in one pass using the pattern's own searcher, so the folding rule cannot diverge from match's. addTokenToPatterns stays the only decider and the filter yields a superset of what it accepts, so results are unchanged.

Measured with the perf test added here (30 parts, 500008 dictionary tokens and 977 blocks each, single-threaded, Release, 25-run medians): infix LIKE -21.7%, LIKE 'needle%' and startsWith -58.4% (29310 -> 690 blocks), ILIKE -11.9%, suffix LIKE and endsWith -19.4%. A prefix covering one block per part reaches -95.8%, too fast to ship as an arm. The filter's worst case, a literal in 500000 of 500008 tokens, is +0.8%, inside that arm's spread; hasToken does not use this path.

The pattern scan now also increments the existing TextIndexReadDictionaryBlocks, making the blocks it reads observable. No setting, no format change.

Reported and prototyped by @ snelheidai in #120457.


Workflow [PR]
Sync PR [sync-upstream/pr/120495]

Version info

  • Merged into: 26.10.1.164 (included in 26.10 and later)

groeneai and others added 4 commits September 16, 2026 21:22
…n can match

Evaluating LIKE / ILIKE / startsWith / endsWith by dictionary scan
(use_text_index_like_evaluation_by_dictionary_scan, on by default) read every
dictionary block of the part, whatever the pattern's shape. The dictionary is
globally sorted and the header's sparse index already stores each block's first
token, so an anchored pattern can only match inside one contiguous block range.
This is follow-up item 2 of the list in MergeTreeIndexConditionText.cpp.

TextIndexAnalyzer::getPatternTokenKeyRanges reports, per pattern, the half-open
range of token keys it can match: [literal, firstStringThatIsGreaterThan-
AllStringsWithPrefix(literal)) for a Prefix pattern, the point range [literal,
literal] for an Exact one (which requires subject_size == literal_size, so at
most one block can hold it), and nothing for Suffix / Substring / General, which
decline the narrowing for the whole scan.

Prefix and Exact are byte comparisons: the OptimizedRegularExpression
constructor demotes a case-insensitive anchored literal to General, because a
case-insensitive re2 folds Unicode and a byte comparison cannot reproduce that.
Byte order is the order the dictionary is sorted in, so the narrowing is sound
in that order, and ILIKE never reaches it.

blocksMatchingTokenKeyRanges turns the key ranges into merged block intervals.
No block before range_begin can hold a matchable token, since a block is indexed
by its smallest token and first(range_begin) <= begin by upperBound; no block at
or after range_end can, since all its tokens exceed the range's end key while
every matchable token is below it. upperBound's strict comparison keeps a block
whose first token equals the end key, which is one extra block and still
correct.

Intervals rather than a materialized list of block indices: dictionary_block_size
is user-settable down to 1, so a wide range over a large dictionary would hold
millions of indices. There is no sentinel value either: an unrestricted scan is
the single interval [0, size), and an empty vector means no block can match, so
a prefix absent from the dictionary now reads nothing instead of falling back to
a full scan.

text_index_like_max_postings_to_read behaves identically: the budget accumulates
only over matched tokens, blocks are still visited in ascending order, and a
skipped block provably holds no matching token, so the bypass fires at the same
point.

The pattern scan also now increments TextIndexReadDictionaryBlocks, which so far
only the exact-token scan did. Without it the number of blocks this scan reads is
not observable, which is what makes a test of the narrowing timing-based.

Reported and prototyped by @snelheidai in ClickHouse#120457.

Co-Authored-By: Claude Opus 5 <[email protected]>
…in one pass

The dictionary pattern scan ran the compiled matcher once per token of every
block it visited. A block's tokens are contiguous in one ColumnString buffer and
every compiled pattern carries a mandatory literal that match() tests before
re2, so one searcher pass over that buffer already finds every token that can
match.

TextIndexAnalyzer::matchTokensByLiterals marks the tokens containing some
pattern's literal, then runs addTokenToPatterns only on the marked ones. The
matcher stays the only decider: a token no pattern's literal occurs in would
have been rejected by match() anyway, on each of its three paths - anchored
(memcmp at the one possible offset), trivial and general (both refuse a subject
the searcher does not find the literal in). Hence the marked set is a superset
of the matched set and the result is unchanged. The filter is disabled for the
whole scan if any pattern has no literal, in which case the per-token loop is
kept.

OptimizedRegularExpression::searchRequiredSubstring exposes the pattern's own
searcher. Using that searcher rather than a locally built one is what makes the
superset property hold: only one of the two searchers is ever constructed, so
the folding rule cannot diverge from the one match() applies. This is also why
MatchImpl's loop is not reused - its VolnitskyCaseInsensitiveUTF8 falls back to
UTF8CaseInsensitiveStringSearcher, which folds differently from the
ASCIICaseInsensitiveStringSearcher match() uses, and for the case-sensitive path
Volnitsky degenerates to the same CaseSensitiveStringSearcher below 20000 bytes
of haystack, which every dictionary block is.

ILIKE reaches the filter and is safe. stringLikeToPatterns refuses any needle
holding a character reachable by ASCII case folding (U+212A folds onto 'k')
before the scan starts, so a token whose bytes only fold to the needle under
Unicode rules cannot arrive here.

The per-pattern pass follows the required-substring loop of
MatchImpl::vectorConstant, including its containment check: tokens are stored
back to back and are not zero-terminated, so an occurrence may straddle two of
them. Skipping such a hit is exact rather than conservative, because an
occurrence contained in the token would have to start earlier than one leaving
it. Marks, not a collected candidate list: queries_by_pattern holds one entry
per pattern of every search query in the RPN, so several patterns are ordinary,
and a union of per-pattern index lists would grow as patterns x tokens and need
a sort and a dedup pass. One byte per token of the block is allocated once per
scan and emits ascending and unique indices, as deserializeTokenInfos requires.

Tests. 05218_text_index_like_dictionary_scan_pruning pins the number of
dictionary blocks read for each pattern shape against a hand-sized dictionary of
4 blocks, and compares every scenario against the same query with
use_skip_indexes = 0, so over-pruning changes the result and under-pruning
changes the counter. A prefix absent below the whole dictionary reads 0 blocks
and an infix reads all 4, which are the two-directional sensitivity controls.
The gtest asserts the superset property directly, including the ASCII-folded
case, which is not observable from SQL on its own. The performance test carries
a 500000-token dictionary, since the existing text_index_like.xml fixture has
about 20 tokens, i.e. one block, where neither change is visible.

Reported and prototyped by @snelheidai in ClickHouse#120457.

Co-Authored-By: Claude Opus 5 <[email protected]>
… recalibrate the perf test

Three test-level gaps found while reviewing the two preceding commits.

A literal occurrence may straddle two adjacent dictionary tokens, because a
block's tokens are stored back to back and are not zero-terminated, and the
filter must then attribute the hit to no token at all and carry on with the
next one. No scenario reached that branch, whose failure mode is a token that
should have matched being skipped, i.e. rows missing from a LIKE result.
'aabb', 'ccdd', 'xxbbcc', 'yybb' share one block as the bytes
'aabbccddxxbbccyybb', where 'bbcc' straddles the first two tokens and then ends
exactly on the end of 'xxbbcc', so one scenario exercises the straddle and the
containment test's boundary at once.

A pattern whose every literal run is shorter than the three bytes the regexp
analysis requires carries no mandatory literal, so it can match a token
anywhere in the dictionary. Both new gates therefore refuse for the whole scan
as soon as one pattern is like that, and nothing tested it. The array tokenizer
admits 'a%b%c%d' because it counts non-wildcard characters, which gives such a
pattern; the scenarios pair it with a literal-bearing prefix as well as running
it alone, and assert the full block count against the one block that prefix
alone is narrowed to.

The performance test's queries all ran far outside the 0.1 to 1 second window
the harness requires, the anchored ones at 5 ms and the dense one at 4.6 s, so
it could not have measured what it exists to defend. The scan runs once per
part, so the table is now 30 parts with merges pinned instead of one, the
needle is broader to give the patched side work to do, the dense case moved to
its own single-part table, and the hasToken query is gone: the token scan
already seeks to one block per part, so no fixture of this shape can lift it
above the floor, and five other text index performance tests cover it.

Also state on TokenKeyRange that equal bounds mean the single key, since the
Exact case relies on it and a lowerBound-style seek would silently break it.
Drop the block-range end-bound comment (the sort-order property is stated one comment above), cut the two contract comments that restated the code below them.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 3 major fixed, 1 declined, 4 nits

Each round ran two independent cold passes over this diff, my own read of the resulting code and a
second-model re-review, every finding adjudicated against the source and not against the diff's own
comments. Both soundness arguments hold, closed from the surrounding code rather than from the change:
Prefix and Exact really are byte comparisons, because the OptimizedRegularExpression constructor
demotes a case-insensitive anchored literal to General and analyzeAnchoredLiteral only yields an
anchored kind when the whole regexp body equals required_substring, and that is the order the dictionary
is sorted in, so ILIKE never reaches the narrowing; the per-block filter uses the pattern's own searcher,
of which only one is ever constructed, so the folding rule cannot diverge from the one match() applies,
and addTokenToPatterns stays the only decider; the postings budget is bit-identical.

⚠️ major, test coverage: the straddling-occurrence branch had no test. A block's tokens sit back to
back in one ColumnString buffer with no separator, so a needle spanning two adjacent tokens produces a
hit the filter must skip, and its failure mode is rows silently missing from a LIKE result; it now has a
scenario where a straddling hit is followed by a contained hit in the same block at the <= equality
boundary, with negative controls replacing the jump to the next token with break, or the containment
<= with <, each turning the pinned [3] into []. AGREED, fixed.

⚠️ major, test coverage: the empty-mandatory-literal decline path had no test. Both new gates are
all-or-nothing over the pattern set, so the token filter's all_of as any_of, or the key-range helper's
early nullopt as a continue, would have silently dropped a literal-less pattern's matching tokens from
a mixed query, reachable at default settings since a sub-3-byte literal is dropped during regexp analysis
while the array tokenizer admits a pattern on its non-wildcard character count; now covered alone,
mixed, and against a prefix-alone control that proves the narrowing is live on that table, with mutations
that abort on the empty-literal assertion and turn [1,2,3,4,5,6,7] into [5,6,7]. AGREED, fixed.

⚠️ major, benchmark validity: the new performance test's queries were far below the harness floor.
Seven of its eight queries ran 5x to 100x under the 0.1 s the performance harness requires and the eighth
above the 1 s ideal, so the file would have raised action-required duration and stability errors on every
run that sampled it, and at 5 ms against 22 ms it could not have measured the improvement it exists to
defend; it now runs single-threaded over 30 parts with merges pinned off, and all seven committed queries
measure 251-689 ms on both sides with 0.8-8.3% spread. Two prescriptions of mine were refuted by
measurement and correctly overridden: index_granularity is not a lever, because the number of matched
granules falls as the granule grows, and the hasToken arm cannot be lifted into the window at all, so it
was dropped in favour of the coverage it already has in five other text-index performance tests.
AGREED, fixed.

❌ declined: a new ProfileEvent counting matcher calls or candidate tokens. The second pass asked for
one on the grounds that disabling the token filter leaves every assertion green, which is true of the
filter's performance and not of its contract. Under-marking is caught in both directions today: drop the
mark and the matched-token list comes out empty, so a pinned prefix scenario returns nothing against its
pinned rows and all fourteen use_skip_indexes = 0 pairs break. The suggested mutation instead degrades
to the previous per-token loop, which is correct behaviour, so a test that reddened on it would assert
that an optimization is switched on rather than that the code is right; that belongs to the performance
test, which is why the finding above was accepted. The one counter this PR does touch is an existing one,
extended because the narrowing changes what is read.

💡 nits. Fixed: the exact-point encoding of the token-key range is now stated on the struct (equal
bounds mean one key, not an empty range, which a later switch to a lower-bound seek would have broken);
the changelog wording; and the description no longer claims that any absent prefix reads zero blocks,
since one sorting inside the dictionary's key space still reads its single candidate block. Noted and not
blocking: the dense control's comment says its literal occurs in all 500008 tokens, where the exact figure
is 500000 of 500008, the other eight being the shared words of the filler sentence, which the pattern
never matches and which therefore charge no postings budget (measured: zero discards at the default
budget); the performance test does not pin use_text_index_like_evaluation_by_dictionary_scan, matching
the neighbouring text_index_like.xml; its 30 explicit inserts are verbose, but the tidier single insert
was measured and rejected because it produced parts of 348384 to 523272 rows, making every pinned block
count non-deterministic; and the dense arm's 8.3% spread is the highest of the seven, against 0.8-2.4%
for the rest.

@clickhouse-gh clickhouse-gh Bot closed this Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Not a bug, so the observable is the block count: against a 4-block hand-sized dictionary the scan reads exactly 0 / 1 / 2 / 4 blocks per pattern shape, pinned in the new test. A separate 10-block fixture gave the same table.
b Root cause explained? The pattern scan was a full linear dictionary walk with a per-token matcher call, using neither fact its surroundings establish: the dictionary is sorted with a searchable sparse index, and every pattern carries a mandatory literal match() tests before re2.
c Fix matches root cause? Yes: it seeks the sorted structure and tests that necessary condition in bulk. No widened bound, no reduced dataset, no no-random-* tag, no defensive check, no new setting, no format change.
d Test intent preserved / new tests added? No existing test weakened; 216/217 of the text_index family pass unchanged (the 1 needs the stateful test.hits). Added: a 17-scenario stateless oracle, a gtest for the one property SQL cannot observe, and a performance test with a large dictionary. Each of the four branches a mutation can reach was verified by building that mutation and observing the scenario redden.
e Both directions demonstrated? Three release binaries from the same tree and compiler (base / commit 1 / both), distinct Build-IDs. The counter goes 977 blocks -> 1 on the prefix arms, and each commit moves only the arms its mechanism predicts.
f Fix is general across code paths? The sibling exact-token scan already narrows with the same upperBound(token) - 1 idiom and is untouched. addTokenToPatterns stays the sole matcher of a token (one caller). Both DictionarySparseIndex representations hold: BitPackedStringArray::get returns full token bytes, only the offsets are bit-packed.
g Fix generalizes across inputs (params/datatypes/wrappers)? One scenario each for Prefix / Exact / Suffix / Substring / General, both accepted tokenizers, case-sensitive and case-insensitive, a token that is a strict prefix of another, an all-0xFF prefix (no upper bound), a prefix below the whole dictionary (empty range), a range spanning a block boundary, several patterns in one query, LowCardinality(String), Nullable(String), two parts, dictionary_block_size = 4, and the postings-budget bailout. An empty mandatory literal declines both mechanisms, tested both on its own and paired with a literal-bearing prefix in one query, as is a literal occurrence straddling two adjacent dictionary tokens.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or defaulted differently and no serialization format touched, so no SettingsChangesHistory.cpp entry is owed. The only observable change is that an existing ProfileEvent now also counts blocks read by this scan.
i Invariants and contracts preserved? matched_indices still comes out ascending and unique as deserializeTokenInfos requires; blocks are still visited in ascending order and the text_index_like_max_postings_to_read budget still accumulates only over matched tokens, so the bypass fires at the same point (asserted by a test scenario with the budget at 1). The scratch mark buffer is re-assigned per block, so nothing leaks between blocks.

Session id: cron:clickhouse-impl-slot-5:20260916-210900

@groeneai
groeneai requested review from CurtizJ and ahmadov September 17, 2026 01:09
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [69de08b]

Summary: ✅


AI Review

Summary

This PR narrows text-index dictionary scans for anchored LIKE patterns to the sparse-index block ranges that can actually contain matching tokens, and adds a per-block literal prefilter for pattern queries, with targeted stateless, gtest, and performance coverage. The previously reported exclusive upper-bound over-read is fixed in the current code, and I did not find a remaining correctness, test, or PR-metadata issue in the current diff.

Final Verdict

✅ No actionable review findings in the current patch.

LLVM Coverage Report

Measured on commit 69de08b.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 132/135 (97.78%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=12 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: fccffc3b-93d0-4aca-8051-d4b9ad9fb4f4
  • MIRAI run: ba753e65-1b00-4fc3-8737-1c23d9092eb3
  • PR check IDs:
    • clickbench_545318_1789634485
    • clickbench_545324_1789634485
    • clickbench_545330_1789634485
    • tpch_adapted_1_official_545341_1789634485
    • tpch_adapted_1_official_545352_1789634485
    • tpch_adapted_1_official_545388_1789634485

`blocksMatchingTokenKeyRanges` resolved both ends of a token-key range with
`upperBound`. For an anchored prefix the end is exclusive, being
`firstStringThatIsGreaterThanAllStringsWithPrefix` of the literal, so
`upperBound` kept the block whose first token is exactly that bound. The
dictionary is sorted, so every token of such a block is at or beyond the bound
and none of them can carry the prefix.

Measured on a two-block dictionary whose second block starts exactly at
`toab`: `LIKE 'toaa%'` read 2 blocks where 1 suffices, per pattern and per
part. The rows returned were never affected, because the per-token matcher
still decided, so this was an over-read and not a wrong result.

Resolve an exclusive end with a new `DictionarySparseIndex::lowerBound`, and
keep the `Exact` kind on `upperBound`: its bounds are equal and denote a single
key, so a lower-bound lookup would drop the very block that starts with it.

The example given in the report, a sparse index `["foo0", "fop0", ...]` queried
with `foo%`, does not exhibit this. `fop0` is strictly greater than the bound
`fop`, so that block was already excluded; only a block starting exactly at the
bound was read needlessly.

Found by the automated review on
ClickHouse#120495 (comment)
The comment claimed the literal occurs in all 500008 tokens and that every
token has a single posting. Both hold for the 500000 `toxxN` tokens but not for
the eight words each message shares, which carry 500000 postings apiece. The
control's conclusion is unchanged: those eight never contain the literal, so
they charge no postings budget, measured as zero discards at the default.

This was disclosed as a residual when the PR was opened, because the phase that
found it could only change comments in `src/`.
`blocksMatchingTokenKeyRanges` declared `range_end` without an initializer and
assigned it in every branch of the if/else chain below it. This tree enables
clang-tidy's `cppcoreguidelines-init-variables`, so `Build (arm_tidy)` failed:

    src/Storages/MergeTree/MergeTreeIndexText.cpp:516:16: error: variable
    'range_end' is not initialized [cppcoreguidelines-init-variables]

Initialize it where it is declared, the way the neighbouring `range_begin`
does, using the unbounded value an empty `end` selects, and narrow it only when
`end` is set. All three cases keep their results, so the block ranges the
dictionary scan visits are unchanged.

Verified with clang-tidy-22 and this tree's `.clang-tidy`: the error is
reported before the change and nothing after it. Reverting the exclusive-end
lookup inside the rewritten statement still reddens `05218_at_upper_bound`
(2 blocks read instead of 1), so the pinned block counts remain sensitive to it.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 69de08b05 with master 718e603a5 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

10 object files changed (+36.85 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexText.cpp.o 777.87 KiB 798.34 KiB +20.46 KiB (+2.63%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

304 translation units recompiled, 2770 s compile time in total, 304 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.89 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -438.1 s (-14%) in total before that adjustment.

Job report

@snelheidai

Copy link
Copy Markdown

ClickBench and TPC-H carry no text index, so the Cloud Performance Report above is silent on the path this PR changes. End-to-end numbers on it, on a large-vocabulary fixture rather than the one-unique-token-per-row shape of the new perf test:

distinct tokens query master 7dc4a129f21 + this PR Δ
2,000,009 LIKE '%zqneedle%' 1704 ms 1375 ms -19.3%
2,000,009 ILIKE '%ZQNEEDLE%' 1716 ms 1369 ms -20.2%
40,010 LIKE '%zqneedle%' 253 ms 212 ms -16.2%
40,010 ILIKE '%ZQNEEDLE%' 252 ms 206 ms -18.3%

8M rows, 128 parts, text(tokenizer = splitByNonAlpha) GRANULARITY 1, one server, max_threads = 1, 9 repetitions, median query_duration_ms, Linux aarch64 4 cores, Release. Head 69de08b0586 applied on 7dc4a129f21; no upstream commit touches MergeTreeIndexText.{cpp,h}, MergeTreeIndexConditionText.*, ITokenizer.cpp or the searcher between that base and current master 0fb497f86f8. The master column comes from an earlier run on the same fixture, whose in-run use_text_index_like_evaluation_by_dictionary_scan = 0 and no-index anchors reproduce their recorded values within 2-4%, so read these percentages at that precision.

The time comes out of the scan, not out of pruning: TextIndexReadGranulesMicroseconds 1602 -> 1275 ms on the 2M fixture, with read_rows 131,072 of 8,000,000 and 16 of 992 marks on both sides. 13 query shapes returned identical answers against index-off, an unindexed twin of the same rows and hasToken, on both fixtures.

One correction to my own estimate in #120457, where I extrapolated your ILIKE -11.9% and predicted ~1510 ms here: ILIKE in fact gains as much as LIKE, reading an identical 85,427 dictionary blocks at 1265 vs 1275 ms of granule time. At this vocabulary the per-block literal filter and not the block-range narrowing is what pays — consistent with the demotion argument in your description, which only rules out the narrowing. So your -11.9% is a floor for that arm, not a ceiling.

The residual, relevant to the Related to #120457 link: at 2,000,009 distinct tokens (~24 per row) the narrowed scan still costs 1375 ms against 775 ms with use_text_index_like_evaluation_by_dictionary_scan = 0 and 737 ms for the same rows with no text index at all, both measured in the same run, so the scan remains a net loss in that regime. Adding the per-part cost bound from my #120457 comment on top of this PR takes the same query to 799 ms, a further -41.9% (9 paired repetitions inside one binary, 1362-1385 vs 789-810 ms, TextIndexDiscardPatternScan firing once per part). That settles the one combination I listed there as unmeasured: the bound composes with the narrowing rather than competing with it, and the cheaper per-token scan moves my estimated crossover from ~8 to ~10 dictionary tokens per row, so the proposed default of 4 stays conservative.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for running this end to end.

I am not folding those percentages into the description. I have not reproduced that fixture, and the figures there are what the committed perf test measures, with the ILIKE number stated for that fixture rather than as a ceiling, so nothing in it needs correcting. I did check the base you compared against: no commit since 7dc4a129f21 touches MergeTreeIndexText.*, MergeTreeIndexConditionText.* or ITokenExtractor.cpp.

On the residual: this PR narrows what the dictionary scan costs, it does not decide when the scan should run. That question and the per-part bound stay in #120457, and I am not pulling them into this diff.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good change, thanks!

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 38c82eb Sep 19, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@ahmadov Just FYI^^ (since in your code)

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 2, 2026
Compile bounded byte automata from literals and RE2 expressions, reuse common
prefix states, and seek past rejected dictionary subtrees. Integrate with the
existing `LIKE` dictionary reader and postings budget without changing the
index format. Add differential, SQL and performance coverage.

Motivation: https://playground.serenedb.com/searchbench
Related: ClickHouse#120495
Related: ClickHouse#115617
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text index: the dictionary pattern scan walks every block and matches every token; narrowing it cuts LIKE/ILIKE query time 5-16%

5 participants