Skip to content

Text index: Add ICU tokenizer - #109940

Merged
Ergus merged 34 commits into
ClickHouse:masterfrom
Ergus:tex_index_icu_tokenizer
Aug 3, 2026
Merged

Ergus merged 34 commits into
ClickHouse:masterfrom
Ergus:tex_index_icu_tokenizer

Conversation

@Ergus

@Ergus Ergus commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Add a new icu tokenizer for full-text search.

It uses the ICU library's word BreakIterator to perform locale-aware Unicode word segmentation, so, languages that do not separate words by whitespace (e.g. Chinese, Japanese, Thai) are split into meaningful words.

The locale is a mandatory parameter, e.g. tokenizer = icu('ja') in a text index, or tokens(s, 'icu', 'ja').

ICU is already a ClickHouse contrib, so no new dependency is added; the tokenizer is only registered when built with ICU.

Changelog category (leave one):

  • New Feature

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

Added a new icu tokenizer for text indexes and the tokens, hasAnyTokens, and hasAllTokens functions, providing locale-aware Unicode word segmentation (including dictionary-based segmentation for languages such as Chinese, Japanese, and Thai).

Version info

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

@Ergus
Ergus marked this pull request as draft July 9, 2026 21:22
@Ergus Ergus added the can be tested Allows running workflows for external contributors label Jul 9, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jul 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5a013e3]

Summary: ✅


AI Review

Summary

This PR adds an icu tokenizer to text indexes and the token-search surface, and the core tokenizer implementation, docs, and no-ICU gating are mostly consistent. One major correctness gap remains: the newly advertised explicit hasPhrase(..., 'icu(''ja'')') form on indexed columns still bypasses the text-index rewrite path, so it can diverge from the 2-argument form whenever the index relies on positions, a preprocessor, or a postprocessor.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp:538, src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:639, tests/queries/0_stateless/02346_text_index_icu_tokenizer.sql:85] The PR now accepts and tests an explicit icu tokenizer argument for hasPhrase, but indexed hasPhrase predicates are still only rewritten/analyzed when they have exactly 2 arguments. hasPhrase(col, phrase, 'icu(''ja'')') therefore skips tokenizer/preprocessor/postprocessor injection and never reaches positional direct-read, even on a column indexed as tokenizer = icu('ja'). The added coverage only exercises a no-normalization case, so it misses the real divergence: on an index with lowerUTF8, stemming, stop-word filtering, or support_phrase_search = 1, the explicit icu form can return different results from hasPhrase(col, phrase) on the same indexed column. Either route the 3-argument form through the same rewrite/index path, or reject/document it for indexed columns.
Final Verdict

Needs changes before merge: the explicit hasPhrase + icu form is now part of the tested surface, but it still bypasses indexed-column normalization and direct-read semantics.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 9, 2026
Comment thread src/Interpreters/ITokenizer.h Resolved
Comment thread src/Interpreters/ITokenizer.cpp Resolved
Comment thread src/Functions/tokens.cpp Resolved
Comment thread src/Functions/hasPhrase.cpp Resolved
@Ergus Ergus changed the title Tex index icu tokenizer Text index icu tokenizer Jul 10, 2026
Comment thread src/Functions/hasAnyAllTokens.cpp Resolved
@Ergus
Ergus force-pushed the tex_index_icu_tokenizer branch from c0d84df to 01df3c6 Compare July 10, 2026 19:12
@Ergus
Ergus marked this pull request as ready for review July 10, 2026 19:26
ITokenizer::Type::SplitByNonAlpha,
ITokenizer::Type::SplitByString,
ITokenizer::Type::AsciiCJK,
ITokenizer::Type::Icu,

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.

Icu is accepted by the row-level evaluator now, but the text-index path still only recognizes 2-argument predicates: MergeTreeIndexConditionText::traverseAtomNode returns false as soon as function_arguments_size != 2, and TextIndexDAGReplacer::processTextIndexFunction still bails out unless children.size() == 2. As a result, hasPhrase(col, phrase, 'icu(''ja'')') on an indexed column never gets positional direct-read or the index's preprocessor / postprocessor normalization, so it can disagree with hasPhrase(col, phrase) as soon as the text index normalizes tokens. Please either route the explicit ICU form through the same text-index path as the inferred form, or reject/document it for indexed columns.

Comment thread src/Functions/tokens.cpp
tokens(value, 'ngrams'[, n])
tokens(value, 'sparseGrams'[, min_length, max_length[, min_cutoff_length]])
tokens(value, 'array')
)";
FunctionDocumentation::Arguments arguments = {
{"value", "The input string.", {"String", "FixedString"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `icu`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},
{"locale", "Only relevant if argument `tokenizer` is `icu`: The mandatory locale, for example `'ja'`.", {"const String"}},

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.

Btw., is there a good argument against making the locale argument optional and en the default locale?

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.

IIUC in some cases the the same characters segment differently under different locale (zh vs ja). So a default could give an inappropriate split for exactly the text that needs icu, and the user might not notice.

For plain space-separated Latin text the locale barely matters, but I won't expect anyone using ICU for it (splitByNonAlpha/asciiCJK already suffice).

Making it explicit is a tiny one-time cost that forces the correct choice, so I'd lean toward keeping it mandatory.

auto it = iterators.find(locale);
if (it == iterators.end())
{
if (iterators.size() >= max_cached_iterators)

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.

Let's add your reply as a comment to iterators.clear().

UErrorCode status = U_ZERO_ERROR;
UBreakIteratorPtr iterator(ubrk_open(UBRK_WORD, locale.c_str(), nullptr, 0, &status), &ubrk_close);

if (U_FAILURE(status))

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 locale contract is not actually enforced here. ICU reports unknown / unsupported locales through warning statuses such as U_USING_DEFAULT_WARNING / U_USING_FALLBACK_WARNING, and U_FAILURE(status) ignores those, so a typo like icu('zz') silently builds an iterator that tokenizes with ICU's fallback locale instead of raising BAD_ARGUMENTS.

That turns a misspelled index definition or function call into wrong tokenization and wrong search results with no user-visible error. This path needs explicit locale validation instead of treating every non-failure ICU status as success.

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.

Good catch but the suggested remedy doesn't work for word break iterators. ICU's word-break rules exist essentially only at root (brkitr/root.txt), so opening a UBRK_WORD iterator for almost any locale falls back to root and returns exactly U_USING_DEFAULT_WARNING/U_USING_FALLBACK_WARNING. Treating those as failure would reject legitimate locales, not just typos.

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.

Also, the practical impact is small here: word segmentation is driven by the script, not the locale, so a misspelled locale falls back to essentially the same tokenization rather than silently-wrong results.

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.

Thinking a bit more on this, if we do want to reject typos, it has to be an explicit locale-availability check and whether to do that is tied to the open question of whether the locale should stay mandatory or get a default.

We can add an availability check if we decide, but I don't think keying off the ICU status is correct.

Comment thread src/Functions/hasAnyAllTokens.cpp Outdated
{"input", "The input column.", {"String", "FixedString", "Nullable(String)", "Nullable(FixedString)", "Array(String)", "Array(FixedString)", "Array(Nullable(String))", "Array(Nullable(FixedString))"}},
{"needles", "Tokens to be searched.", {"String", "Array(String)"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `splitByString`, `asciiCJK`, `icu('<locale>')`, `ngrams`, `sparseGrams`, and `array`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},

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.

These new explicit ICU forms are only equivalent on the brute-force path. On indexed columns the text-index side still only recognizes 2-argument predicates: MergeTreeIndexConditionText::traverseAtomNode returns false as soon as function_arguments_size != 2, and TextIndexDAGReplacer::processTextIndexFunction bails out unless children.size() == 2.

As a result, hasAnyTokens(col, '日本語', 'icu(''ja'')') / hasAllTokens(...) never get the index tokenizer, preprocessor, postprocessor, or direct-read handling. A text index with lowerUTF8, stemming, or stop-word postprocessing can therefore return different results between the explicit ICU form and the inferred 2-argument form on the same indexed column. Please either route the 3-argument form through the same text-index path, or reject/document it for indexed columns.

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 pre-existing and tokenizer-agnostic. Passing any explicit tokenizer as the 3rd argument to has*Token bypasses the index the same way, and only diverges from the inferred form when the index has a preprocessor/postprocessor. The docs already note this.

This exact area was reviewed earlier in this PR (the separate-argument form was dropped precisely so icu behaves like the others here).

Comment thread src/Interpreters/TokenizerFactory.cpp Resolved
Comment thread src/Interpreters/ITokenizer.h Resolved
Comment thread src/Interpreters/ITokenizer.cpp Resolved
@Ergus
Ergus requested a review from a team as a code owner July 31, 2026 21:25
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 139/155 (89.68%) · Uncovered code

Full report · Diff report

@Ergus
Ergus added this pull request to the merge queue Aug 3, 2026
Merged via the queue into ClickHouse:master with commit 485b16d Aug 3, 2026
351 of 352 checks passed
@Ergus
Ergus deleted the tex_index_icu_tokenizer branch August 3, 2026 10:06
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 3, 2026
@Ergus Ergus mentioned this pull request Aug 3, 2026
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 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.

3 participants