Repository navigation
Enable using the text index in PREWHERE - #89977
10 commits merged into
Conversation
|
Workflow [PR], commit [30e7063] Summary: ❌
|
There was a problem hiding this comment.
Hi @fastio
Very thanks for your PR. However I have some important comments and changes we need to address.
-
I am not convinced about the necessity to use inverted indices in the
PREWHEREbecause 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 usingPREWHERE hasTokeninstead of justWHERE hasToken. However: -
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 columnshasToken(colA,) AND hasToken(colB)to check that the substitution is actually correct and refers to the right columns
d. mixed conditions with no indexed columnshasToken AND id id % 2to 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. -
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
tryToSubstituteWhereandtryToSubstitutePreWhereand call them fromoptimizeDirectReadFromTextIndexkeeping the preamble common code around to DRY. -
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Minor: If this is a String don't (ab)use auto please.
@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. |
715f8a4 to
49c9e79
Compare
| /// 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. |
There was a problem hiding this comment.
For the average reader, it is not clear what term "index condition" means.
There was a problem hiding this comment.
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*/) |
There was a problem hiding this comment.
There is quite some code duplication here :-/
There was a problem hiding this comment.
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.
@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 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:
Do you think this makes sense? |
|
Let's keep it as simple and dumb as possible. In practice, very few users use explicit |
Ok, got it. |
| 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) \ |
There was a problem hiding this comment.
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.
This comment was marked as resolved.
This comment was marked as resolved.
|
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 |
|
|
||
| SET enable_analyzer = 1; | ||
| SET allow_experimental_full_text_index = 1; | ||
| SET use_skip_indexes_on_data_read=1; |
|
|
||
| CREATE TABLE tab | ||
| ( | ||
| `id` Int64, |
There was a problem hiding this comment.
Cosmetic: Please remove the backticks around column names.
| ORDER BY id | ||
| SETTINGS index_granularity = 8; | ||
|
|
||
| INSERT INTO tab VALUES |
There was a problem hiding this comment.
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' |
There was a problem hiding this comment.
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, |
| ( | ||
| `id` Int64, | ||
| `a` Int32, | ||
| `text` String, |
There was a problem hiding this comment.
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' |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Parameter add_alias ideally gets a comment in l. 197-199.
|
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. |
98e3309
|
@fastio test with EXPLAIN output which show that text index is used with PREWHERE is missing |
Changelog category (leave one):
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
Details
PREWHERE does not currently make use of the inverted text index (TYPE text(...)).
Resolves #89975