Apache DataFusion SQL Query Engine
ARROW-10685: [Rust] [DataFusion] Added support for Join on filter-pushdown optimizer.
Jorge C. Leitaoa1c979b3a8e8
diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 44a557b310..fde96b4a61 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -113,12 +113,7 @@ impl DataFrame for DataFrameImpl {right_cols: &[&str],) -> Result<Arc<dyn DataFrame>> {let plan = LogicalPlanBuilder::from(&self.plan)- .join(- Arc::new(right.to_logical_plan()),- join_type,- left_cols,- right_cols,- )?+ .join(&right.to_logical_plan(), join_type, left_cols, right_cols)?.build()?;Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))}diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex a88944448b..d182a5d845 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -186,7 +186,7 @@ impl LogicalPlanBuilder {/// Apply a joinpub fn join(&self,- right: Arc<LogicalPlan>,+ right: &LogicalPlan,join_type: JoinType,left_keys: &[&str],right_keys: &[&str],@@ -212,7 +212,7 @@ impl LogicalPlanBuilder {);Ok(Self::from(&LogicalPlan::Join {left: Arc::new(self.plan.clone()),- right,+ right: Arc::new(right.clone()),on: left_keys.iter().zip(right_keys.iter())diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rsindex 36c23dcf74..37573e6547 100644--- a/rust/datafusion/src/optimizer/filter_push_down.rs+++ b/rust/datafusion/src/optimizer/filter_push_down.rs@@ -14,156 +14,126 @@//! Filter Push Down optimizer rule ensures that filters are applied as early as possible in the plan-use crate::error::{DataFusionError, Result};+use crate::error::Result;use crate::logical_plan::Expr;use crate::logical_plan::{and, LogicalPlan};use crate::optimizer::optimizer::OptimizerRule;use crate::optimizer::utils;use std::{- collections::{BTreeMap, HashMap, HashSet},+ collections::{HashMap, HashSet},sync::Arc,};/// Filter Push Down optimizer rule pushes filter clauses down the plan+/// # Introduction+/// A filter-commutative operation is an operation whose result of filter(op(data)) = op(filter(data)).+/// An example of a filter-commutative operation is a projection; a counter-example is `limit`.///-/// This optimization looks for the maximum depth of each column in the plan where a filter can be applied and-/// re-writes the plan with filters on those locations.-/// It performs two passes on the plan:-/// 1. identify filters, which columns they use, and projections along the path-/// 2. move filters down, re-writing the expressions using the projections-/*-A filter-commutative operation is an operation whose result of filter(op(data)) = op(filter(data)).-An example of a filter-commutative operation is a projection; a counter-example is `limit`.--The filter-commutative property is column-specific. An aggregate grouped by A on SUM(B)-can commute with a filter that depends on A only, but does not commute with a filter that depends-on SUM(B).--A location in this module is identified by a number, depth, which is 0 for the last operation-and highest for the first operation (typically a scan).--This optimizer commutes filters with filter-commutative operations to push the filters-to the maximum possible depth, consequently re-writing the filter expressions by every-projection that changes the filter's expression.-- Filter: #b Gt Int64(10)- Projection: #a AS b--is optimized to-- Projection: #a AS b- Filter: #a Gt Int64(10) <--- changed from #b to #a--To perform such optimization, we first analyze the plan to identify three items:--1. Where are the filters located in the plan-2. Where are non-commutable operations' columns located in the plan (break_points)-3. Where are projections located in the plan--With this information, we re-write the plan by:--1. Computing the maximum possible depth of each column between breakpoints-2. Computing the maximum possible depth of each filter expression based on the columns it depends on-3. re-write the filter expression for every projection that it commutes with from its original depth to its max possible depth-4. recursively re-write the plan by deleting old filter expressions and adding new filter expressions on their max possible depth.-*/+/// The filter-commutative property is column-specific. An aggregate grouped by A on SUM(B)+/// can commute with a filter that depends on A only, but does not commute with a filter that depends+/// on SUM(B).+///+/// This optimizer commutes filters with filter-commutative operations to push the filters+/// the closest possible to the scans, re-writing the filter expressions by every+/// projection that changes the filter's expression.+///+/// Filter: #b Gt Int64(10)+/// Projection: #a AS b+///+/// is optimized to+///+/// Projection: #a AS b+/// Filter: #a Gt Int64(10) <--- changed from #b to #a+///+/// This performs a single pass trought the plan. When it passes trought a filter, it stores that filter,+/// and when it reaches a node that does not commute with it, it adds the filter to that place.+/// When it passes through a projection, it re-writes the filter's expression taking into accoun that projection.+/// When multiple filters would have been written, it `AND` their expressions into a single expression.pub struct FilterPushDown {}-impl OptimizerRule for FilterPushDown {- fn name(&self) -> &str {- return "filter_push_down";- }-- fn optimize(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan> {- let result = analyze_plan(plan, 0)?;- let break_points = result.break_points.clone();-- // get max depth over all breakpoints- let max_depth = break_points.keys().max();- if max_depth.is_none() {- // it is unlikely that the plan is correct without break points as all scans- // adds breakpoints. We just return the plan and let others handle the error- return Ok(plan.clone());- }- let max_depth = *max_depth.unwrap(); // unwrap is safe by previous if-- // construct optimized position of each of the new filters- // E.g. when we have a filter (c1 + c2 > 2), c1's max depth is 10 and c2 is 11, we- // can push the filter to depth 10- let mut new_filters: BTreeMap<usize, Expr> = BTreeMap::new();- for (filter_depth, expr) in result.filters {- // get all columns on the filter expression- let mut filter_columns: HashSet<String> = HashSet::new();- utils::expr_to_column_names(&expr, &mut filter_columns)?;-- // identify the depths that are filter-commutable with this filter- let mut new_depth = filter_depth;- for depth in filter_depth..max_depth {- if let Some(break_columns) = break_points.get(&depth) {- if filter_columns- .intersection(break_columns)- .peekable()- .peek()- .is_none()- {- new_depth += 1- } else {- // non-commutable: can't advance any further- break;- }- } else {- new_depth += 1- }- }+#[derive(Debug, Clone, Default)]+struct State {+ // (predicate, columns on the predicate)+ filters: Vec<(Expr, HashSet<String>)>,+}- // re-write the new filters based on all projections that it crossed.- // E.g. in `Filter: #b\n Projection: #a > 1 as b`, we can swap them, but the filter must be "#a > 1"- let mut new_expression = expr.clone();- for depth_i in filter_depth..new_depth {- if let Some(projection) = result.projections.get(&depth_i) {- new_expression = rewrite(&new_expression, projection)?;- }- }+/// builds a new [LogicalPlan] from `plan` by issuing new [LogicalPlan::Filter] if any of the filters+/// in `state` depend on the columns `used_columns`.+fn issue_filters(+ mut state: State,+ used_columns: HashSet<String>,+ plan: &LogicalPlan,+) -> Result<LogicalPlan> {+ // pick all filters in the current state that depend on any of `used_columns`+ let (predicates, predicate_columns): (Vec<_>, Vec<_>) = state+ .filters+ .iter()+ .filter(|(_, columns)| {+ columns+ .intersection(&used_columns)+ .collect::<HashSet<_>>()+ .len()+ > 0+ })+ .map(|&(ref a, ref b)| (a, b))+ .unzip();++ if predicates.is_empty() {+ // all filters can be pushed down => optimize inputs and return new plan+ let new_inputs = utils::inputs(&plan)+ .iter()+ .map(|input| optimize(input, state.clone()))+ .collect::<Result<Vec<_>>>()?;++ let expr = utils::expressions(&plan);+ return utils::from_plan(&plan, &expr, &new_inputs);+ }- // AND filter expressions that would be placed on the same depth- if let Some(existing_expression) = new_filters.get(&new_depth) {- new_expression = and(existing_expression, &new_expression)- }- new_filters.insert(new_depth, new_expression);- }+ // reduce filters to a single filter with an AND+ let predicate = predicates+ .iter()+ .skip(1)+ .fold(predicates[0].clone(), |acc, predicate| and(&acc, predicate));++ // add a new filter node with the predicates+ let plan = LogicalPlan::Filter {+ predicate: predicate.clone(),+ input: Arc::new(plan.clone()),+ };++ // remove all filters from the state that cannot be pushed further down+ state.filters = state+ .filters+ .iter()+ .filter(|(_, columns)| !predicate_columns.contains(&columns))+ .cloned()+ .collect::<Vec<_>>();- optimize_plan(plan, &new_filters, 0)- }-}+ // continue optimization over all input nodes by cloning the current state (i.e. each node is independent)+ let new_inputs = utils::inputs(&plan)+ .iter()+ .map(|input| optimize(input, state.clone()))+ .collect::<Result<Vec<_>>>()?;-/// The result of a plan analysis suitable to perform a filter push down optimization-// BTreeMap are ordered, which ensures stability in ordered operations.-// Also, most inserts here are at the end-struct AnalysisResult {- /// maps the depths of non filter-commutative nodes to their columns- /// depths not in here indicate that the node is commutative- pub break_points: BTreeMap<usize, HashSet<String>>,- /// maps the depths of filter nodes to expressions- pub filters: BTreeMap<usize, Expr>,- /// maps the depths of projection nodes to their expressions- pub projections: BTreeMap<usize, HashMap<String, Expr>>,+ let expr = utils::expressions(&plan);+ utils::from_plan(&plan, &expr, &new_inputs)}-/// Recursively transverses the logical plan looking for depths that break filter pushdown-fn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {+fn optimize(plan: &LogicalPlan, mut state: State) -> Result<LogicalPlan> {match plan {LogicalPlan::Filter { input, predicate } => {- let mut result = analyze_plan(&input, depth + 1)?;- result.filters.insert(depth, predicate.clone());- Ok(result)+ let mut columns: HashSet<String> = HashSet::new();+ utils::expr_to_column_names(predicate, &mut columns)?;+ // collect the predicate+ state.filters.push((predicate.clone(), columns));+ optimize(input, state)}LogicalPlan::Projection {input,expr,schema,} => {- let mut result = analyze_plan(&input, depth + 1)?;-+ // A projection is filter-commutable, but re-writes all predicate expressions// collect projection.let mut projection = HashMap::new();schema.fields().iter().enumerate().for_each(|(i, field)| {@@ -175,95 +145,81 @@ fn analyze_plan(plan: &LogicalPlan, depth: usize) -> Result<AnalysisResult> {projection.insert(field.name().clone(), expr);});- result.projections.insert(depth, projection);- Ok(result)++ // re-write all filters based on this projection+ // E.g. in `Filter: #b\n Projection: #a > 1 as b`, we can swap them, but the filter must be "#a > 1"+ for (predicate, columns) in state.filters.iter_mut() {+ *predicate = rewrite(predicate, &projection)?;++ columns.clear();+ utils::expr_to_column_names(predicate, columns)?;+ }++ // optimize inner+ let new_input = optimize(input, state)?;++ utils::from_plan(&plan, &expr, &vec![new_input])}LogicalPlan::Aggregate {input, aggr_expr, ..} => {- let mut result = analyze_plan(&input, depth + 1)?;+ // An aggregate's aggreagate columns are _not_ filter-commutable => collect these:+ // * columns whose aggregation expression depends on+ // * the aggregation columns themselves// construct set of columns that `aggr_expr` depends on- let mut agg_columns = HashSet::new();- utils::exprlist_to_column_names(aggr_expr, &mut agg_columns)?;+ let mut used_columns = HashSet::new();+ utils::exprlist_to_column_names(aggr_expr, &mut used_columns)?;- // collect all columns that break at this depth:- // * columns whose aggregation expression depends on- // * the aggregation columns themselves- let mut columns = agg_columns.iter().cloned().collect::<HashSet<_>>();let agg_columns = aggr_expr.iter().map(|x| x.name(input.schema())).collect::<Result<HashSet<_>>>()?;- columns.extend(agg_columns);- result.break_points.insert(depth, columns);+ used_columns.extend(agg_columns);- Ok(result)+ issue_filters(state, used_columns, plan)+ }+ LogicalPlan::Sort { .. } => {+ // sort is filter-commutable+ issue_filters(state, HashSet::new(), plan)}- LogicalPlan::Sort { input, .. } => analyze_plan(&input, depth + 1),LogicalPlan::Limit { input, .. } => {- let mut result = analyze_plan(&input, depth + 1)?;-- // collect all columns that break at this depth- let columns = input+ // limit is _not_ filter-commutable => collect all columns from its input+ let used_columns = input.schema().fields().iter().map(|f| f.name().clone()).collect::<HashSet<_>>();- result.break_points.insert(depth, columns);- Ok(result)+ issue_filters(state, used_columns, plan)}- LogicalPlan::Extension { node } => {- let inputs = node.inputs();-- let mut result = match inputs.len() {- 0 => AnalysisResult {- break_points: BTreeMap::new(),- filters: BTreeMap::new(),- projections: BTreeMap::new(),- },- 1 => analyze_plan(inputs[0], depth + 1)?,- _ => {- return Err(DataFusionError::NotImplemented(- "Not Yet Implemented: Predicate pushdown for multiple inputs"- .into(),- ))- }- };-- // collect all columns that break at this depth- let columns = node- .schema()- .fields()- .iter()- .map(|f| f.name().clone())- .collect::<HashSet<_>>();- result.break_points.insert(depth, columns);-- Ok(result)+ LogicalPlan::Join { .. } => {+ // join is filter-commutable+ issue_filters(state, HashSet::new(), plan)}-- // all other plans add breaks to all their columns to indicate that filters can't proceed further._ => {- let columns = plan+ // all other plans are _not_ filter-commutable+ let used_columns = plan.schema().fields().iter().map(|f| f.name().clone()).collect::<HashSet<_>>();- let mut break_points = BTreeMap::new();-- break_points.insert(depth, columns);- Ok(AnalysisResult {- break_points,- filters: BTreeMap::new(),- projections: BTreeMap::new(),- })+ issue_filters(state, used_columns, plan)}}}+impl OptimizerRule for FilterPushDown {+ fn name(&self) -> &str {+ return "filter_push_down";+ }++ fn optimize(&mut self, plan: &LogicalPlan) -> Result<LogicalPlan> {+ optimize(plan, State::default())+ }+}+impl FilterPushDown {#[allow(missing_docs)]pub fn new() -> Self {@@ -271,43 +227,6 @@ impl FilterPushDown {}}-/// Returns a re-written logical plan where all old filters are removed and the new ones are added.-fn optimize_plan(- plan: &LogicalPlan,- new_filters: &BTreeMap<usize, Expr>,- depth: usize,-) -> Result<LogicalPlan> {- // optimize the plan recursively:- let new_plan = match plan {- LogicalPlan::Filter { input, .. } => {- // ignore old filters- Ok(optimize_plan(&input, new_filters, depth + 1)?)- }- _ => {- // all other nodes are copied, optimizing recursively.- let expr = utils::expressions(plan);-- let inputs = utils::inputs(plan);- let new_inputs = inputs- .iter()- .map(|plan| optimize_plan(plan, new_filters, depth + 1))- .collect::<Result<Vec<_>>>()?;-- utils::from_plan(plan, &expr, &new_inputs)- }- }?;-- // if a new filter is to be applied, apply it- if let Some(expr) = new_filters.get(&depth) {- return Ok(LogicalPlan::Filter {- predicate: expr.clone(),- input: Arc::new(new_plan),- });- } else {- Ok(new_plan)- }-}-/// replaces columns by its name on the projection.fn rewrite(expr: &Expr, projection: &HashMap<String, Expr>) -> Result<Expr> {let expressions = utils::expr_sub_expressions(&expr)?;@@ -332,9 +251,9 @@ fn rewrite(expr: &Expr, projection: &HashMap<String, Expr>) -> Result<Expr> {#[cfg(test)]mod tests {use super::*;- use crate::logical_plan::col;use crate::logical_plan::{lit, sum, Expr, LogicalPlanBuilder, Operator};use crate::test::*;+ use crate::{logical_plan::col, prelude::JoinType};fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {let mut rule = FilterPushDown::new();@@ -672,4 +591,39 @@ mod tests {assert_optimized_plan_eq(&plan, expected);Ok(())}++ #[test]+ fn filters_join() -> Result<()> {+ let table_scan = test_table_scan()?;+ let left = LogicalPlanBuilder::from(&table_scan).build()?;+ let right = LogicalPlanBuilder::from(&table_scan)+ .project(vec![col("a")])?+ .build()?;+ let plan = LogicalPlanBuilder::from(&left)+ .join(&right, JoinType::Inner, &["a"], &["a"])?+ .filter(col("a").lt_eq(lit(1i64)))?+ .build()?;++ // not part of the test, just good to know:+ assert_eq!(+ format!("{:?}", plan),+ "\+ Filter: #a LtEq Int64(1)\+ \n Join: a = a\+ \n TableScan: test projection=None\+ \n Projection: #a\+ \n TableScan: test projection=None"+ );++ // filter sent to side before the join+ let expected = "\+ Join: a = a\+ \n Filter: #a LtEq Int64(1)\+ \n TableScan: test projection=None\+ \n Projection: #a\+ \n Filter: #a LtEq Int64(1)\+ \n TableScan: test projection=None";+ assert_optimized_plan_eq(&plan, expected);+ Ok(())+ }}