-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Move nested union optimization from plan builder to logical optimizer #7695
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
965c5e5
Add naive implementation of eliminate_nested_union
7196753
Remove union optimization from LogicalPlanBuilder::union
63645b2
Fix propagate_union_children_different_schema test
879d0f3
Add implementation of eliminate_one_union
ace9c6d
Simplified eliminate_nested_union test
bd6c4d4
Fix
c6dc425
Merge remote-tracking branch 'apache/main' into add_union_optimization
alamb 1d5e66a
clippy
alamb 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 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 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,211 @@ | ||
// 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 replace nested unions to single union. | ||
use crate::{OptimizerConfig, OptimizerRule}; | ||
use datafusion_common::Result; | ||
use datafusion_expr::logical_plan::{LogicalPlan, Union}; | ||
|
||
use crate::optimizer::ApplyOrder; | ||
use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema; | ||
use std::sync::Arc; | ||
|
||
#[derive(Default)] | ||
/// An optimization rule that replaces nested unions with a single union. | ||
pub struct EliminateNestedUnion; | ||
|
||
impl EliminateNestedUnion { | ||
#[allow(missing_docs)] | ||
pub fn new() -> Self { | ||
Self {} | ||
} | ||
} | ||
|
||
impl OptimizerRule for EliminateNestedUnion { | ||
fn try_optimize( | ||
&self, | ||
plan: &LogicalPlan, | ||
_config: &dyn OptimizerConfig, | ||
) -> Result<Option<LogicalPlan>> { | ||
// TODO: Add optimization for nested distinct unions. | ||
match plan { | ||
maruschin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
LogicalPlan::Union(Union { inputs, schema }) => { | ||
let inputs = inputs | ||
.iter() | ||
.flat_map(|plan| match plan.as_ref() { | ||
LogicalPlan::Union(Union { inputs, schema }) => inputs | ||
.iter() | ||
.map(|plan| { | ||
Arc::new( | ||
coerce_plan_expr_for_schema(plan, schema).unwrap(), | ||
) | ||
}) | ||
.collect::<Vec<_>>(), | ||
_ => vec![plan.clone()], | ||
}) | ||
.collect::<Vec<_>>(); | ||
|
||
Ok(Some(LogicalPlan::Union(Union { | ||
inputs, | ||
schema: schema.clone(), | ||
}))) | ||
} | ||
_ => Ok(None), | ||
} | ||
} | ||
|
||
fn name(&self) -> &str { | ||
"eliminate_nested_union" | ||
} | ||
|
||
fn apply_order(&self) -> Option<ApplyOrder> { | ||
Some(ApplyOrder::BottomUp) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::test::*; | ||
use arrow::datatypes::{DataType, Field, Schema}; | ||
use datafusion_expr::{col, logical_plan::table_scan}; | ||
|
||
fn schema() -> Schema { | ||
Schema::new(vec![ | ||
Field::new("id", DataType::Int32, false), | ||
Field::new("key", DataType::Utf8, false), | ||
Field::new("value", DataType::Float64, false), | ||
]) | ||
} | ||
|
||
fn assert_optimized_plan_equal(plan: &LogicalPlan, expected: &str) -> Result<()> { | ||
assert_optimized_plan_eq(Arc::new(EliminateNestedUnion::new()), plan, expected) | ||
} | ||
|
||
#[test] | ||
fn eliminate_nothing() -> Result<()> { | ||
let plan_builder = table_scan(Some("table"), &schema(), None)?; | ||
|
||
let plan = plan_builder | ||
.clone() | ||
.union(plan_builder.clone().build()?)? | ||
.build()?; | ||
|
||
let expected = "\ | ||
Union\ | ||
\n TableScan: table\ | ||
\n TableScan: table"; | ||
assert_optimized_plan_equal(&plan, expected) | ||
} | ||
|
||
#[test] | ||
fn eliminate_nested_union() -> Result<()> { | ||
let plan_builder = table_scan(Some("table"), &schema(), None)?; | ||
|
||
let plan = plan_builder | ||
.clone() | ||
.union(plan_builder.clone().build()?)? | ||
.union(plan_builder.clone().build()?)? | ||
.union(plan_builder.clone().build()?)? | ||
.build()?; | ||
|
||
let expected = "\ | ||
Union\ | ||
\n TableScan: table\ | ||
\n TableScan: table\ | ||
\n TableScan: table\ | ||
\n TableScan: table"; | ||
assert_optimized_plan_equal(&plan, expected) | ||
} | ||
|
||
// We don't need to use project_with_column_index in logical optimizer, | ||
// after LogicalPlanBuilder::union, we already have all equal expression aliases | ||
#[test] | ||
fn eliminate_nested_union_with_projection() -> Result<()> { | ||
let plan_builder = table_scan(Some("table"), &schema(), None)?; | ||
|
||
let plan = plan_builder | ||
.clone() | ||
.union( | ||
plan_builder | ||
.clone() | ||
.project(vec![col("id").alias("table_id"), col("key"), col("value")])? | ||
.build()?, | ||
)? | ||
.union( | ||
plan_builder | ||
.clone() | ||
.project(vec![col("id").alias("_id"), col("key"), col("value")])? | ||
.build()?, | ||
)? | ||
.build()?; | ||
|
||
let expected = "Union\ | ||
\n TableScan: table\ | ||
\n Projection: table.id AS id, table.key, table.value\ | ||
\n TableScan: table\ | ||
\n Projection: table.id AS id, table.key, table.value\ | ||
\n TableScan: table"; | ||
assert_optimized_plan_equal(&plan, expected) | ||
} | ||
|
||
#[test] | ||
fn eliminate_nested_union_with_type_cast_projection() -> Result<()> { | ||
let table_1 = table_scan( | ||
Some("table_1"), | ||
&Schema::new(vec![ | ||
Field::new("id", DataType::Int64, false), | ||
Field::new("key", DataType::Utf8, false), | ||
Field::new("value", DataType::Float64, false), | ||
]), | ||
None, | ||
)?; | ||
|
||
let table_2 = table_scan( | ||
Some("table_1"), | ||
&Schema::new(vec![ | ||
Field::new("id", DataType::Int32, false), | ||
Field::new("key", DataType::Utf8, false), | ||
Field::new("value", DataType::Float32, false), | ||
]), | ||
None, | ||
)?; | ||
|
||
let table_3 = table_scan( | ||
Some("table_1"), | ||
&Schema::new(vec![ | ||
Field::new("id", DataType::Int16, false), | ||
Field::new("key", DataType::Utf8, false), | ||
Field::new("value", DataType::Float32, false), | ||
]), | ||
None, | ||
)?; | ||
|
||
let plan = table_1 | ||
.union(table_2.build()?)? | ||
.union(table_3.build()?)? | ||
.build()?; | ||
|
||
let expected = "Union\ | ||
\n TableScan: table_1\ | ||
\n Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value\ | ||
\n TableScan: table_1\ | ||
\n Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value\ | ||
\n TableScan: table_1"; | ||
assert_optimized_plan_equal(&plan, expected) | ||
} | ||
} |
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.
at one point (maybe as a TODO) we probably should also remove unions that have only a single child since they are basically a no-op/pass-through. Not sure if this should be an separate optimizer rule or if this should be done in this rule.
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 believe the
EliminateOneUnion
rule, also added in this PR, handles the one union case