-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat: Support Expanding OR Conditions in INNER JOIN into Multiple Mutually Exclusive Branches #22370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xiedeyantu
wants to merge
1
commit into
apache:main
Choose a base branch
from
xiedeyantu:expand
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: Support Expanding OR Conditions in INNER JOIN into Multiple Mutually Exclusive Branches #22370
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! [`ExpandJoinOrPredicate`] rewrites inner joins with OR filters into a UNION ALL | ||
| //! of mutually exclusive hashjoin-capable inner joins. | ||
|
|
||
| use crate::optimizer::ApplyOrder; | ||
| use crate::{OptimizerConfig, OptimizerRule}; | ||
| use std::sync::Arc; | ||
|
|
||
| use datafusion_common::tree_node::Transformed; | ||
| use datafusion_common::Result; | ||
| use datafusion_expr::logical_plan::{Join, LogicalPlan, Projection, Union}; | ||
| use datafusion_expr::utils::{can_hash, find_valid_equijoin_key_pair, split_binary_owned, split_conjunction_owned}; | ||
| use datafusion_expr::{Expr, ExprSchemable, JoinType, Operator}; | ||
|
|
||
| #[derive(Default, Debug)] | ||
| pub struct ExpandJoinOrPredicate; | ||
|
|
||
| impl ExpandJoinOrPredicate { | ||
| #[expect(missing_docs)] | ||
| pub fn new() -> Self { | ||
| Self {} | ||
| } | ||
| } | ||
|
|
||
| impl OptimizerRule for ExpandJoinOrPredicate { | ||
| fn name(&self) -> &str { | ||
| "expand_join_or_predicate" | ||
| } | ||
|
|
||
| fn supports_rewrite(&self) -> bool { | ||
| true | ||
| } | ||
|
|
||
| fn apply_order(&self) -> Option<ApplyOrder> { | ||
| Some(ApplyOrder::BottomUp) | ||
| } | ||
|
|
||
| fn rewrite( | ||
| &self, | ||
| plan: LogicalPlan, | ||
| _config: &dyn OptimizerConfig, | ||
| ) -> Result<Transformed<LogicalPlan>> { | ||
| match plan { | ||
| LogicalPlan::Join(join) => rewrite_join(join), | ||
| _ => Ok(Transformed::no(plan)), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn rewrite_join(join: Join) -> Result<Transformed<LogicalPlan>> { | ||
| let original_schema = Arc::clone(&join.schema); | ||
|
|
||
| if join.join_type != JoinType::Inner || join.null_aware { | ||
| return Ok(Transformed::no(LogicalPlan::Join(join))); | ||
| } | ||
|
|
||
| let Some(filter) = join.filter.clone() else { | ||
| return Ok(Transformed::no(LogicalPlan::Join(join))); | ||
| }; | ||
|
|
||
| if filter.is_volatile() { | ||
| return Ok(Transformed::no(LogicalPlan::Join(join))); | ||
| } | ||
|
|
||
| let disjuncts = split_binary_owned(filter, Operator::Or); | ||
| if disjuncts.len() < 2 { | ||
| return Ok(Transformed::no(LogicalPlan::Join(join))); | ||
| } | ||
|
|
||
| let left_schema = join.left.schema(); | ||
| let right_schema = join.right.schema(); | ||
|
|
||
| let Some(branch_keys) = disjuncts | ||
| .iter() | ||
| .map(|expr| extract_hashjoin_keys(expr, left_schema, right_schema)) | ||
| .collect::<Result<Option<Vec<Vec<(Expr, Expr)>>>>>()? | ||
| else { | ||
| return Ok(Transformed::no(LogicalPlan::Join(join))); | ||
| }; | ||
|
|
||
| let mut guards = Vec::with_capacity(disjuncts.len().saturating_sub(1)); | ||
| let mut branches = Vec::with_capacity(disjuncts.len()); | ||
|
|
||
| for (disjunct, keys) in disjuncts.into_iter().zip(branch_keys.into_iter()) { | ||
| let branch_filter = guards | ||
| .iter() | ||
| .cloned() | ||
| .reduce(Expr::and); | ||
|
|
||
| let mut on = join.on.clone(); | ||
| on.extend(keys); | ||
|
|
||
| let branch = LogicalPlan::Join(Join::try_new( | ||
| Arc::clone(&join.left), | ||
| Arc::clone(&join.right), | ||
| on, | ||
| branch_filter, | ||
| join.join_type, | ||
| join.join_constraint, | ||
| join.null_equality, | ||
| join.null_aware, | ||
| )?); | ||
|
|
||
| let branch = LogicalPlan::Projection(Projection::new_from_schema( | ||
| Arc::new(branch), | ||
| Arc::clone(&original_schema), | ||
| )); | ||
|
|
||
| branches.push(Arc::new(branch)); | ||
|
|
||
| guards.push(disjunct.is_not_true()); | ||
| } | ||
|
|
||
| let rewritten = LogicalPlan::Union(Union { | ||
| inputs: branches, | ||
| schema: original_schema, | ||
| }); | ||
|
|
||
| Ok(Transformed::yes(rewritten)) | ||
| } | ||
|
|
||
| fn extract_hashjoin_keys( | ||
| expr: &Expr, | ||
| left_schema: &datafusion_common::DFSchema, | ||
| right_schema: &datafusion_common::DFSchema, | ||
| ) -> Result<Option<Vec<(Expr, Expr)>>> { | ||
| let conjuncts = split_conjunction_owned(expr.clone()); | ||
| let mut keys = Vec::with_capacity(conjuncts.len()); | ||
|
|
||
| for conjunct in conjuncts { | ||
| let Expr::BinaryExpr(binary) = conjunct else { | ||
| return Ok(None); | ||
| }; | ||
|
|
||
| if binary.op != Operator::Eq { | ||
| return Ok(None); | ||
| } | ||
|
|
||
| let Some((left, right)) = find_valid_equijoin_key_pair( | ||
| &binary.left, | ||
| &binary.right, | ||
| left_schema, | ||
| right_schema, | ||
| )? else { | ||
| return Ok(None); | ||
| }; | ||
|
|
||
| let left_type = left.get_type(left_schema)?; | ||
| let right_type = right.get_type(right_schema)?; | ||
| if !can_hash(&left_type) || !can_hash(&right_type) { | ||
| return Ok(None); | ||
| } | ||
|
|
||
| keys.push((left, right)); | ||
| } | ||
|
|
||
| Ok(Some(keys)) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we avoid a new rule for this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see this as a relatively standalone piece of logic, and I haven’t yet found a clean way to hook into it.
Another concern is that I’m not sure whether DataFusion can reliably obtain the row counts from both sides of a join—during testing, I noticed that when both tables are very small (say, ~10 rows), NestedLoopJoin can actually be faster than HashJoin + Union. However, once both tables grow larger (e.g., 1000+ rows), the rewrite shows very significant gains.
Could you walk me through your concerns in more detail? That would help me figure out how to improve it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The concern mostly is makung the optimizer list longer and writing more passes than necessary. If it would fit in an existing planning / optimization pass it would be good.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The only solution I can think of right now is to add this capability to the existing
extract_equijoin_predicaterules. However, strictly speaking, they do completely different things, and the code logic isn't reusable. But if you agree, I can modify it this way. Or please feel free to let me know if you have any better suggestions.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am wonder if instead using union + duplicating scan / subquery we can try one of the following approaches:
Disjoint hash join operator (supporting multiple branches) this would also work for non-mutually exclusive ones => This would probably be a big/complex feature.
Add a new operator that "expands" the input data for multiple output operators (two hash joins) and unions them together later (e.g.
ExpandExec -> [HashJoinExec(a==b), HashJoinExec(c==d)] -> UnionExec). This avoids the duplicated scan / subquery which might be (much) slower in some cases. I think this will work pretty well in general and we probably could enable it by default?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think approach 1 means adding a new specialized hash join operator for ORed equality conditions:
We could add a specialized
DisjointHashJoinExecoperator. The core logic would look like:t1.v1andt1.v2.The benefits are:
I think this approach would be relatively straightforward to implement after:
I'm looking for help reviewing this feature 🎣 , would also be happy to help with follow-up work, such as extending this idea into a disjoint equi-join implementation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah that is exactly what I mean, thanks @2010YOUY01 for explaining fully.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@2010YOUY01 Thank you so much for your detailed explanation of this logic! I think it's a very good idea, and for inner joins, this implementation is optimal, completing the entire logic directly at the physical execution layer. Regarding my current proposal, I support this implementation. However, since I'm not entirely clear on the execution-level logic, implementing it using DisjointHashJoinExec might take some time.
Actually, there's 2 PRs(apache/calcite#4300, apache/calcite#4315) I submitted to Calcite, This rule file (https://github.com/apache/calcite/blob/main/core/src/main/java/org/apache/calcite/rel/rules/JoinExpandOrToUnionRule.java) will be more intuitive. where I implemented inner/left/right/full/anti joins (I didn't implement semi-join because its semantics are not easily split into multiple mutually exclusive joins). Their methods for splitting multiple join branches differ (refer to the comments in the connection code above). This isn't easily implemented using DisjointHashJoinExec; for example, left joins would be split into inner and anti joins. I limited the PR to inner joins because I wanted to implement the first step first, as the performance improvement was significant when testing joins of two tables (1000+ rows). I can't construct SQL to test other scenarios yet, as they all involve anti joins. If everyone accepts this solution, I will expand it to support more join types later. This is why I implemented it as a separate rule. There's another reason, which I also mentioned above: when the table only has 10 rows of data, the overhead becomes apparent, slowing down this optimization. Therefore, parameters or statistical information can help decide whether to rewrite it.
Regarding your first question, I think we can achieve scan reuse at either the logical or physical layer; we don't need to worry too much about rewriting the logic.
Regarding the second question, I think it might be difficult for us to do, perhaps because my understanding of DataFusion's execution layer is still limited.
Regarding the third question, similar to the first, the complexity of the plan is not necessarily directly related to the actual execution logic or performance.
This is just my personal opinion; please correct me if I'm wrong. Thank you very much for participating in the discussion.
If we're only considering inner joins (without expanding to other join types), I personally like the second solution @Dandandan mentioned. @2010YOUY01 If you've already implemented it, then I'll close this PR. If you're interested in further expansions of this PR, I can implement these capabilities through multiple PRs. Looking forward to your reply!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This might not be obvious to everyone yet, but with #21983, extending this into a new specialized join operator should be easy, and it would automatically support outer/semi/... join types.
I can show this with a PoC later. Once we have that version, we can decide which approach to take.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@2010YOUY01 Thank you for your great idea. I look forward to your solution and will also study your existing solutions.