Skip to content

Add splitByRegexp tokenizer for text indexes - #110002

Merged
Ergus merged 36 commits into
ClickHouse:masterfrom
Ergus:text_index_splitByRegexp
Aug 24, 2026
Merged

Ergus merged 36 commits into
ClickHouse:masterfrom
Ergus:text_index_splitByRegexp

Conversation

@Ergus

@Ergus Ergus commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Closes: #103783

The existing text-index tokenizers cannot preserve tokens that contain special
characters. For example, splitByNonAlpha tokenizes C++ as just c, so a
text index over a column of technology names (C++, C#, F#, ...) produces
false positives and there is no way to search for the original term: hasToken
rejects needles with separator characters, and searching for the stripped token
matches unrelated rows.

Usage:

    CREATE TABLE t (id UInt64, description String,
        INDEX idx description TYPE text(tokenizer = splitByRegexp('[^\p{L}\p{N}#+]+')))
    ENGINE = MergeTree ORDER BY id;

Changelog category (leave one):

  • New Feature

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

Added a splitByRegexp tokenizer for text indexes and the tokens function. It splits the input into tokens using a regular expression as the separator, for example tokenizer = splitByRegexp('[^\p{L}\p{N}#+]+'), which allows preserving tokens containing special characters such as C++ or C# that other tokenizers would break apart.


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

Version info

  • Merged into: 26.8.1.1967 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [016fee6]

Summary: ✅


AI Review

Summary

This PR adds a splitByRegexp tokenizer for text indexes and the tokens function, and extends hasPhrase to use it. The hasPhrase part is still not safe to merge: both correctness and the documented exception behavior still depend on whether the text-index rewrite runs, so the original C++ / C# false positives can still come back on fallback paths.

Findings
  • ❌ [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1186] Adding splitByRegexp to the supported hasPhrase tokenizers only fixes the path where optimizeDirectReadFromTextIndex injects the index tokenizer. When there is no usable skip-index condition (for example SETTINGS use_skip_indexes = 0), standalone FunctionHasPhrase still falls back to splitByNonAlpha, so hasPhrase(description, 'C# and') matches a row containing C++ and again. Suggested fix: make the non-index path pick up the text-index tokenizer too, or reject this mode when the rewrite is unavailable.
  • ❌ [src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:1203] [docs/reference/engines/table-engines/mergetree-family/textindexes.mdx:518] The new BAD_ARGUMENTS guard for splitByRegexp + postprocessor only fires when a usable text-index condition exists. If the planner skips that rewrite, the query silently falls back to standalone hasPhrase instead of throwing, while the docs still describe the result as read-path independent and splitByRegexp as fully supported without a postprocessor. Suggested fix: move the rejection to a place that runs even without a selected condition, or make the standalone path honor the same tokenizer/postprocessor contract and then narrow the docs to the real behavior.
Tests
  • ⚠️ The new stateless coverage only exercises the index-backed/direct-read path. Add a focused query with SETTINGS use_skip_indexes = 0 for both plain splitByRegexp phrase search and the splitByRegexp + postprocessor case; the current regression would not catch either blocker above.
Final Verdict

❌ Changes requested. The new splitByRegexp phrase-search semantics still depend on an optimization path, and the unsupported postprocessor combination is not rejected consistently.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 138/145 (95.17%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 10, 2026
Comment thread src/Interpreters/TokenizerFactory.cpp Resolved
Comment thread src/Functions/tokens.cpp Resolved
@Ergus
Ergus force-pushed the text_index_splitByRegexp branch from 93d8a8f to f4f34a1 Compare July 10, 2026 19:32
Comment thread src/Interpreters/ITokenizer.h Resolved
size_t & match_start,
size_t & match_length,
OptimizedRegularExpression::MatchVec & matches)
{

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.

Can we make this a lambda or helper function inside ITokenizer.cpp please?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is intentional because this function will be used by the splitByRegex sql function. I just didn't want to add that change here to not mix changes


DROP TABLE tab_regex_simple;

-- 2. Character class `[ ,;]`: split on a space, comma or semicolon.

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.

Can we convert to

SELECT '2. Character class `[ ,;]`: split on a space, comma or semicolon.'

so that the reference file becomes structured by section?

Comment thread src/Interpreters/ITokenizer.cpp Resolved
Comment thread src/Interpreters/ITokenizer.cpp Resolved
(
id UInt64,
description String,
INDEX idx description TYPE text(tokenizer = splitByRegexp('[^\\p{L}\\p{N}#+]+'), support_phrase_search = 1)

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.

The regression here only exercises the positional direct-read path. With support_phrase_search = 1 and a fully materialized index, hasPhrase is replaced by the virtual-column exact search, so this does not prove the default no-positions path that originally depended on injecting splitByRegexp(...) into the row-level hasPhrase call. Please add the same C# and / C++ and repro on a default support_phrase_search = 0 index (or split this into two sections) so the hint-mode path is covered as well.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 137/144 (95.14%) · Uncovered code

Full report · Diff report

@Ergus
Ergus requested a review from a team as a code owner August 3, 2026 14:09
For most functions (`=`, `IN`, `startsWith`, `endsWith`, `LIKE`, `mapContains*`), the text index is used only to skip irrelevant data blocks; ClickHouse still verifies each surviving row using the original predicate against the original column data.
For token search functions (`hasToken`, `hasAllTokens`, `hasAnyTokens`), the text index is the primary evaluation path: ClickHouse normalizes the needle through the same preprocessor, tokenizer, and postprocessor that were applied at index build time, and uses this normalized form for both indexed and non-indexed table parts. With a postprocessor, the haystack tokens are also normalized at query time (for any tokenizer, not only `array`), so both sides of the comparison are consistently transformed and the result does not depend on whether the index is read directly (setting `query_plan_direct_read_from_text_index`) or whether a given part has a materialized index — e.g. enabling case-insensitive matching for `hasAllTokens(col, ['FOO'])` with a `lower` postprocessor.
Without `support_phrase_search`, `hasPhrase` uses the index only as a hint and verifies each surviving row with the original predicate; a postprocessor additionally normalizes both the phrase and the haystack tokens the same way, so the result is independent of the read path, and tokens the postprocessor drops do not break phrase adjacency. With `support_phrase_search = 1`, `hasPhrase` uses exact direct reads (still applying the postprocessor, if any).
Without `support_phrase_search`, `hasPhrase` uses the index only as a hint and verifies each surviving row with the original predicate; a postprocessor additionally normalizes both the phrase and the haystack tokens the same way, so the result is independent of the read path, and tokens the postprocessor drops do not break phrase adjacency. With `support_phrase_search = 1`, `hasPhrase` uses exact direct reads (still applying the postprocessor, if any). This postprocessor support does not extend to the `splitByRegexp` tokenizer: `hasPhrase` on a `splitByRegexp` index combined with a postprocessor is rejected (see footnote ³ below).

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.

This compatibility note is still too narrow for the current implementation.

processTextIndexFunction still rewrites postprocessed hasPhrase inputs by arrayStringConcat(..., ' ') and then validates the resulting tokens with isTokenSeparator, so the same read-path divergence remains for other supported tokenizers whose tokens do not round-trip through that encoding. For example, splitByString(['::']) + postprocessor rewrites one::two::three to one two three, which false-negatives because re-tokenization no longer sees ::, and asciiCJK can still reject valid connector tokens like foo.bar or a:b.

Please either make the rewrite tokenizer-aware or narrow this prose/table to exclude every tokenizer whose hasPhrase + postprocessor path is still unsupported.

/// `+` (which the validation would reject). Rather than bypassing the index - which would silently fall
/// back to the default `splitByNonAlpha` and produce false positives - reject this combination
/// explicitly. `splitByRegexp` + `hasPhrase` without a postprocessor is fully supported.
if (tokenizer->getType() == ITokenizer::Type::SplitByRegexp && has_postprocessor)

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.

This rejection only runs when optimizeDirectReadFromTextIndex has a selected text-index condition. ReadFromMergeTree stops populating skip_indexes.useful_indices as soon as use_skip_indexes = 0 (src/Processors/QueryPlan/ReadFromMergeTree.cpp:2348-2353), and collectTextIndexReadInfos immediately bails out on an empty useful_indices set (src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:162-163). In that mode processTextIndexFunction never injects the table tokenizer or throws here, so hasPhrase(description, 'C# and') on a splitByRegexp('[^\\p{L}\\p{N}#+]+') index still falls back to default splitByNonAlpha semantics and can false-positive on ... C++ and ....

If this combination is intentionally unsupported, the check needs to live somewhere that is not gated on skip-index analysis. Otherwise the new docs/tests should scope the exception to the indexed path instead of promising an unconditional rejection.

Comment thread src/Functions/tokens.cpp Resolved
static const std::unordered_set<std::string_view> supported_tokenizers = {
SplitByNonAlphaTokenizer::getExternalName(),
SplitByStringTokenizer::getExternalName(),
SplitByRegexpTokenizer::getExternalName(),

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.

hasPhrase is only correct for splitByRegexp while the text-index rewrite is active. collectTextIndexReadInfos returns nothing as soon as there is no usable skip-index condition (for example SETTINGS use_skip_indexes = 0), so optimizeDirectReadFromTextIndex never injects the index tokenizer and standalone FunctionHasPhrase falls back to splitByNonAlpha. On a table with tokenizer = splitByRegexp('[^\\p{L}\\p{N}#+]+'), hasPhrase(description, 'C# and') SETTINGS use_skip_indexes = 0 still matches a row containing C++ and, which brings back the exact false positive this PR is trying to remove. Either the non-index path also needs to pick up the text-index tokenizer, or this support needs to be rejected when the rewrite is unavailable.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 016fee674 with master 400ba9d99 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.52 MiB 701.52 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

20 object files changed (+82.40 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasAnyAllTokens.cpp.o 908.30 KiB 939.45 KiB +31.15 KiB (+3.43%)
src/CMakeFiles/dbms.dir/Interpreters/ITokenizer.cpp.o 240.01 KiB 259.49 KiB +19.48 KiB (+8.12%)

737 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

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

Job report

@Ergus
Ergus added this pull request to the merge queue Aug 24, 2026
Merged via the queue into ClickHouse:master with commit a32804e Aug 24, 2026
178 checks passed
@Ergus
Ergus deleted the text_index_splitByRegexp branch August 24, 2026 00:41
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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.

Feature request: splitByRegexp tokenizer for text indexes

3 participants