Skip to content

Enable using the text index in PREWHERE - #89977

Merged
10 commits merged into
ClickHouse:masterfrom
fastio:enable_using_inverted_text_index_in_prewhere
Dec 5, 2025
Merged

10 commits merged into
ClickHouse:masterfrom
fastio:enable_using_inverted_text_index_in_prewhere

Conversation

@fastio

@fastio fastio commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Enable using inverted index in PREWHERE. Resolves #89975

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Details

PREWHERE does not currently make use of the inverted text index (TYPE text(...)).

Resolves #89975

@Ergus Ergus self-assigned this Nov 13, 2025
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Nov 13, 2025
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30e7063]

Summary: ❌

job_name test_name status info comment
Fast test failure
02995_new_settings_history FAIL cidb
Build (amd_debug) dropped
Build (amd_asan) dropped
Build (amd_tsan) dropped
Build (amd_msan) dropped
Build (amd_ubsan) dropped
Build (amd_binary) dropped
Build (arm_asan) dropped
Build (arm_binary) dropped
Build (arm_tsan) dropped

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 13, 2025

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

Very thanks for your PR. However I have some important comments and changes we need to address.

  1. I am not convinced about the necessity to use inverted indices in the PREWHERE because what the inverted indices optimization (direct read optimization) does is to move filtering to the PREWHERE. Maybe for semantics (in case the user still wants to do it) it makes some sense, but from a practical point of view I don't think there is any benefit using PREWHERE hasToken instead of just WHERE hasToken. However:

  2. A change like this needs exhaustive testing. Including conditions where

    a. we use a single condition (hasToken, hasAllTokens...) to check that substitution happens.
    b. multiple conditions on a single indexed column (hasToken AND hasToken, hasToken and hasAnyToken...) to check that ALL the expected sunstitutions happen
    c. conditions on different indexed columns hasToken(colA,) AND hasToken(colB) to check that the substitution is actually correct and refers to the right columns
    d. mixed conditions with no indexed columns hasToken AND id id % 2 to check that even with other dependencies some substitution takes place.
    e. mixing potentially conflicting conditions in the WHERE and the PREWHERE to ensure that the code solves the corner cases correctly.

  3. Considering the single responsibility principle I think that your new code should be implemented in a separated function in order to have the WHERE and PREWHERE substitution logics totally separated. You can add two functions like tryToSubstituteWhere and tryToSubstitutePreWhere and call them from optimizeDirectReadFromTextIndex keeping the preamble common code around to DRY.

  4. The main motivation for a change like this should be some performance benefit. It will be very desirable if you show some numbers befor and after your change to support this change.

QueryPlan::Node * filter_node = (stack.rbegin() + 1)->node;
FilterStep * filter_step = typeid_cast<FilterStep *>(filter_node->step.get());
if (!filter_step)
if (!filter_step && !read_from_merge_tree_step)

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.

This condition is already checked in L243. if !read_from_merge_tree_step you never get here


ActionsDAG & filter_dag = filter_step->getExpression();
const ActionsDAG::Node & filter_column_node = filter_dag.findInOutputs(filter_step->getFilterColumnName());
if (filter_step)

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 the previous condition fixed this if is not needed right?? Could you please simplify the logic || at least addd some comments?


auto logger = getLogger("optimizeDirectReadFromTextIndex");
LOG_DEBUG(logger, "{}", optimizationInfoToString(added_columns, removed_columns));
if (read_from_merge_tree_step)

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.

As I said before. If !read_from_merge_tree_step you never arrive here. Also this optimization is a bit pointless in that case

cloned_prewhere_info.prewhere_column_name);

bool removes_filter_column = filter_step->removesFilterColumn();
if (added_columns.empty())

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.

All this code is almost a copy-paste of the code above. Maybe you need to find a simpler approach to simplify and DRY.

lazily_read_info,
query_info.row_level_filter,
query_info.prewhere_info));
ignore_prewhere ? nullptr : query_info.prewhere_info));

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.

Sorry, I don't see any use for this variable. What I am missing?

{
const auto & [index_name, column_name] = replaced.value();
added_columns[index_name].emplace_back(column_name, node.result_type);
if (origin_prewhere_column_name == origin_result_name)

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.

where is this origin_result_name defined?

/// Example: hasToken(text_col, 'token') -> __text_index_text_col_idx_hasToken_0
/// Returns a pair of (added columns by index name, removed columns)
std::pair<IndexReadColumns, Names> replace()
std::tuple<IndexReadColumns, Names, String> replace(const String & origin_prewhere_column_name)

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 argument passed to this function is not always the prewhere column. In the fist call it is the filter column, which is totally valid to be non-index column right?


for (ActionsDAG::Node & node : actions_dag.nodes)
{
auto prewhere_column_name = origin_prewhere_column_name;

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: If this is a String don't (ab)use auto please.

Ergus

This comment was marked as duplicate.

@fastio

fastio commented Nov 13, 2025

Copy link
Copy Markdown
Contributor Author

Hi @fastio

Very thanks for your PR. However I have some important comments and changes we need to address.

  1. I am not convinced about the necessity to use inverted indices in the PREWHERE because what the inverted indices optimization (direct read optimization) does is to move filtering to the PREWHERE. Maybe for semantics (in case the user still wants to do it) it makes some sense, but from a practical point of view I don't think there is any benefit using PREWHERE hasToken instead of just WHERE hasToken. However:
  2. A change like this needs exhaustive testing. Including conditions where
    a. we use a single condition (hasToken, hasAllTokens...) to check that substitution happens.
    b. multiple conditions on a single indexed column (hasToken AND hasToken, hasToken and hasAnyToken...) to check that ALL the expected sunstitutions happen
    c. conditions on different indexed columns hasToken(colA,) AND hasToken(colB) to check that the substitution is actually correct and refers to the right columns
    d. mixed conditions with no indexed columns hasToken AND id id % 2 to check that even with other dependencies some substitution takes place.
    e. mixing potentially conflicting conditions in the WHERE and the PREWHERE to ensure that the code solves the corner cases correctly.
  3. Considering the single responsibility principle I think that your new code should be implemented in a separated function in order to have the WHERE and PREWHERE substitution logics totally separated. You can add two functions like tryToSubstituteWhere and tryToSubstitutePreWhere and call them from optimizeDirectReadFromTextIndex keeping the preamble common code around to DRY.
  4. The main motivation for a change like this should be some performance benefit. It will be very desirable if you show some numbers befor and after your change to support this change.

@Ergus I much appreciate your careful and detailed review. I apologize for submitting this PR too hastily — it resulted in a less-than-ideal review experience, and that’s on me.
I will go through all your comments, update the code accordingly, add the missing test cases, and include the necessary performance data to demonstrate the value of this PR.

@fastio
fastio force-pushed the enable_using_inverted_text_index_in_prewhere branch from 715f8a4 to 49c9e79 Compare November 13, 2025 17:59
@Ergus

Ergus commented Nov 14, 2025

Copy link
Copy Markdown
Member

Some tests are failing:

03373_named_session_try_recreate_before_timeout: This is flaky: #89226
test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures: Also flaky: #88931

The others need to be checked

/// which use only the index information to bypass the normal column scan which can consume significant amount of the execution time.
void optimizeDirectReadFromTextIndex(const Stack & stack, QueryPlan::Nodes & /*nodes*/)
/// Helper function.
/// Collects index conditions from the given ReadFromMergeTree step and stores them in index_conditions.

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 the average reader, it is not clear what term "index condition" means.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for pointing that out. You’re right :). I will either replace it with a more descriptive phrase or add a short explanation to make the meaning explicit.

///
/// Same as `optimizeWhereDirectReadFromTextIndex, this function replaces text function nodes from the user query (using semi-brute-force process) with internal virtual columns
/// which use only the index information to bypass the normal column scan which can consume significant amount of the execution time.
void optimizePrewhereDirectReadFromTextIndex(const Stack & stack, QueryPlan::Nodes & /*nodes*/)

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.

There is quite some code duplication here :-/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right, there is some duplication here. I will refactor this part and move more of the shared logic into common routines to eliminate the duplication.

@fastio

fastio commented Nov 16, 2025 •

Copy link
Copy Markdown
Contributor Author

checked

Some tests are failing:

03373_named_session_try_recreate_before_timeout: This is flaky: #89226 test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures: Also flaky: #88931

The others need to be checked

@Ergus Thanks.

At this stage, I’d like to first ensure that the overall approach is correct.

To properly implement direct reads from the inverted text index for text functions (e.g.hasToken,hasAnyTokens,hasAllTokens
) appearing in WHERE and PREWHERE, the optimization needs to correctly handle three scenarios:

Scenario 1: Only WHERE contains eligible text functions

The case is already supported by the current logic in the ClickHouse kernel, so no additional work is required there.

Scenario 2: Only PREWHERE contains eligible text functions

For queries where only the PREWHERE clause contains such text functions, we need to apply the same idea as in the WHERE-only case: detect the eligible text functions in PREWHERE and rewrite them to use virtual-column constructs from the text index.

Scenario 3: Both WHERE and PREWHERE contain eligible text functions

If the query has eligible text functions in both WHERE and PREWHERE clause, we should avoid doing duplicated work and ensure the filters are simply processed as much as possible. In this case, I plan to:

  • Extract the ActionsDAG in WHERE that are related to the text functions and their dependencies.
  • Merge these extracted actions into the PREWHERE actions so that the text-based filtering is done consistently in one place.
  • After this merge, we treat it like Scenario 2: apply the same direct-read rewriting on the PREWHERE side and then continue with the usual optimization pipeline.

Do you think this makes sense?

@rschu1ze

rschu1ze commented Nov 16, 2025 •

Copy link
Copy Markdown
Member

Let's keep it as simple and dumb as possible. In practice, very few users use explicit PREWHERE filters in their SELECT queries, so this PR addresses only an exotic/obscure/niche use case. We can simply forbid the case that PREWHERE and WHERE contain eligible functions (--> throw an exception).

@fastio

fastio commented Nov 17, 2025

Copy link
Copy Markdown
Contributor Author

Let's keep it as simple and dumb as possible. In practice, very few users use explicit PREWHERE filters in their SELECT queries, so this PR addresses only an exotic/obscure/niche use case. We can simply forbid the case that PREWHERE and WHERE contain eligible functions (--> throw an exception).

Ok, got it.

Comment thread src/Common/ErrorCodes.cpp Outdated
M(760, TEXT_INDEX_USED_IN_BOTH_PREWHERE_AND_WHERE) \
M(761, TEXT_INDEX_USED_IN_BOTH_PREWHERE_AND_WHERE) \
M(762, UNICODE_ERROR) \
M(763, ACME_ERROR) \

@Ergus Ergus Nov 17, 2025 •

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 don't have a strong opinion on this detail @rschu1ze . But I think that a new error is not needed in this case. Just an "INCORRECT_QUERRY" error with a clear message may work and will be simpler.

@Ergus Ergus closed this Nov 17, 2025
@Ergus Ergus reopened this Nov 17, 2025
@Ergus

This comment was marked as resolved.

@Ergus

Ergus commented Nov 19, 2025

Copy link
Copy Markdown
Member

Hi @fastio

There are some tests with weird errors. If you need some help to check them do no hesitate to request ;)

@fastio

fastio commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @fastio

There are some tests with weird errors. If you need some help to check them do no hesitate to request ;)

@Ergus Thank you for the helpful feedback.

The failure comes from 02973_backup_of_in_memory_compressed. From what I can see, the same test is currently failing on multiple other PRs as well, so it’s likely not caused by this change.

025-11-21 04:25:43 Reason: having stderror:  
2025-11-21 04:25:43 [cc417434f0e1] 2025.11.21 01:25:41.089052 [ 3508 ] {5544491b-588b-4087-bd46-cb491fd4eca9} <Error> BackupsWorker: Failed to make backup File('test.zip'): Code: 598. DB::Exception: Backup File('test.zip') already exists. (BACKUP_ALREADY_EXISTS), Stack trace (when copying this message, always include the lines below):
2025-11-21 04:25:43 
2025-11-21 04:25:43 0. ./contrib/llvm-project/libcxx/include/__exception/exception.h:0: Poco::Exception::Exception(String const&, int) @ 0x00000000400cd120
2025-11-21 04:25:43 1. ./ci/tmp/build/./src/Common/Exception.cpp:129: DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x000000001dfe07bc
2025-11-21 04:25:43 2. DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000f35d61c
2025-11-21 04:25:43 3. DB::Exception::Exception(PreformattedMessage&&, int) @ 0x000000000f35c94c
2025-11-21 04:25:43 4. DB::Exception::Exception<String const&>(int, FormatStringHelperImpl<std::type_identity<String const&>::type>, String const&) @ 0x000000000f379520
2025-11-21 04:25:43 5. ./ci/tmp/build/./src/Backups/BackupImpl.cpp:591: DB::BackupImpl::checkBackupDoesntExist() const @ 0x00000000288e7b38
2025-11-21 04:25:43 6. ./ci/tmp/build/./src/Backups/BackupImpl.cpp:201: DB::BackupImpl::open() @ 0x00000000288e2ad0
2025-11-21 04:25:43 7. ./ci/tmp/build/./src/Backups/BackupImpl.cpp:136: DB::BackupImpl::BackupImpl(DB::BackupFactory::CreateParams, DB::BackupImpl::ArchiveParams const&, std::shared_ptr<DB::IBackupWriter>) @ 0x00000000288e4024
2025-11-21 04:25:43 8. ./contrib/llvm-project/libcxx/include/__memory/unique_ptr.h:759: std::shared_ptr<DB::IBackup> std::__function::__policy_func<std::shared_ptr<DB::IBackup> (DB::BackupFactory::CreateParams const&)>::__call_func[abi:ne210105]<DB::registerBackupEnginesFileAndDisk(DB::BackupFactory&)::$_0>(std::__function::__policy_storage const*, DB::BackupFactory::CreateParams const&) @ 0x0000000028a1c7dc
2025-11-21 04:25:43 9. ./contrib/llvm-project/libcxx/include/__functional/function.h:508: ? @ 0x00000000288d0644
2025-11-21 04:25:43 10. ./ci/tmp/build/./src/Backups/BackupsWorker.cpp:611: DB::BackupsWorker::openBackupForWriting(DB::BackupInfo const&, DB::BackupSettings const&, std::shared_ptr<DB::IBackupCoordination>, std::shared_ptr<DB::Context const> const&) const @ 0x00000000288a8e9c
2025-11-21 04:25:43 11. ./ci/tmp/build/./src/Backups/BackupsWorker.cpp:470: DB::BackupsWorker::BackupStarter::doBackup() @ 0x00000000288c5800
2025-11-21 04:25:43 12. ./ci/tmp/build/./src/Backups/BackupsWorker.cpp:561: void std::__function::__policy_func<void ()>::__call_func[abi:ne210105]<DB::BackupsWorker::startMakingBackup(std::shared_ptr<DB::IAST> const&, 


SET enable_analyzer = 1;
SET allow_experimental_full_text_index = 1;
SET use_skip_indexes_on_data_read=1;

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.

Cosmetic: + spaces around 1


CREATE TABLE tab
(
`id` Int64,

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.

Cosmetic: Please remove the backticks around column names.

ORDER BY id
SETTINGS index_granularity = 8;

INSERT INTO tab VALUES

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.

Could you please add short separators comments -- - every 4 rows (granule) and long separator comments every 4 * 8 = 64 rows (index granule)? This will make it easier to correlate the expected results in the .reference file with the queries in this file.

(127, 107, 'xyz uvw rst', 'aaa bbb ccc'),
(128, 108, 'final test row', 'completed yes');

-- Basic: single text-index function on 'text'

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 rewrite the comments to SELECT 'Basic: single text-index function on "text"', so the results in the .reference file contain some useful comments.

CREATE TABLE tab
(
`id` Int64,
`a` Int32,

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.

a --> int or x

(
`id` Int64,
`a` Int32,
`text` 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.

text --> str_indexed1, text2 --> str_indexed2

-- Basic: hasAllTokens on 'text'
SELECT count() FROM tab PREWHERE hasAllTokens(text, ['column', 'store']);

-- Basic: text-index functions on 'text2'

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.

Re l. 163 - 168: Since columns text and text2 have the same index definitions, we are testing exactly the same things as in l. l. 154-161. Please remove.

SELECT count() FROM tab PREWHERE hasAllTokens(text2, ['merge', 'tree']);

-- Text condition + numeric condition (AND)
SELECT count() FROM tab PREWHERE hasToken(text, 'clickhouse') AND a > 0;

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.

We need to test two things:

  • the query result is correct,
  • execution uses the text index

Queries could fall back to brute-force search and still return a correct result. We need to check the output of EXPLAIN PLAN indexes = 1.

/// Example: hasToken(text_col, 'token') -> __text_index_text_col_idx_hasToken_0
/// Returns a pair of (added columns by index name, removed columns)
std::pair<IndexReadColumns, Names> replace()
std::pair<IndexReadColumns, Names> replace(bool add_alias = false)

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.

Parameter add_alias ideally gets a comment in l. 197-199.

@rschu1ze

Copy link
Copy Markdown
Member

@fastio I added some comments ... @Ergus is on vacation and back in 2 weeks, he knows the code better than me, it would be good to wait for him to do a final review + merge this PR. Thanks for working on this!

@rschu1ze rschu1ze changed the title Enable using inverted index in prewhere Enable using the text index in PREWHERE Nov 24, 2025
@CurtizJ

CurtizJ commented Nov 24, 2025

Copy link
Copy Markdown
Member

I've also briefly reviewed the PR. The changes look good to me. Sorry for merging the conflicting PR #88550. I'll resolve the conflicts and merge your changes in a separate branch.

@CurtizJ CurtizJ mentioned this pull request Nov 24, 2025
@fastio

fastio commented Nov 25, 2025

Copy link
Copy Markdown
Contributor Author

@fastio I added some comments ... @Ergus is on vacation and back in 2 weeks, he knows the code better than me, it would be good to wait for him to do a final review + merge this PR. Thanks for working on this!

@rschu1ze Thanks for the update!

@fastio

fastio commented Nov 25, 2025

Copy link
Copy Markdown
Contributor Author

I've also briefly reviewed the PR. The changes look good to me. Sorry for merging the conflicting PR #88550. I'll resolve the conflicts and merge your changes in a separate branch.

@CurtizJ Thank you for taking the time to review and merge it!

@github-merge-queue github-merge-queue Bot closed this pull request by merging all changes into ClickHouse:master in 98e3309 Dec 5, 2025
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Dec 5, 2025
@fm4v

fm4v commented Dec 8, 2025

Copy link
Copy Markdown
Member

@fastio test with EXPLAIN output which show that text index is used with PREWHERE is missing

@CurtizJ

CurtizJ commented Dec 8, 2025

Copy link
Copy Markdown
Member

@fm4v I've added tests with EXPLAIN in #90768.

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-improvement Pull request with some product improvements 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.

PREWHERE currently cannot use inverted text index (text index is ignored in PREWHERE)

7 participants