Skip to content

Support direct reading from text index as a hint for functions like and equals - #88550

Merged
CurtizJ merged 22 commits into
ClickHouse:masterfrom
CurtizJ:direct-read-hint
Nov 24, 2025
Merged

CurtizJ merged 22 commits into
ClickHouse:masterfrom
CurtizJ:direct-read-hint

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Oct 14, 2025 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Improved filtering performance for predicates with functions such as like, equals, has, and others by leveraging an additional preliminary filter built from the text index. This optimization is enabled via the query_plan_text_index_add_hint setting. Improved usage of the text index for columns of Map data type.

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [405dd22]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan, targeted) failure
01459_manual_write_to_replicas_quorum_detach_attach FAIL cidb, flaky
01459_manual_write_to_replicas_quorum_detach_attach FAIL cidb, flaky
01459_manual_write_to_replicas_quorum_detach_attach FAIL cidb, flaky
01459_manual_write_to_replicas_quorum_detach_attach FAIL cidb, flaky
01459_manual_write_to_replicas_quorum_detach_attach FAIL cidb, flaky
Stateless tests (amd_msan, parallel) failure
01132_max_rows_to_read FAIL cidb, flaky
00816_long_concurrent_alter_column FAIL cidb, flaky
Integration tests (amd_tsan, 1/6) failure
test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures[1] FAIL cidb, flaky
Integration tests (amd_tsan, 3/6) failure
test_restore_db_replica/test.py::test_query_after_restore_db_replica[alter table-no exists table-no restart] FAIL cidb, flaky
BuzzHouse (amd_debug) failure
Logical error: 'Inconsistent AST formatting: the query: FAIL cidb
BuzzHouse (amd_ubsan) failure
/home/ubuntu/actions-runner/_work/ClickHouse/ClickHouse/src/IO/VarInt.h:32:5: runtime error: store to null pointer of type 'char' FAIL cidb

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 14, 2025
@CurtizJ
CurtizJ marked this pull request as ready for review November 19, 2025 17:46
@george-larionov george-larionov self-assigned this Nov 20, 2025

@george-larionov george-larionov 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 ran out of time, I will finish the review tomorrow.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved

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

Overall it looks good to me, it is a nice optimization. Just a few comments and suggestions.

return std::nullopt;
/// Do not optimize if there are multiple text indexes set for the same expression.
/// It is abgious which index to use. However, we allow to use several indexes for different expressions.
/// for example, we can use indexes both for mapKeys(m) and mapValues(m) in one function m['key'] = 'value'.

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 you add a test for this case?

return std::nullopt;

if (function_node.children.size() != 2)
if (!WhichDataType(function_node.result_type).isUInt8())

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 what situation would this be hit? Can we test for it?

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.

@george-larionov The initial test was because the first version of the optimization was implemented only for hasToken and searchAll|Any which had an specific prototype and the check was replacing function nodes with other function nodes with similar prototypes.

I suppose that the new test is to force a stop here in case some other functions are added in the future; because the new version replaces the function with an UInt column.

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.

It's an early exit for functions that cannot be used in the text index to avoid further heavy analysis of them.

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 add add a brief comment in the source code.

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

Overall LGTM but:

I added a few questions; the most concerning one for me is the probabilistic approach to estimate cardinality because I find it too heuristic for a 100% accuracy; and normal language doesn't follow a uniform words distribution. But I am pretty sure that I could be missing something there.

Some changes will be needed to accomplish with the changes for empty matches merged in #89757

There are also some conflicts with master that should be fixed before merging.

An external contributed PR #89977 should be updated if this merges before because there are conflicts

return &dag.addFunction(node->function_base, new_children, "");
}

return node;

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 the DAG there is only one list of node objects and the rest are pointers to the nodes in that list.

In that case if we iterate over the list and replace node info in place it is just simpler and faster. Don't need to store and search a ReplacementMap, don't need to iterate recursively over all the DAG and don't need to update any reference in a children because memory address won't change and the list entries are unique.

Did we have an issue with that approach?

Because the "and" replacement implemented bellow I think is also possible with the "old" method.

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.

Technically, in-place modification was incorrect because we didn't update the result_name of the parent nodes; however, we should do this. It didn't cause bugs, but left a DAG in an inconsistent state. Also, I'd like to avoid modifying private fields of ActionsDAG inplace, and use public methods like addInput and addFunction. Iterating a DAG one extra time is not a big performance issue.

return std::nullopt;

if (function_node.children.size() != 2)
if (!WhichDataType(function_node.result_type).isUInt8())

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.

@george-larionov The initial test was because the first version of the optimization was implemented only for hasToken and searchAll|Any which had an specific prototype and the check was replacing function nodes with other function nodes with similar prototypes.

I suppose that the new test is to force a stop here in case some other functions are added in the future; because the new version replaces the function with an UInt column.

const String new_filter_column_name = filter_column_node.result_name;
auto new_filter_column_name = result.filter_node->result_name;
filter_node->step = std::make_unique<FilterStep>(read_from_merge_tree_step->getOutputHeader(), filter_dag.clone(), new_filter_column_name, removes_filter_column);
}

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 another PR: #89977 That adds support for PREWHERE and will conflict with these changes.

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

@CurtizJ I (and likely users too) lost the overview

  • which function,
  • with which tokenizer,

is (not) supported by direct read or by by direct read as a hint. Could you please update https://clickhouse.com/docs/engines/table-engines/mergetree-family/invertedindexes#direct-read as well? While at it, please also document (user-level docs) how the hint mechanism works.

return std::nullopt;

if (function_node.children.size() != 2)
if (!WhichDataType(function_node.result_type).isUInt8())

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 add add a brief comment in the source code.

@CurtizJ

CurtizJ commented Nov 24, 2025 •

Copy link
Copy Markdown
Member Author

I'll add documentation in a separate PR. The documentation of inverted indexes requires some other corrections, though.

@CurtizJ

CurtizJ commented Nov 24, 2025

Copy link
Copy Markdown
Member Author

Failed tests are flaky according to the cidb.

@CurtizJ
CurtizJ added this pull request to the merge queue Nov 24, 2025
Merged via the queue into ClickHouse:master with commit 4a24752 Nov 24, 2025
@CurtizJ
CurtizJ deleted the direct-read-hint branch November 24, 2025 16:19
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 24, 2025
@EmeraldShift

Copy link
Copy Markdown
Contributor

Is this optimization expected to work for LowCardinality columns? I'm unable to leverage it in this setup (fiddle):

CREATE TABLE x (c LowCardinality(String), INDEX i c type text(tokenizer='array'))
ENGINE = MergeTree
ORDER BY tuple()
SETTINGS allow_experimental_full_text_index;

INSERT INTO x VALUES ('config');

EXPLAIN actions = 1
SELECT count() FROM x
WHERE c = 'config'
SETTINGS
    use_skip_indexes_on_data_read,
  query_plan_text_index_add_hint, text_index_hint_max_selectivity=1, allow_experimental_full_text_index;

Expression ((Project names + Projection))
Actions: INPUT :: 0 -> count() UInt64 : 0
Positions: 0
  Aggregating
  Keys:
  Aggregates:
      count()
        Function: count() → UInt64
        Arguments: none
  Skip merging: 0
    Expression (Before GROUP BY)
    Positions:
      Filter ((WHERE + Change column names to column identifiers))
      Filter column: equals(__table1.c, \'config\'_String) (removed)
      Actions: INPUT : 0 -> c LowCardinality(String) : 0
               COLUMN Const(String) -> \'config\'_String String : 1
               FUNCTION equals(c :: 0, \'config\'_String :: 1) -> equals(__table1.c, \'config\'_String) LowCardinality(UInt8) : 2
      Positions: 2
        ReadFromMergeTree (default.x)
        ReadType: Default
        Parts: 1
        Granules: 1

However, using an ordinary String column works:

Expression ((Project names + Projection))
Actions: INPUT :: 0 -> count() UInt64 : 0
Positions: 0
  Aggregating
  Keys:
  Aggregates:
      count()
        Function: count() → UInt64
        Arguments: none
  Skip merging: 0
    Expression (Before GROUP BY)
    Positions:
      Filter
      Filter column: __text_index_i_equals_888efda921680e32e66fe44752bfa9ba (removed)
      Actions: INPUT :: 0 -> __text_index_i_equals_888efda921680e32e66fe44752bfa9ba UInt8 : 0
      Positions: 0
        ReadFromMergeTree (default.x)
        ReadType: Default
        Parts: 1
        Granules: 1

@rschu1ze

Copy link
Copy Markdown
Member

@EmeraldShift I opened a bug - #90778

@alexey-milovidov

Copy link
Copy Markdown
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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.

7 participants