Skip to content

Add unicode_word tokenizer - #99357

Merged
Ergus merged 2 commits into
ClickHouse:masterfrom
amosbird:unicode-word-tokenizer
Mar 17, 2026
Merged

Ergus merged 2 commits into
ClickHouse:masterfrom
amosbird:unicode-word-tokenizer

Conversation

@amosbird

@amosbird amosbird commented Mar 13, 2026 •

Copy link
Copy Markdown
Collaborator

Add a new unicode_word tokenizer that splits text using Unicode word boundary rules similar to UAX #29.

Tokenization rules:

  • ASCII alphanumeric characters and underscores form tokens (underscore alone is not a valid token)
  • Connectors: : connects letters only; . and ' connect same-type characters (letter-letter or digit-digit)
  • Non-ASCII Unicode characters become single-character tokens
  • Stop words (configurable, defaults to common CJK punctuation) are filtered out

The tokenizer is registered in TokenizerFactory and automatically available for text() indexes and the tokens/tokensForLikePattern functions. It supports LIKE pattern matching via nextInStringLike.

This is the third and final PR split from #90268, following:

Changelog category (leave one):

  • New Feature

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

Add unicode_word tokenizer for full-text indexes and the tokens function. It splits text using Unicode word boundary rules: ASCII words are formed with connector characters (underscore, colon, dot, single quote), while non-ASCII Unicode characters become single-character tokens. Configurable stop words default to common CJK punctuation.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Adds a new tokenizer used by full-text indexes and tokens/tokensForLikePattern, which can change query results and index behavior for users who opt into it; the LIKE-pattern parsing and UTF-8 handling paths increase surface area for edge-case bugs.

Overview
Adds a new unicode_word tokenizer for text indexes and the tokens/tokensForLikePattern functions, providing Unicode-aware tokenization with ASCII connector rules and single-character non-ASCII tokens.

The tokenizer is registered in TokenizerFactory with configurable stop_words (defaulting to common CJK punctuation), wired into forEachToken dispatch, and exposed via updated docs and system.tokenizers output.

Extends function argument validation/docs for tokens(...) to accept unicode_word and its optional stop_words, and adds stateless tests covering tokenization, LIKE-pattern behavior, and text-index LIKE selectivity with the new tokenizer.

Written by Cursor Bugbot for commit 507d206. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.755

@clickhouse-gh

clickhouse-gh Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [17a6953]

Summary: ✅


AI Review

Summary

This PR adds a new unicode_word tokenizer and wires it into TokenizerFactory, tokens, tokensForLikePattern, docs, and stateless tests. The implementation direction is reasonable, but there are two concrete issues that should be addressed before merge: a compile-time regression risk from a heavy header include in ITokenizer.h, and a test comment/behavior mismatch around escaped % in LIKE-pattern tokenization.

Missing context

  • ⚠️ No CI results/logs were provided in this review context, so runtime/performance validation could not be independently confirmed.

Findings

❌ Blockers

  • [src/Interpreters/ITokenizer.h:11] Adding absl/container/flat_hash_set.h to a broadly included interface header increases transitive compile cost and violates compilation-time constraints for high-fan-out headers.
    • Suggested fix: keep heavy containers out of ITokenizer.h (for example, move stop-word storage behind a pimpl or store stop words in an implementation-owned structure in .cpp), or switch to a lighter dependency profile that avoids this include in the public header.

⚠️ Majors

  • [tests/queries/0_stateless/04038_unicode_word_tokenizer.sql:30] The inline comment says escaped % is included as a normal character, but expected output shows a\%b is tokenized as ['a','b'].
    • Suggested fix: update the comment to match behavior, or adjust tokenizer behavior and expected results so code/tests/comments are consistent.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅ Feature is opt-in via explicit tokenizer selection (unicode_word).
No magic constants ✅
Backward compatibility ✅
SettingsHistory.cpp ➖
Safe rollout ✅
Compilation time ❌ absl/container/flat_hash_set.h added to ITokenizer.h.

Performance & Safety

  • The new public-header dependency (absl/container/flat_hash_set.h) is the primary performance concern because it can increase build times across many translation units.

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Remove heavy absl dependency from ITokenizer.h transitive includes.
    • Fix the escaped-% test comment/behavior mismatch so the test intent is unambiguous.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 13, 2026
@amosbird
amosbird force-pushed the unicode-word-tokenizer branch from 8b2a82c to 552c527 Compare March 13, 2026 01:05
select tokensForLikePattern('%abc', 'unicode_word'); -- wildcard before token
select tokensForLikePattern('abc%', 'unicode_word'); -- token before wildcard
select tokensForLikePattern('a_b%c_d', 'unicode_word'); -- wildcard in between
select tokensForLikePattern('a\%b a\_c', 'unicode_word'); -- escaped % and _ included as normal chars

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 inline comment says escaped % and _ are included as normal characters, but the expected output below shows escaped % is treated as a separator (a\%b becomes ["a","b"]). Please either update the comment text or adjust behavior/tests so they match.

@amosbird
amosbird force-pushed the unicode-word-tokenizer branch from 552c527 to ad181f0 Compare March 13, 2026 01:07
Comment thread src/Interpreters/ITokenizer.h Resolved
Add a new unicode_word tokenizer that splits text using Unicode word
boundary rules similar to UAX ClickHouse#29. ASCII alphanumeric characters form
tokens with connectors (underscore, colon, dot, single quote), while
non-ASCII Unicode characters become single-character tokens. Stop words
(configurable, defaults to common CJK punctuation) are filtered out.

The tokenizer is registered in TokenizerFactory and automatically
available for text() indexes and the tokens()/tokensForLikePattern()
functions. It supports LIKE pattern matching via nextInStringLike().

This is the third and final PR split from ClickHouse#90268.
@amosbird
amosbird force-pushed the unicode-word-tokenizer branch from ad181f0 to 507d206 Compare March 13, 2026 02:47

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

if ((token_start > 0 || is_prefix) && (token_start + token_len < length || is_suffix))
tokens.push_back({data + token_start, token_len});
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicated substring methods belong in base template

Low Severity

The substringToBloomFilter and substringToTokens implementations in UnicodeWordTokenizer are exact duplicates of the same methods in SplitByNonAlphaTokenizer. Both iterate tokens via nextInString and apply the same first-token/last-token prefix/suffix filtering logic. This identical logic could be provided as a default in the ITokenizerHelper base class template (alongside the existing stringToBloomFilter and stringToTokens defaults), eliminating the duplication and ensuring the filtering logic stays consistent if it ever changes.

Additional Locations (1)
Fix in Cursor Fix in Web

@Ergus Ergus self-assigned this Mar 13, 2026

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

Hi @amosbird

Very thanks for this contribution. It looks good, but:

  1. I added two comments to check in nextInStringLike. Just to be safe.
  2. I suggested a little test cases to add for improvement.
  3. It worth comparing performance with SplitByNonAlpha if possible

Only 1 needs your full confirmation or solution from your side in order to approve this.

Comment thread src/Interpreters/ITokenizer.cpp Resolved
Comment thread src/Interpreters/ITokenizer.cpp Resolved
Comment thread src/Interpreters/ITokenizer.cpp Resolved
…, add tests

- Fix pos overflow for truncated UTF-8 in nextInStringLike
- Fix escaped-state leak after stop word continue in nextInStringLike
- Deduplicate substringToBloomFilter/substringToTokens via shared template helpers
- Add edge case tests: empty string, dot as stop word, wrong argument type,
  stop word with escaped char in LIKE pattern
- Add unicode_word tokenizer to performance benchmark
@Ergus Ergus added the can be tested Allows running workflows for external contributors label Mar 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.70% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.20% 76.30% +0.10%

PR changed lines: PR changed-lines coverage: 92.31% (288/312, 0 noise lines excluded)
Diff coverage report
Uncovered code

@Ergus
Ergus added this pull request to the merge queue Mar 17, 2026
Merged via the queue into ClickHouse:master with commit 3a36431 Mar 17, 2026
410 of 475 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 17, 2026
Compared to `ngrams(N)`, the `sparseGrams` tokenizer produces variable-length N-grams, allowing for a more flexible representation of the original text.
For example, `tokenizer = sparseGrams(3, 5, 4)` internally generates 3-, 4-, 5-grams from the input string but only the 4- and 5-grams are returned.
- `array` performs no tokenization, i.e. every row value is a token (see function [array](/sql-reference/functions/array-functions.md/#array)).
- `unicode_word` splits strings into tokens using Unicode word boundary rules (similar to UAX #29). ASCII alphanumeric characters and underscores form tokens with connectors (`:` for letters, `.` and `'` for same-type characters). Non-ASCII Unicode characters become single-character tokens. Stop words (configurable, defaults to common CJK punctuation) are skipped. An optional parameter `stop_words` can be specified as an array of strings, for example, `tokenizer = unicode_word([',', '。'])`.

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.

unicode_word --> unicodeWord please for naming consistency with other tokenizers

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.

UAX #29 ... this is too cryptic and readers are unable to decipher that. Please add a link to a blog post or an article or something similar + a link to the Unicode spec.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Renamed to unicodeWord. #99837

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added link to UAX #29. #99837

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added CJK link. #99837

Compared to `ngrams(N)`, the `sparseGrams` tokenizer produces variable-length N-grams, allowing for a more flexible representation of the original text.
For example, `tokenizer = sparseGrams(3, 5, 4)` internally generates 3-, 4-, 5-grams from the input string but only the 4- and 5-grams are returned.
- `array` performs no tokenization, i.e. every row value is a token (see function [array](/sql-reference/functions/array-functions.md/#array)).
- `unicode_word` splits strings into tokens using Unicode word boundary rules (similar to UAX #29). ASCII alphanumeric characters and underscores form tokens with connectors (`:` for letters, `.` and `'` for same-type characters). Non-ASCII Unicode characters become single-character tokens. Stop words (configurable, defaults to common CJK punctuation) are skipped. An optional parameter `stop_words` can be specified as an array of strings, for example, `tokenizer = unicode_word([',', '。'])`.

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.

"Stopword" is technically correct but also a weird term when used exclusively for interpunctation symbols, e.g. .. Please change Stop words (configurable, default [...] to

An optional parameter (for example, `tokenizer = unicodeWord([', ', '。'])`) specifies character sequences that are ignored, i.e. stopwords. The default skipped characters are: < ... >

Please document in < ... > what characters exactly are skipped by default.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Rewrote as suggested: parameter-first description with all 11 default skipped characters listed explicitly. #99837

Comment thread src/Functions/tokens.cpp
FunctionDocumentation::Arguments arguments = {
{"value", "The input string.", {"String", "FixedString"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `ngrams`, `splitByString`, `array`, and `sparseGrams`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"const String"}},
{"tokenizer", "The tokenizer to use. Valid arguments are `splitByNonAlpha`, `ngrams`, `splitByString`, `array`, `sparseGrams`, and `unicode_word`. Optional, if not set explicitly, defaults to `splitByNonAlpha`.", {"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.

Minor: Please apply the same change in src/Functions/hasAnyAllTokens.cpp.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added unicodeWord to both doc strings. #99837

{
}

static const char * getName() { return "unicode_word"; }

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.

unicodeWord

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done. #99837

///
/// 4. Token Validity
///
/// * Tokens must contain at least **one ASCII letter or digit** to be valid.

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.

In l. 383, we say that each Chinese character forms a single-character token.
In l. 388, we say that all tokens must contain an ASCII letter or digit.

This is a contradiction.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Split into: ASCII tokens need at least one letter/digit; non-ASCII Unicode characters are valid on their own. #99837

///
/// 2. Connectors
///
/// * `:` connects **letters only**, not digits.

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.

For my understanding, do we mean Westerm : here or CJK :?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Clarified as "ASCII : (U+003A)". #99837

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.

Please also add a handful of tests to 03403_function_tokens.sql

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.

And 02346_text_index_creation.sql needs adjustment as well.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added 7 test cases. #99837

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added 3 CREATE TABLE tests. #99837

zlareb1 added a commit to zlareb1/ClickHouse that referenced this pull request Mar 18, 2026
…ickHouse#99357)

Covers two gaps in PR ClickHouse#99357:
1. hasToken and equality predicates via MergeTreeIndexConditionText with the
   unicode_word tokenizer — neither code path had stateless test coverage.
2. Empty stop_words array (unicode_word([])) — exercises the zero-stop-words
   branch in TokenizerFactory, verifying CJK punctuation (e.g. ',') is
   indexed as a token and found via hasToken.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
george-larionov pushed a commit to amosbird/ClickHouse that referenced this pull request Mar 20, 2026
Follow-up to PR ClickHouse#99357 addressing post-merge review comments:
- Rename `unicode_word` to `unicodeWord` for naming consistency with other tokenizers
- Add link to Unicode Text Segmentation (UAX ClickHouse#29) spec in docs
- Add link to CJK Wikipedia article in docs
- Rewrite stop words documentation with explicit default character list
- Add `unicodeWord` to valid tokenizer lists in `hasAnyTokens`/`hasAllTokens` docs
- Clarify comments: ASCII-only connectors, CJK as single-char tokens, split validity rules
- Add `unicodeWord` tests to 03403_function_tokens and 02346_text_index_creation
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.

4 participants