Skip to content

Add hasAnyTokenLike and hasAllTokenLike functions with text index support - #121831

Open
valerypetrov wants to merge 83 commits into
ClickHouse:masterfrom
valerypetrov:text-index-per-token-predicates
Open

valerypetrov wants to merge 83 commits into
ClickHouse:masterfrom
valerypetrov:text-index-per-token-predicates

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Related: #121650

Adds two functions that check each token (word) of a string against LIKE patterns: hasAnyTokenLike finds a token that matches one of the patterns, and hasAllTokenLike finds tokens that match every one of several patterns. With a text index on the column, they look up the matching tokens in the index instead of splitting every row into tokens.

SELECT count() FROM logs WHERE hasAnyTokenLike(Body, 'charg%');

On master the same check is arrayExists(t -> startsWith(t, 'charg'), tokens(Body)), which cannot use the index. On 3 million log-like rows (the table of the performance test, max_threads = 4, query condition cache off, median of 9 runs on this PR's CI build), hasAnyTokenLike(message, 'charg%') took 1 ms and the arrayExists form took 69 ms, both returning 300. Patterns that match too many tokens fall back to checking every row.

hasAnyTokenRegexp moves to a follow-up PR; hasAnyTokenPrefix is dropped because hasAnyTokenLike(s, 'abc%') covers it.

Changelog category (leave one):

  • New Feature

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

Add functions hasAnyTokenLike and hasAllTokenLike, which check the tokens of a string against LIKE patterns and can use the text index.

🤖 Generated with Claude Code


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

valerypetrov and others added 4 commits September 23, 2026 11:48
They check whether any token of the input starts with a prefix, matches a
`LIKE` pattern or matches a regular expression. The text index finds the
matching dictionary tokens and reads their posting lists; since the pattern
is applied per token, the result is exact and eligible for direct read.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Stateless tests for the semantics without an index and for the text index
path (pruning, direct read, tokenizer mismatch, fallback on too many
postings, `Nullable` and `Array(String)` columns, preprocessor), and a
performance test against the `arrayExists(tokens(...))` formulation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The dictionary scan of a pattern (`LIKE`, `ILIKE`, `startsWith`, `endsWith`,
`hasTokenPrefix`, `hasTokenLike`, `hasTokenMatch`) is abandoned when the pattern
matches more tokens than this, and the predicate is evaluated on the column.
`text_index_like_max_postings_to_read` counts only large postings, so a pattern
matching a million rare tokens collected all of them and was 50 times slower than
the column scan. The default 20000 is the measured break-even on 10 million rows.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…enLike` and `hasTokenMatch`

As for `hasAnyTokens`, the functions without the tokenizer argument use the
tokenizer of the text index. `hasTokenPrefix` applies the `lower` or `upper`
preprocessor of the index to the input and the prefix. A pattern cannot be
preprocessed, so `hasTokenLike` and `hasTokenMatch` do not use an index with a
preprocessor.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@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 23, 2026
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e72f14]

Summary: ❌

job_name test_name status info comment
Style check FAIL
cpp FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 23, 2026
… `hasTokenMatch`

Move the `lowerUTF8` preprocessor case into its own `no-fasttest` test,
because the Fast test build has no ICU and fails with `UNKNOWN_FUNCTION`.

Link the new functions and the `text_index_like_max_matched_tokens` setting to
their reference pages without anchors: the anchors only appear once the
reference docs are regenerated, so the internal links check rejected them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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 ⚠️

15 object files changed (+573.22 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasAnyAllTokenPatterns.cpp.o new 461.69 KiB +461.69 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexConditionText.cpp.o 1.07 MiB 1.11 MiB +44.74 KiB (+4.09%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp.o 546.42 KiB 574.23 KiB +27.81 KiB (+5.09%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexText.cpp.o 900.54 KiB 920.34 KiB +19.80 KiB (+2.20%)

711 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

38 translation units recompiled, 489 s compile time in total, 37 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Functions/hasAnyAllTokenPatterns.cpp: 5.6 s

Job report

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 24, 2026
valerypetrov and others added 2 commits September 23, 2026 21:16
…h` depend only on the index definition

The functions were rewritten with the index tokenizer and preprocessor only if
the index could serve them, so e.g. `use_text_index_like_evaluation_by_dictionary_scan = 0`,
an empty needle, or an index with a preprocessor made `hasTokenPrefix` on an
`array` index fall back to `splitByNonAlpha` and return other rows.

Now the index condition always returns a query for them when the column has the
index, one without patterns if the index cannot be used, which only carries the
rewrite. The `lower`/`upper` preprocessor of `hasTokenPrefix` is applied whenever
the index is defined, not only when the index is used. The functions no longer
take the tokenizer from an index that is analyzed for another function (e.g.
`mapKeys(m)` for `m['key']`), and do not use the index for map elements or JSON
paths. Add the functions to the support matrix in the documentation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…okenMatch`

Check that the results do not depend on settings on `array`, `lower`, `lowerUTF8`
and `Nullable` indexes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Ergus

Ergus commented Sep 24, 2026

Copy link
Copy Markdown
Member

Hi @valerypetrov

Very thanks for contributing. Do you prefer me to fix the conflicts and push directly in your branch or you prefer doing it yourself?

@valerypetrov

valerypetrov commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @valerypetrov

Very thanks for contributing. Do you prefer me to fix the conflicts and push directly in your branch or you prefer doing it yourself?

Hey @Ergus , let me try to do that today. If I’m unlucky, please do that for me.

valerypetrov and others added 2 commits September 24, 2026 09:09
One conflict, in SettingsChangesHistory.cpp: master and this branch each added
a row at the top of the 26.10 block. Both are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h` with a running offset

Same `current_offset` loop as `hasAnyAllTokens`, instead of relying on the zeroed
element before the offsets for the first row. The new cases evaluate full array
columns, not constants, whose first row matches, for String, Nullable(String) and
FixedString elements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two text indexes can serve the same expression although a column may
have only one: an index on `if(s != '', s, 'none')` is matched through
its normalized name `if(notEmpty(s), s, 'none')`, which another index
can have literally. Both conditions were then selected, the tokenizer
and preprocessor rewrite of `hasTokenPrefix`, `hasTokenLike` and
`hasTokenMatch` was skipped, and each index still pruned granules with
its own tokenizer, so the result changed with `use_skip_indexes` and
direct read.

Now every text index analyzed for such a function must give it the same
tokenizer and the same applied preprocessor (only `lower` or `upper`,
and only for `hasTokenPrefix`). If they agree, the index with the first
name serves the function, so the rewrite always happens and the choice
does not depend on hash order. If they disagree, the function throws
BAD_ARGUMENTS in the rewrite pass, which covers the filter and the
SELECT list whether or not an index is used. An explicit tokenizer
argument leaves only the indexes with that tokenizer. The selection for
other text-search functions is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved

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

Some comments about the tests:

  • Text index tests go under 02346
  • For a feature like this we need some more tests.
    i.e:
    • Postprocessor -> rewrite_only: No test uses a postprocessor index. Try INDEX idx(msg) TYPE text(tokenizer = splitByNonAlpha, postprocessor = lower(msg)) + hasTokenPrefix(msg, 'Charg') with the index on and with use_skip_indexes = 0.
    • Map element / JSON path: The !candidate_for_exact_mode exit and the mapKeys-served early return are untested. Try m Map(String, String), INDEX ik(mapKeys(m)) TYPE text(tokenizer = array), then hasTokenPrefix(m['k'], 'pro') with the index on and off.
    • LowCardinality(String) indexed column, where direct read is allowed.
    • Tokenizers other than splitByNonAlpha and array on the index side. The new path does not restrict the tokenizer, which could conlict with ngrams or sparseGrams.

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

I think we discussed in the internal meeting today that we rather wanted functions hasAnyTokenLike and hasAnyTokenPrefix. hasAnyTokenRegexp is questionable and better to be avoided because it cannot be efficiently evaluated (it needs a full dictionary scan).

@Ergus Ergus self-assigned this Nov 3, 2026
The previous master merge did not compile: master now passes the map subcolumn
shadowing check as a callable `is_column_shadowing_map_subcolumn`. Master's embedded
postings fix in `QueryBuilder::addTokenInfo` now passes the token to this branch's
`addPostings`, which skips a token whose postings it already has. Master's dictionary
DFA cursors are kept next to this branch's per-analyzer pattern copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rschu1ze
rschu1ze removed their request for review November 6, 2026 20:50
valerypetrov and others added 2 commits November 6, 2026 15:17
…ictionaries

The new functions built their TextSearchQuery without the shared automaton budget, so every
partition condition compiled its own DFAs with no total limit. They now pass the budget like LIKE does.

The whole-dictionary bailout also fired when a DFA could seek, so a selective prefix pattern such
as 'target_%' over a large dictionary fell back to reading every granule. The bailout now applies
only without a DFA; the matched-token cap still bounds the seek path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits November 10, 2026 13:50
Master changed `traverseMapElementValueNode` to take the function node
and check the map value default; keep that signature next to this
branch's `hasIndexForMapElementSubcolumn`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With bucketed map serialization `optimize_functions_to_subcolumns` reads `m[1]` as the subcolumn `m.key_k` when the key is `Enum8('k' = 1)`, since the subcolumn is named by the Enum name. The index on `m[1]` was looked up by guessing the key literal from the subcolumn suffix, which never gives `1` for `k`. `hasAnyTokenLike` and `hasAllTokenLike` then took the default tokenizer instead of the index tokenizer, so the setting changed their results, also with skip indexes disabled.

The index now computes the subcolumn name of its own `m['key']` expression from the map key type, the same way the subcolumn pass does, and matches that name exactly. The subcolumn tests now use bucketed map serialization, without which the rewrite never happens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…so before the subcolumn rewrite

With `optimize_functions_to_subcolumns = 0` the per-token pattern functions matched the index only by
the expression name, so `m['k']` missed an index on `m[1]` (and the other way round) for a map with the
key `Enum8('k' = 1)`, and took the default tokenizer instead of the index's. The setting then changed
the result. Both the index and the query element now go through the same key normalization as the
subcolumn name.

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

Building the subcolumn name inserts the key into a FixedString column, which pads a short key with
NUL bytes. `arrayElement` compares the key unpadded, so m['k'] and m['k\0\0'] are different elements,
but both got the same subcolumn name. The index on one was then used for the other and indexed queries
lost or added rows. A key that needs padding now gets no subcolumn name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 3 commits November 15, 2026 16:15
…n-predicates

Conflict in optimizeDirectReadFromTextIndex.cpp: master switched selectConditions to
VectorWithMemoryTracking, the branch added choosePerTokenPatternFunctionIndex right above it.
Both are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ap key

Building the subcolumn name inserts the key into a FixedString column, which pads a short key with
NUL bytes. arrayElement compares the key unpadded, so with bucketed maps m['k'] returned the value
of the key 'k\0\0' when optimize_functions_to_subcolumns was on and nothing when it was off.
hasAnyTokenLike and hasAllTokenLike over such an element changed their result with the setting.
A key that needs padding is no longer rewritten to a subcolumn.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…n-predicates

Conflict in MergeTreeIndexConditionText.h: master added [[nodiscard]] to the const methods, the
branch added isPerTokenPatternFunction and a comment next to them. Both are kept, and the const
methods the branch adds get [[nodiscard]] too, as modernize-use-nodiscard is enabled now.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
/// The per-token pattern functions take the tokenizer of the index on their input, so they must find an index on `m['key']`
/// also after `optimize_functions_to_subcolumns` makes `m.key_<key>` of it. Otherwise that setting changes their result.
if (!has_index_column && isPerTokenPatternFunction(function_name))
has_index_column = hasIndexForMapElementSubcolumn(index_column_node);

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.

[Blocker] Match indexes declared on subcolumns before choosing the tokenizer.

The additional matching only handles indexes defined as map lookups. An index declared directly on m.key_k gets no map_element_subcolumn_name, because the helper in MergeTreeIndexText.cpp accepts only an arrayElement index expression. Consequently, the equivalent query operand m['k'] finds the index only after subcolumn optimization. The same query then uses splitByNonAlpha with the optimizer disabled and array with it enabled, changing results even when skip indexes are disabled.

Reproduced with this head's Fast test binary:

CREATE TABLE t
(
    id UInt8,
    m Map(String, String),
    INDEX idx(m.key_k) TYPE text(tokenizer = array)
)
ENGINE = MergeTree ORDER BY id
SETTINGS map_serialization_version = 'with_buckets',
         map_serialization_version_for_zero_level_parts = 'with_buckets';
INSERT INTO t VALUES (1, {'k': 'env:prod-eu'});

SELECT count() FROM t WHERE hasAnyTokenLike(m['k'], 'prod%')
SETTINGS optimize_functions_to_subcolumns = 0, use_skip_indexes = 0;
-- 1
SELECT count() FROM t WHERE hasAnyTokenLike(m['k'], 'prod%')
SETTINGS optimize_functions_to_subcolumns = 1, use_skip_indexes = 0;
-- 0

hasAllTokenLike(m['k'], ['env:prod%']) likewise changes from 0 to 1; both discrepancies also occur with skip indexes enabled.

The same gap affects tuple subcolumns: with m Tuple(k String), INDEX idx(m.k) TYPE text(tokenizer = array), and the value tuple('env:prod-eu'), the two functions on tupleElement(m, 'k') exhibit exactly the same changes. That path has no matching normalization here either.

Please canonicalize both index definitions and query operands to the same subcolumn identity, including map and tuple subcolumns, and add regression coverage for both functions with subcolumn optimization enabled/disabled.

valerypetrov and others added 3 commits November 15, 2026 22:17
…unction

hasAnyTokenLike and hasAllTokenLike take the tokenizer of the index on their
input. An index declared on `m.key_k` or `t.k` was found only after
optimize_functions_to_subcolumns rewrote `m['k']` or `tupleElement(t, 'k')`,
so that setting changed the result. The element function now finds it too.

Also mark hasLiteralAt [[nodiscard]] for clang-tidy.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ition

`tupleElement(t, -1)` and `tupleElement(t, toInt64(1))` are rewritten to the subcolumn `t.k` by
`optimize_functions_to_subcolumns`, but the text index condition resolved only string names and
unsigned positions. So an index on `t.k` gave its tokenizer to `hasAnyTokenLike` and
`hasAllTokenLike` only when the rewrite was on, and the result depended on the setting.

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 dismissed their stale review November 16, 2026 17:26

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

valerypetrov and others added 2 commits November 21, 2026 23:01
…s under 26.12

Master is 26.12 now, and the settings history check requires a new setting
to carry a record under the current version. `hasAnyTokenLike` and
`hasAllTokenLike` are introduced in 26.12 for the same reason.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Ergus Ergus removed their assignment Nov 23, 2026
valerypetrov and others added 2 commits November 23, 2026 23:11
The style check forbids plain std containers in src/Processors/QueryPlan.
`choosePerTokenPatternFunctionIndex` kept its candidates in a `std::map`;
switch it to the `MapWithMemoryTracking` alias, like the other containers
in this file. The map stays ordered, because the choice falls back to the
first index by name.

Co-Authored-By: Claude Fable 5.2 <[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-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants