alamb commented on code in PR #3482: URL: https://github.com/apache/arrow-datafusion/pull/3482#discussion_r973572268
########## datafusion/optimizer/src/reduce_cross_join.rs: ########## @@ -0,0 +1,452 @@ +// 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. + +//! Optimizer rule to reduce cross join to inner join if join predicates are available in filters. +use crate::{OptimizerConfig, OptimizerRule}; +use datafusion_common::{Column, Result}; +use datafusion_expr::{ + logical_plan::{Filter, Join, CrossJoin, JoinType, LogicalPlan}, + utils::from_plan, and, or, utils::can_hash +}; +use datafusion_expr::{Expr, Operator}; + +use std::collections::HashSet; + +//use std::collections::HashMap; +use std::sync::Arc; +use datafusion_expr::logical_plan::JoinConstraint; + +#[derive(Default)] +pub struct ReduceCrossJoin; + +impl ReduceCrossJoin { + #[allow(missing_docs)] + pub fn new() -> Self { + Self {} + } +} + +impl OptimizerRule for ReduceCrossJoin { + fn optimize( + &self, + plan: &LogicalPlan, + _optimizer_config: &mut OptimizerConfig, + ) -> Result<LogicalPlan> { + let mut possible_join_keys : Vec<(Column, Column)> = vec![]; + let mut all_join_keys = HashSet::new(); + + reduce_cross_join(self, plan, &mut possible_join_keys, &mut all_join_keys,) + } + + fn name(&self) -> &str { + "reduce_cross_join" + } +} + +/// Attempt to reduce cross joins to inner joins. +/// for queries: +/// 'select ... from a, b where a.x = b.y and b.xx = 100;' +/// 'select ... from a, b where (a.x = b.y and b.xx = 100) or (a.x = b.y and b.xx = 200);' +/// 'select ... from a, b, c where (a.x = b.y and b.xx = 100 and a.z = c.z) +/// or (a.x = b.y and b.xx = 200 and a.z=c.z);' +/// For above queries, the join predicate is available in filters and they are moved to +/// join nodes appropriately +/// This fix helps to improve the performance of TPCH Q19. issue#78 +/// +fn reduce_cross_join( + _optimizer: &ReduceCrossJoin, + plan: &LogicalPlan, + possible_join_keys: &mut Vec<(Column, Column)>, + all_join_keys: &mut HashSet<(Column, Column)>, +) -> Result<LogicalPlan> { + match plan { + LogicalPlan::Filter(Filter { input, predicate }) => { + extract_possible_join_keys(predicate, possible_join_keys); + let new_plan = reduce_cross_join(_optimizer, input, possible_join_keys, all_join_keys)?; + + // if there are no join keys then do nothing. + if all_join_keys.is_empty() { + Ok(plan.clone()) + } + else { + // remove join expressions from filter + match remove_join_expressions(predicate, all_join_keys)? { + Some(filter_expr) => { + Ok(LogicalPlan::Filter(Filter { + predicate: filter_expr, + input: Arc::new(new_plan), + })) + } + _ => Ok(new_plan) + } + } + } + LogicalPlan::CrossJoin(cross_join) => { + let left_plan = reduce_cross_join( + _optimizer, + &cross_join.left, + possible_join_keys, + all_join_keys, + )?; + let right_plan = reduce_cross_join( + _optimizer, + &cross_join.right, + possible_join_keys, + all_join_keys, + )?; + // can we find a match? + let left_schema = left_plan.schema(); + let right_schema = right_plan.schema(); + let mut join_keys = vec![]; + + for (l, r) in possible_join_keys { + if left_schema.field_from_column(l).is_ok() + && right_schema.field_from_column(r).is_ok() + && can_hash( + left_schema + .field_from_column(l) + .unwrap() + .data_type(), + ) + { + join_keys.push((l.clone(), r.clone())); + } else if left_schema.field_from_column(r).is_ok() + && right_schema.field_from_column(l).is_ok() + && can_hash( + left_schema + .field_from_column(r) + .unwrap() + .data_type(), + ) + { + join_keys.push((r.clone(), l.clone())); + } + } + + // if there are no join keys then do nothing. + if join_keys.is_empty() { + Ok(LogicalPlan::CrossJoin(CrossJoin { + left: Arc::new(left_plan), + right: Arc::new(right_plan), + schema: cross_join.schema.clone(), + })) + } + else { + // Keep track of join keys being pushed to Join nodes + all_join_keys.extend(join_keys.clone()); + + Ok(LogicalPlan::Join(Join { + left: Arc::new(left_plan), + right: Arc::new(right_plan), + join_type: JoinType::Inner, + join_constraint: JoinConstraint::On, + on: join_keys, + filter: None, + schema: cross_join.schema.clone(), + null_equals_null: false, + })) + } + } + _ => { + let expr = plan.expressions(); + + // apply the optimization to all inputs of the plan + let inputs = plan.inputs(); + let new_inputs = inputs + .iter() + .map(|plan| { + reduce_cross_join( + _optimizer, + plan, + possible_join_keys, + all_join_keys, + ) + }) + .collect::<Result<Vec<_>>>()?; + + from_plan(plan, &expr, &new_inputs) + } + } +} + +fn intersect( + accum: &mut Vec<(Column, Column)>, + vec1: &[(Column, Column)], + vec2: &[(Column, Column)], +) -> () { + + for x1 in vec1.iter() { + for x2 in vec2.iter() { + if x1.0 == x2.0 && x1.1 == x2.1 + || x1.1 == x2.0 && x1.0 == x2.1 + { + accum.push((x1.0.clone(), x1.1.clone())); + } + } + } + + () +} + +/// Extract join keys from a WHERE clause +fn extract_possible_join_keys( + expr: &Expr, + accum: &mut Vec<(Column, Column)>, +) -> () { + match expr { + Expr::BinaryExpr { left, op, right } => match op { + Operator::Eq => match (left.as_ref(), right.as_ref()) { + (Expr::Column(l), Expr::Column(r)) => { + // Ensure that we don't add the same Join keys multiple times + if !(accum.contains(&(l.clone(), r.clone())) || + accum.contains(&(r.clone(), l.clone()))) { + accum.push((l.clone(), r.clone())); + } + () + } + _ => (), + }, + Operator::And => { + extract_possible_join_keys(left, accum); + extract_possible_join_keys(right, accum) + }, + // Fix for issue#78 join predicates from inside of OR expr also pulled up properly. + Operator::Or => { Review Comment: Yes, I agree with @avantgardnerio -- I am fairly sure you are correct, but I would like to see a test that both removes any doubt as well as serves as protection against regression when / if this code is refactored in the future -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org