Skip to content

Text index: allow hasPhrase to accept an array of strings as input - #120859

Merged
ahmadov merged 20 commits into
masterfrom
ahmadov/hasphrase-array-input
Oct 2, 2026
Merged

ahmadov merged 20 commits into
masterfrom
ahmadov/hasphrase-array-input

Conversation

@ahmadov

@ahmadov ahmadov commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Previously, the hasPhrase function only accepted a string input, so the text index postprocessor rewrite had to rejoin the postprocessed tokens into a string for hasPhrase to re-tokenize. The rejoin used a space, so a tokenizer that does not split on spaces got back a different token sequence and hasPhrase returned wrong results.

hasPhrase now takes an Array(String) whose elements would be tokenized same as hasAny/AllTokens.

Additionally, the array/keyword tokenizer support has been added with this PR. The reason for supporting it is due to how postprocessor rewrite the hasPhrase queries.

Suppose we have this text index definition:

text(tokenizer = splitByString(['()']), postprocessor = lower(message))

and the query is:

hasPhrase(message, 'foo()bar');

after the rewrite that query conceptually becomes:

hasPhrase(arrayMap(x -> lower(x), tokens(message, 'splitByString([\'()\'])')), ['foo', 'bar'], 'array')

since the array/keyword tokenizer is no-op, we need it to avoid double-tokenization of array elements.

Fixes #117075.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

On a column whose text index has a postprocessor, hasPhrase rejoined the index tokens with a space before matching, so it returned wrong results unless that space matched how the tokenizer splits. Allowing hasPhrase to accept an Array(String) removes joining tokens completely.


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

Version info

  • Merged into: 26.10.1.1248-master (included in 26.10 and later)

Previously, the `hasPhrase` function only accepted a string input, so
the text index postprocessor rewrite had to rejoin the postprocessed
tokens into a string for `hasPhrase` to re-tokenize. The rejoin used a
space, so a tokenizer that does not split on spaces got back a different
token sequence and `hasPhrase` returned wrong results.

`hasPhrase` now takes an `Array(String)` whose elements are the tokens, so the
rewrite passes the index's token sequence directly and nothing is re-tokenized.

Fixes #117075.
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a4b268]

Summary: ✅


AI Review

Summary

This PR fixes the hasPhrase postprocessor re-tokenization bug by letting hasPhrase operate on token arrays, extending the text-index rewrite and index-analysis paths to Array(String) phrases/haystacks and the array tokenizer, and adding focused stateless coverage for the new contracts. After reviewing the current diff and the full prior discussion, I did not find remaining correctness, compatibility, or high-impact performance issues in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0a4b268.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 253/276 (91.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 18, 2026
Comment thread src/Functions/hasPhrase.cpp Resolved
Comment thread src/Functions/hasPhrase.cpp Resolved
@ahmadov ahmadov added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 18, 2026
Comment thread src/Functions/hasPhrase.cpp Resolved
Comment thread src/Functions/hasPhrase.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0a4b26896 with master 28dc98b1f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0982e5a39; 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.

Object file sizes

39 object files changed (+172.97 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasPhrase.cpp.o 491.86 KiB 611.05 KiB +119.19 KiB (+24.23%)
src/CMakeFiles/dbms.dir/Processors/Transforms/Window/SlidingBlocks.cpp.o new 34.98 KiB +34.98 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/WindowTransform.cpp.o 160.67 KiB 136.67 KiB -24.00 KiB (-14.94%)

719 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

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

Job report

@ahmadov
ahmadov requested review from Ergus and rschu1ze September 22, 2026 12:10

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

With this PR the splitByRegexp + postprocessor rejection rationale changes.

The comment in MergeTreeIndexConditionText.cpp:1427 justifies the throw entirely in terms of a mechanism deleted in PR: "rejoins the normalized tokens with a space and re-tokenizes them, and validates each token with the splitByNonAlpha separator rule."

We can avoid all that now so please, update the comment ;)

Comment thread src/Functions/hasPhrase.cpp Resolved
continue;

/// An empty element is not a token; the index has no position for one.
std::string_view element = col_elements.getDataAt(element_index);

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.

IIUC FixedString array elements are now matched with their NUL padding. Is that intended?

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.

Yes. executeMatchPhraseOnArray currently feeds ColumnFixedString::getDataAt straight into the matcher, so an element like toFixedString('aa', 4) is compared as aa\0\0, not aa.

That means the row path returns the wrong answer for padded values, for example hasPhrase([toFixedString('aa', 4), toFixedString('bb', 4)], ['aa', 'bb']) stays false here, while the indexed rewrite tokenizes the same elements down to aa / bb and can return true. So trailing NUL padding still leaks into Array(FixedString) matching in the current code.

/// Argument types shared by the token-search functions `hasAnyTokens`, `hasAllTokens` and `hasPhrase`.

/// Function input accepts string, fixed string, array of string or array of fixed strings.
inline bool isStringOrFixedStringOrArrayOfStringOrFixedString(const IDataType & type)

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.

FWIS Array(Nothing) is accepted as a phrase but rejected as an input, so hasPhrase('a', []) should work while hasPhrase([], 'a') throws ILLEGAL_TYPE_OF_ARGUMENT

Comment thread src/Functions/hasPhrase.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.

Does a text(tokenizer = array) index can answer hasPhrase? Because the function now accepts the array tokenizer.

FWIS traverseFunctionNode returns false, so the query does a full scan and force_data_skipping_indices fails with INDEX_NOT_USED. The function has to accept array because the postprocessor rewrite passes it, so it cannot be hidden again.

I think that supporting it on the index side is one entry in the set; positions work for any tokenizer. Should we add it now with a force_data_skipping_indices test on an Array(String) column?

Note that `splitByRegexp` is not supported for `hasPhrase` when the text index also defines a postprocessor.
The tokenizer argument must be one of `splitByNonAlpha`, `splitByString`, `splitByRegexp`, `array`, `ngrams`, `asciiCJK`, or `icu`.

If `input` is an [Array(String)](/reference/data-types/array), its elements are tokenized like any other input and their tokens form a single sequence per row, so a phrase may span two elements. With the `array` tokenizer each element is one token, which is how a column of already tokenized values is searched.

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 constrain the sentence in l. 352 to String phrases and needles?

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'm confused:

The PR message says "nothing gets re-tokenized".

L. 356 says "If input is an Array(String), its elements are tokenized like any other input [...]"

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.

I'm confused:

The PR message says "nothing gets re-tokenized".

L. 356 says "If input is an Array(String), its elements are tokenized like any other input [...]"

the PR message was wrong, I just added the support for array/keyword tokenizer recently, but it was not reflected on the PR message. I just updated the message to include the necessity of the array/keyword tokenizer.

Comment thread src/Functions/hasPhrase.cpp Resolved
@ahmadov
ahmadov requested review from Ergus and rschu1ze September 29, 2026 21:28
Comment thread src/Functions/hasPhrase.cpp Resolved
if (!drop_empty_needles || !element_value.empty())
tokens.push_back(element_value);
}
/// Compaction is unsound after a postprocessor, and the functions collapse duplicates themselves.

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.

"the functions collapse duplicates themselves" is not true for hasPhrase

ErrorCodes::BAD_ARGUMENTS,
"Function 'hasPhrase' is not supported on a text index that uses the 'splitByRegexp' tokenizer and a postprocessor");
/// Positions restart per element, so the granule token test plus the row-level function decide instead.
const bool use_positions = has_positions && !indexed_column_is_array;

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.

Positions are also turned off for Array columns with a postprocessor, where they would be correct.

@ahmadov
ahmadov enabled auto-merge October 1, 2026 22:07
@ahmadov
ahmadov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into master with commit a717648 Oct 2, 2026
149 checks passed
@ahmadov
ahmadov deleted the ahmadov/hasphrase-array-input branch October 2, 2026 03:36
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@ahmadov @Ergus — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 12, 2026
… arrays

ClickHouse#120859 made hasPhrase accept an Array(String) haystack, so on a Variant or
Dynamic path an Array alternative can satisfy a string-needle hasPhrase while
the JSONAllValues index holds that value's text, not its elements.
Measured with JSON(v Variant(Array(String), String)) and the array tokenizer:
hasPhrase(j.v, 'abc', 'array') counted 0 with the index and 1 without it.

The other kept string searches still reject an Array haystack, so only
hasPhrase leaves the allow-list. On a bare Dynamic path hasPhrase returns
Dynamic and is not a valid filter, so the cost is index use on Variant paths.
The Variant index-use control moves to hasToken, and the array face joins
the hasAllTokens one in the test.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 9, 2026
Add the no hint, no direct read and use_skip_indexes = 0 variants to the
default needle rows of 05315, and a hasPhrase(m['k'], repeat(char(0), 3))
cell on tab_post. That cell used to raise "Text index postprocessor
produced an invalid token '#'"; since ClickHouse#120859 the hasPhrase rewrite
compares token arrays and no longer throws, so it returns the absent-key
row like use_skip_indexes = 0 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... hold Skip for auto-updating. pr-bugfix Pull request with bugfix, not backported by default 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.

Text index with splitByString tokenizer + postprocessor: hasPhrase returns wrong results on every execution path (silent row loss and false positives)

6 participants