Skip to content

Text index: serve position(s, 'x') > 0 as s LIKE '%x%' - #122069

Open
valerypetrov wants to merge 35 commits into
ClickHouse:masterfrom
valerypetrov:text-index-position
Open

valerypetrov wants to merge 35 commits into
ClickHouse:masterfrom
valerypetrov:text-index-position

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Related: #113086

Queries like WHERE position(message, 'error') > 0 can now use a text index on message, the same way WHERE message LIKE '%error%' already does. Before, the text index was ignored for position.

This also works for positionUTF8, countSubstrings and the case-insensitive versions of these functions.

test case query master this PR
3M log rows, few distinct words position(message, 'charged') > 0 9 ms 1 ms
3M log rows, a unique id in every row position(message, 'charged') > 0 13 ms 40 ms

The second case is slower because the index has to check every distinct word. LIKE '%charged%' behaves the same way on master. The "this PR" numbers were measured with that equivalent LIKE query.

Changelog category (leave one):

  • Performance Improvement

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

The text index is now used for position(s, 'needle') > 0, the same way as for s LIKE '%needle%'.

🤖 Generated with Claude Code


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

valerypetrov and others added 2 commits September 24, 2026 11:30
`position(s, 'x') > 0` and the comparisons equivalent to it (`!= 0`,
`>= 1` and the mirrored forms such as `0 < position(s, 'x')`) only test
whether the needle occurs in `s`, which is `s LIKE '%x%'` with `%`, `_`
and `\` escaped. The text index recognized only the LIKE spelling, so
this common idiom from MySQL read every granule (ClickHouse#113086).

Recognize these comparisons over `position`, `positionUTF8` and
`countSubstrings` and hand the escaped pattern to the existing LIKE
analysis, so the dictionary scan, the Exact/Hint choice and direct read
follow the LIKE rules unchanged. `positionCaseInsensitive` (alias
`instr`) and `countSubstringsCaseInsensitive` go through the ILIKE
analysis: they search with ASCIICaseInsensitiveStringSearcher, the same
ASCII-only folding the dictionary scan matches tokens with.

The start-position form, an empty needle (`position(s, '')` is 1 for
every row), a non-constant needle, other comparisons, the UTF-8
case-insensitive variants (they fold per code point) and an index with a
postprocessor keep row-level evaluation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The occurrence check is served through the LIKE analysis with the
pattern '%needle%'. Two inputs made it drop granules holding matching
rows:

- The LIKE hint runs the index preprocessor over the whole pattern,
  including the `%` and escapes added for the needle. With
  replaceRegexpAll(message, '[^a-z ]', '') the `%` is stripped, so for
  position(message, 'p ab q') the partial tokens 'p' and 'q' became
  complete and the row 'xp ab qx' was pruned. Only the ASCII
  lower/upper preprocessor is accepted now, the rule ilike already has.
- A needle that is not valid UTF-8, such as the tail bytes of a CJK
  character, is tokenized by asciiCJK differently from the row, which
  holds the whole character. substringToTokens refuses such needles
  for the same reason.

The test is renumbered to 05257 to avoid a clash, and now also covers
both declines, the postprocessor decline, NOT (position = 0), NULL
rows under negation, a position and LIKE pair sharing one virtual
column, and a part written before the index was added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@valerypetrov
valerypetrov marked this pull request as ready for review September 24, 2026 19:25
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 24, 2026

@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.

Looks perfect, thank you!

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [00a064f]


AI Review

Summary

Adds opt-in text-index acceleration for occurrence comparisons using position, positionUTF8, countSubstrings, and their case-insensitive variants. The default-off use_text_index_for_substring_search setting addresses the previous large-dictionary performance blocker, whose thread is now resolved. No remaining blockers or majors.

PR Metadata

Performance Improvement is appropriate. The required changelog entry needs to mention the new opt-in setting.

Findings

💡 Nits

  • PR description, Changelog entry: “The text index is now used” implies automatic acceleration, but the new setting defaults to disabled. Suggested replacement: “Text indexes can now accelerate position(s, 'needle') > 0 and equivalent substring occurrence comparisons when use_text_index_for_substring_search = 1 (disabled by default).”
Missing context / blind spots
  • ⚠️ The broader CI suite for 00a064fc is still pending. The focused 02346_text_index_position regression passed in the current Fast test; broader validation remains with the normal CI jobs.
Final Verdict

Status: ✅ Approve

@alexey-milovidov alexey-milovidov self-assigned this Sep 24, 2026
@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... labels Sep 24, 2026
@rschu1ze rschu1ze added the hold Skip for auto-updating. label Sep 24, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@Ergus Could you please take this PR to your review list?

@rschu1ze rschu1ze assigned Ergus and unassigned alexey-milovidov Sep 24, 2026
@rschu1ze

Copy link
Copy Markdown
Member

@valerypetrov Thanks for this PR. Could I ask you toclean the PR message up? It ideally says clearly what this PR changes (+ avoid slop in all shapes and forms.)

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 81233be8e with master 2b066904b (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.

Compile time of recompiled translation units

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

Job report

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@valerypetrov Thanks for this PR. Could I ask you toclean the PR message up? It ideally says clearly what this PR changes (+ avoid slop in all shapes and forms.)

@rschu1ze , sure thing. It was pretty messy, I cleaned it up.

valerypetrov and others added 2 commits September 24, 2026 15:04
… LIKE lacks

positionCaseInsensitiveUTF8 and countSubstringsCaseInsensitiveUTF8 go through ILIKE too:
on a column no non-ASCII code point matches an ASCII letter in them (checked for every
code point), so for the needles the ILIKE path accepts they find exactly what its
dictionary scan finds.

The empty needle and postprocessor refusals are dropped because the LIKE path already
handles both correctly. The preprocessor and UTF-8 refusals stay: the LIKE hint path
preprocesses the whole pattern and mis-tokenizes a needle cut inside a character.

The test uses plain strings for the case-folding rows and explains what it checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds a sub-section and rows in the function table, and removes the paragraph from the
LIKE/ILIKE tuning section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR lets text-index analysis treat position/countSubstrings comparisons with a constant needle (such as > 0) as LIKE '%needle%', or ILIKE for the case-insensitive variants. That code only runs on tables that have a text index, and neither clickbench nor tpch_adapted_1_official has one. The only flagged row is clickbench Q33 at -5.0% (981 ms vs 1033 ms). It was correctly kept as no change: the PR median sits inside master's current range of 962–1202 ms, CPU time is nearly unchanged, and the query has a noisy history. No performance change is attributable to this PR on these benchmarks.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: aeae8057-4ba5-46a8-aac6-a5399b8a5a54
  • MIRAI run: d16a0a0b-3a63-4c7f-a57c-4af6a6d6f04e
  • PR check IDs:
    • clickbench_837901_1791700048
    • clickbench_837914_1791700048
    • clickbench_837920_1791700048
    • tpch_adapted_1_official_837926_1791700048
    • tpch_adapted_1_official_837958_1791700048
    • tpch_adapted_1_official_837972_1791700049

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 25, 2026
The exact direct read replaces the comparison with a UInt8 virtual column,
which turns the NULL of a NULL row into 0. When the same check is also used
outside the top-level filter, for example `x OR NOT x` or in the SELECT list,
the NULL row leaks into the result or shows 0 instead of NULL. Master does not
use the index for position() at all, so falling back for Nullable and
LowCardinality(Nullable) haystacks is never worse than master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say what `traverseSubstringOccurrenceNode` does, and why its preprocessor
and UTF-8 checks are not redundant with the `like` branch of
`traverseFunctionNode`. Mention in the docs that a `Nullable` column is
not served.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now passes the argument node to traverseFunctionNode and strips
lossless conversions from it; this branch passes the function name so
position() checks can reuse the LIKE path. Keep the name parameter and
take master's argument node and unwrapping.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…izers

`position` and `countSubstrings` search bytes. The `ngrams`, `sparseGrams` and `asciiCJK` tokenizers read a byte that starts a multi-byte UTF-8 character together with the bytes after it, even when those are ASCII. For a value such as `unhex('F0616C706861')` the index then holds no n-gram of `alpha`, so `position(s, 'alpha') > 0` lost the row with the index while a scan returned it.

The comparison is now served as `LIKE` only by the `splitByNonAlpha` and `array` tokenizers, whose tokens are plain byte ranges. The test with an absent map key moves from `ngrams(3)` to `splitByNonAlpha`, and a new case covers values that are not valid UTF-8 for the three other tokenizers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits November 15, 2026 16:52
Conflict in MergeTreeIndexConditionText.h: master added [[nodiscard]] to stringLikeToPatterns, the
branch added its ascii_case_folding argument. Both are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

valerypetrov and others added 2 commits November 23, 2026 10:25
The test for a needle that is not valid UTF-8 used the `asciiCJK`
tokenizer, which `traverseSubstringOccurrenceNode` now refuses before it
looks at the needle, so nothing exercised the UTF-8 check anymore.

The check is not redundant with the `like` branch of
`traverseFunctionNode`, which does not validate the pattern:
`SplitByNonAlphaTokenizer::nextInStringLike` reads a UTF-8 lead byte
together with the bytes after it, so `'%one two\xF0-x three four%'`
yields the token `two\xF0-x three`, which the matching row's index does
not hold, and the row is dropped. The case now uses `splitByNonAlpha`
and such a needle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 23, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Amazing change, as always!

@clickhouse-gh
clickhouse-gh Bot dismissed stale reviews from themself November 23, 2026 22:59

AI review of a later commit does not approve the PR, see the AI Review comment.

…ests

No performance test executed the comparisons that the text index now serves
as `LIKE '%needle%'`, so the change was only measured through the equivalent
`LIKE` queries.

Add `position`, `countSubstrings` and `positionCaseInsensitive` comparisons
to `text_index_like.xml` (a dictionary of about 20 tokens) and to
`text_index_like_large_dictionary.xml` (500008 tokens in each of 30 parts),
next to the `LIKE` queries on the same tables, so the comparison with master
covers both the small dictionary, where the index avoids the full scan, and
the large one, where the dictionary scan can cost more than the full scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov removed the hold Skip for auto-updating. label Nov 24, 2026
valerypetrov and others added 2 commits November 24, 2026 09:26
`position`, `countSubstrings` and their case-insensitive variants reject a
`FixedString` haystack, while the `LIKE` that the text index serves them as
accepts it. The exception comes from the 0-row header evaluation when the
filter step is built, before index analysis and the direct read rewrite,
so the query throws whether or not the index answers the comparison.

Pin that for `FixedString` and `LowCardinality(FixedString)` columns with
direct read enabled and disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 24, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 25, 2026 00:40

AI review of a later commit does not approve the PR, see the AI Review comment.

…for_substring_search`

Serving `position(s, 'x') > 0` as `s LIKE '%x%'` makes it pay the dictionary scan of that `LIKE`. With about one
distinct token per row the scan is slower than searching the column: the performance test with a large dictionary
measured `position` and `countSubstrings` about 3x slower and `positionCaseInsensitive` about 1.5x slower than
on master, and the existing cost check, which compares compressed bytes, still admits the scan there.

Add the setting `use_text_index_for_substring_search`, disabled by default, so these comparisons search the column
as before unless it is enabled. The small-dictionary performance test enables it to measure the gain, and the
large-dictionary one keeps the default to check that nothing regresses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants