Skip to content

Apache DataFusion SQL Query Engine

NestedLoopJoin Projection Pushdown (#14120)

Jay Zhan05f4e5a7475c
diff --git a/datafusion/core/src/physical_optimizer/projection_pushdown.rs b/datafusion/core/src/physical_optimizer/projection_pushdown.rs
index d2d35c3877..2f1cf3a8e6 100644
--- a/datafusion/core/src/physical_optimizer/projection_pushdown.rs
+++ b/datafusion/core/src/physical_optimizer/projection_pushdown.rs
@@ -51,6 +51,7 @@ use datafusion_physical_expr::{
utils::collect_columns, Partitioning, PhysicalExpr, PhysicalExprRef,
PhysicalSortExpr, PhysicalSortRequirement,
};
+use datafusion_physical_plan::joins::utils::{JoinOn, JoinOnRef};
use datafusion_physical_plan::streaming::StreamingTableExec;
use datafusion_physical_plan::union::UnionExec;
@@ -137,14 +138,11 @@ pub fn remove_unnecessary_projections(
} else if let Some(union) = input.downcast_ref::<UnionExec>() {
try_pushdown_through_union(projection, union)?
} else if let Some(hash_join) = input.downcast_ref::<HashJoinExec>() {
- try_pushdown_through_hash_join(projection, hash_join)?.map_or_else(
- || try_embed_projection(projection, hash_join),
- |e| Ok(Some(e)),
- )?
+ try_pushdown_through_hash_join(projection, hash_join)?
} else if let Some(cross_join) = input.downcast_ref::<CrossJoinExec>() {
try_swapping_with_cross_join(projection, cross_join)?
} else if let Some(nl_join) = input.downcast_ref::<NestedLoopJoinExec>() {
- try_swapping_with_nested_loop_join(projection, nl_join)?
+ try_pushdown_through_nested_loop_join(projection, nl_join)?
} else if let Some(sm_join) = input.downcast_ref::<SortMergeJoinExec>() {
try_swapping_with_sort_merge_join(projection, sm_join)?
} else if let Some(sym_join) = input.downcast_ref::<SymmetricHashJoinExec>() {
@@ -549,6 +547,12 @@ impl EmbeddedProjection for HashJoinExec {
}
}
+impl EmbeddedProjection for NestedLoopJoinExec {
+ fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
+ self.with_projection(projection)
+ }
+}
+
impl EmbeddedProjection for FilterExec {
fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
self.with_projection(projection)
@@ -626,53 +630,44 @@ fn collect_column_indices(exprs: &[(Arc<dyn PhysicalExpr>, String)]) -> Vec<usiz
indices
}
-/// Tries to push `projection` down through `hash_join`. If possible, performs the
-/// pushdown and returns a new [`HashJoinExec`] as the top plan which has projections
-/// as its children. Otherwise, returns `None`.
-fn try_pushdown_through_hash_join(
- projection: &ProjectionExec,
- hash_join: &HashJoinExec,
-) -> Result<Option<Arc<dyn ExecutionPlan>>> {
- // TODO: currently if there is projection in HashJoinExec, we can't push down projection to left or right input. Maybe we can pushdown the mixed projection later.
- if hash_join.contain_projection() {
- return Ok(None);
- }
+struct JoinData {
+ projected_left_child: ProjectionExec,
+ projected_right_child: ProjectionExec,
+ join_filter: Option<JoinFilter>,
+ join_on: JoinOn,
+}
- // Convert projected expressions to columns. We can not proceed if this is
- // not possible.
+fn try_pushdown_through_join(
+ projection: &ProjectionExec,
+ join_left: &Arc<dyn ExecutionPlan>,
+ join_right: &Arc<dyn ExecutionPlan>,
+ join_on: JoinOnRef,
+ schema: SchemaRef,
+ filter: Option<&JoinFilter>,
+) -> Result<Option<JoinData>> {
+ // Convert projected expressions to columns. We can not proceed if this is not possible.
let Some(projection_as_columns) = physical_to_column_exprs(projection.expr()) else {
return Ok(None);
};
- let (far_right_left_col_ind, far_left_right_col_ind) = join_table_borders(
- hash_join.left().schema().fields().len(),
- &projection_as_columns,
- );
+ let (far_right_left_col_ind, far_left_right_col_ind) =
+ join_table_borders(join_left.schema().fields().len(), &projection_as_columns);
if !join_allows_pushdown(
&projection_as_columns,
- &hash_join.schema(),
+ &schema,
far_right_left_col_ind,
far_left_right_col_ind,
) {
return Ok(None);
}
- let Some(new_on) = update_join_on(
- &projection_as_columns[0..=far_right_left_col_ind as _],
- &projection_as_columns[far_left_right_col_ind as _..],
- hash_join.on(),
- hash_join.left().schema().fields().len(),
- ) else {
- return Ok(None);
- };
-
- let new_filter = if let Some(filter) = hash_join.filter() {
+ let new_filter = if let Some(filter) = filter {
match update_join_filter(
&projection_as_columns[0..=far_right_left_col_ind as _],
&projection_as_columns[far_left_right_col_ind as _..],
filter,
- hash_join.left().schema().fields().len(),
+ join_left.schema().fields().len(),
) {
Some(updated_filter) => Some(updated_filter),
None => return Ok(None),
@@ -681,72 +676,116 @@ fn try_pushdown_through_hash_join(
None
};
+ let Some(new_on) = update_join_on(
+ &projection_as_columns[0..=far_right_left_col_ind as _],
+ &projection_as_columns[far_left_right_col_ind as _..],
+ join_on,
+ join_left.schema().fields().len(),
+ ) else {
+ return Ok(None);
+ };
+
let (new_left, new_right) = new_join_children(
&projection_as_columns,
far_right_left_col_ind,
far_left_right_col_ind,
- hash_join.left(),
- hash_join.right(),
+ join_left,
+ join_right,
)?;
- Ok(Some(Arc::new(HashJoinExec::try_new(
- Arc::new(new_left),
- Arc::new(new_right),
- new_on,
- new_filter,
- hash_join.join_type(),
- hash_join.projection.clone(),
- *hash_join.partition_mode(),
- hash_join.null_equals_null,
- )?)))
+ Ok(Some(JoinData {
+ projected_left_child: new_left,
+ projected_right_child: new_right,
+ join_filter: new_filter,
+ join_on: new_on,
+ }))
}
-/// Tries to swap the projection with its input [`CrossJoinExec`]. If it can be done,
-/// it returns the new swapped version having the [`CrossJoinExec`] as the top plan.
-/// Otherwise, it returns None.
-fn try_swapping_with_cross_join(
+/// Tries to push `projection` down through `nested_loop_join`. If possible, performs the
+/// pushdown and returns a new [`NestedLoopJoinExec`] as the top plan which has projections
+/// as its children. Otherwise, returns `None`.
+fn try_pushdown_through_nested_loop_join(
projection: &ProjectionExec,
- cross_join: &CrossJoinExec,
+ nl_join: &NestedLoopJoinExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
- // Convert projected PhysicalExpr's to columns. If not possible, we cannot proceed.
- let Some(projection_as_columns) = physical_to_column_exprs(projection.expr()) else {
+ // TODO: currently if there is projection in NestedLoopJoinExec, we can't push down projection to left or right input. Maybe we can pushdown the mixed projection later.
+ if nl_join.contains_projection() {
return Ok(None);
- };
+ }
- let (far_right_left_col_ind, far_left_right_col_ind) = join_table_borders(
- cross_join.left().schema().fields().len(),
- &projection_as_columns,
- );
+ if let Some(JoinData {
+ projected_left_child,
+ projected_right_child,
+ join_filter,
+ ..
+ }) = try_pushdown_through_join(
+ projection,
+ nl_join.left(),
+ nl_join.right(),
+ &[],
+ nl_join.schema(),
+ nl_join.filter(),
+ )? {
+ Ok(Some(Arc::new(NestedLoopJoinExec::try_new(
+ Arc::new(projected_left_child),
+ Arc::new(projected_right_child),
+ join_filter,
+ nl_join.join_type(),
+ // Returned early if projection is not None
+ None,
+ )?)))
+ } else {
+ try_embed_projection(projection, nl_join)
+ }
+}
- if !join_allows_pushdown(
- &projection_as_columns,
- &cross_join.schema(),
- far_right_left_col_ind,
- far_left_right_col_ind,
- ) {
+/// Tries to push `projection` down through `hash_join`. If possible, performs the
+/// pushdown and returns a new [`HashJoinExec`] as the top plan which has projections
+/// as its children. Otherwise, returns `None`.
+fn try_pushdown_through_hash_join(
+ projection: &ProjectionExec,
+ hash_join: &HashJoinExec,
+) -> Result<Option<Arc<dyn ExecutionPlan>>> {
+ // TODO: currently if there is projection in HashJoinExec, we can't push down projection to left or right input. Maybe we can pushdown the mixed projection later.
+ if hash_join.contains_projection() {
return Ok(None);
}
- let (new_left, new_right) = new_join_children(
- &projection_as_columns,
- far_right_left_col_ind,
- far_left_right_col_ind,
- cross_join.left(),
- cross_join.right(),
- )?;
-
- Ok(Some(Arc::new(CrossJoinExec::new(
- Arc::new(new_left),
- Arc::new(new_right),
- ))))
+ if let Some(JoinData {
+ projected_left_child,
+ projected_right_child,
+ join_filter,
+ join_on,
+ }) = try_pushdown_through_join(
+ projection,
+ hash_join.left(),
+ hash_join.right(),
+ hash_join.on(),
+ hash_join.schema(),
+ hash_join.filter(),
+ )? {
+ Ok(Some(Arc::new(HashJoinExec::try_new(
+ Arc::new(projected_left_child),
+ Arc::new(projected_right_child),
+ join_on,
+ join_filter,
+ hash_join.join_type(),
+ // Returned early if projection is not None
+ None,
+ *hash_join.partition_mode(),
+ hash_join.null_equals_null,
+ )?)))
+ } else {
+ try_embed_projection(projection, hash_join)
+ }
}
-/// Tries to swap the projection with its input [`NestedLoopJoinExec`]. If it can be done,
-/// it returns the new swapped version having the [`NestedLoopJoinExec`] as the top plan.
+/// Tries to swap the projection with its input [`CrossJoinExec`]. If it can be done,
+/// it returns the new swapped version having the [`CrossJoinExec`] as the top plan.
/// Otherwise, it returns None.
-fn try_swapping_with_nested_loop_join(
+fn try_swapping_with_cross_join(
projection: &ProjectionExec,
- nl_join: &NestedLoopJoinExec,
+ cross_join: &CrossJoinExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
// Convert projected PhysicalExpr's to columns. If not possible, we cannot proceed.
let Some(projection_as_columns) = physical_to_column_exprs(projection.expr()) else {
@@ -754,47 +793,31 @@ fn try_swapping_with_nested_loop_join(
};
let (far_right_left_col_ind, far_left_right_col_ind) = join_table_borders(
- nl_join.left().schema().fields().len(),
+ cross_join.left().schema().fields().len(),
&projection_as_columns,
);
if !join_allows_pushdown(
&projection_as_columns,
- &nl_join.schema(),
+ &cross_join.schema(),
far_right_left_col_ind,
far_left_right_col_ind,
) {
return Ok(None);
}
- let new_filter = if let Some(filter) = nl_join.filter() {
- match update_join_filter(
- &projection_as_columns[0..=far_right_left_col_ind as _],
- &projection_as_columns[far_left_right_col_ind as _..],
- filter,
- nl_join.left().schema().fields().len(),
- ) {
- Some(updated_filter) => Some(updated_filter),
- None => return Ok(None),
- }
- } else {
- None
- };
-
let (new_left, new_right) = new_join_children(
&projection_as_columns,
far_right_left_col_ind,
far_left_right_col_ind,
- nl_join.left(),
- nl_join.right(),
+ cross_join.left(),
+ cross_join.right(),
)?;
- Ok(Some(Arc::new(NestedLoopJoinExec::try_new(
+ Ok(Some(Arc::new(CrossJoinExec::new(
Arc::new(new_left),
Arc::new(new_right),
- new_filter,
- nl_join.join_type(),
- )?)))
+ ))))
}
/// Tries to swap the projection with its input [`SortMergeJoinExec`]. If it can be done,
@@ -1345,7 +1368,7 @@ mod tests {
ColumnarValue, Operator, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
};
use datafusion_physical_expr::expressions::{
- BinaryExpr, CaseExpr, CastExpr, NegativeExpr,
+ binary, col, BinaryExpr, CaseExpr, CastExpr, NegativeExpr,
};
use datafusion_physical_expr::ScalarFunctionExpr;
use datafusion_physical_plan::joins::PartitionMode;
@@ -2402,6 +2425,73 @@ mod tests {
Ok(())
}
+ #[test]
+ fn test_nested_loop_join_after_projection() -> Result<()> {
+ let left_csv = create_simple_csv_exec();
+ let right_csv = create_simple_csv_exec();
+
+ let col_left_a = col("a", &left_csv.schema())?;
+ let col_right_b = col("b", &right_csv.schema())?;
+ let col_left_c = col("c", &left_csv.schema())?;
+ // left_a < right_b
+ let filter_expr =
+ binary(col_left_a, Operator::Lt, col_right_b, &Schema::empty())?;
+ let filter_column_indices = vec![
+ ColumnIndex {
+ index: 0,
+ side: JoinSide::Left,
+ },
+ ColumnIndex {
+ index: 1,
+ side: JoinSide::Right,
+ },
+ ColumnIndex {
+ index: 2,
+ side: JoinSide::Right,
+ },
+ ];
+ let filter_schema = Schema::new(vec![
+ Field::new("a", DataType::Int32, true),
+ Field::new("b", DataType::Int32, true),
+ Field::new("c", DataType::Int32, true),
+ ]);
+
+ let join: Arc<dyn ExecutionPlan> = Arc::new(NestedLoopJoinExec::try_new(
+ left_csv,
+ right_csv,
+ Some(JoinFilter::new(
+ filter_expr,
+ filter_column_indices,
+ filter_schema,
+ )),
+ &JoinType::Inner,
+ None,
+ )?);
+
+ let projection: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
+ vec![(col_left_c, "c".to_string())],
+ Arc::clone(&join),
+ )?);
+ let initial = get_plan_string(&projection);
+ let expected_initial = [
+ "ProjectionExec: expr=[c@2 as c]",
+ " NestedLoopJoinExec: join_type=Inner, filter=a@0 < b@1",
+ " CsvExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], has_header=false",
+ " CsvExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], has_header=false",
+ ];
+ assert_eq!(initial, expected_initial);
+
+ let after_optimize =
+ ProjectionPushdown::new().optimize(projection, &ConfigOptions::new())?;
+ let expected = [
+ "NestedLoopJoinExec: join_type=Inner, filter=a@0 < b@1, projection=[c@2]",
+ " CsvExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], has_header=false",
+ " CsvExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], has_header=false",
+ ];
+ assert_eq!(get_plan_string(&after_optimize), expected);
+ Ok(())
+ }
+
#[test]
fn test_hash_join_after_projection() -> Result<()> {
// sql like
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index b0232abbe4..77bf4bb71d 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -1110,6 +1110,7 @@ impl DefaultPhysicalPlanner {
physical_right,
join_filter,
join_type,
+ None,
)?)
}
} else if session_state.config().target_partitions() > 1
diff --git a/datafusion/core/tests/fuzz_cases/join_fuzz.rs b/datafusion/core/tests/fuzz_cases/join_fuzz.rs
index b331388f4f..04eb48e41c 100644
--- a/datafusion/core/tests/fuzz_cases/join_fuzz.rs
+++ b/datafusion/core/tests/fuzz_cases/join_fuzz.rs
@@ -486,7 +486,7 @@ impl JoinFuzzTestCase {
let filter = JoinFilter::new(expression, column_indices, intermediate_schema);
Arc::new(
- NestedLoopJoinExec::try_new(left, right, Some(filter), &self.join_type)
+ NestedLoopJoinExec::try_new(left, right, Some(filter), &self.join_type, None)
.unwrap(),
)
}
diff --git a/datafusion/physical-optimizer/src/join_selection.rs b/datafusion/physical-optimizer/src/join_selection.rs
index 1cd05933be..5f7f1f396a 100644
--- a/datafusion/physical-optimizer/src/join_selection.rs
+++ b/datafusion/physical-optimizer/src/join_selection.rs
@@ -1055,6 +1055,7 @@ mod tests_statistical {
Arc::clone(&small),
nl_join_filter(),
&join_type,
+ None,
)
.unwrap(),
);
@@ -1123,6 +1124,7 @@ mod tests_statistical {
Arc::clone(&small),
nl_join_filter(),
&join_type,
+ None,
)
.unwrap(),
);
diff --git a/datafusion/physical-plan/src/joins/hash_join.rs b/datafusion/physical-plan/src/joins/hash_join.rs
index 832703b743..8ccefb0397 100644
--- a/datafusion/physical-plan/src/joins/hash_join.rs
+++ b/datafusion/physical-plan/src/joins/hash_join.rs
@@ -26,7 +26,7 @@ use std::{any::Any, vec};
use super::utils::{
asymmetric_join_output_partitioning, get_final_indices_from_shared_bitmap,
- reorder_output_after_swap,
+ reorder_output_after_swap, swap_join_projection,
};
use super::{
utils::{OnceAsync, OnceFut},
@@ -477,7 +477,7 @@ impl HashJoinExec {
}
/// Return whether the join contains a projection
- pub fn contain_projection(&self) -> bool {
+ pub fn contains_projection(&self) -> bool {
self.projection.is_some()
}
@@ -626,38 +626,6 @@ impl HashJoinExec {
}
}
-/// This function swaps the given join's projection.
-fn swap_join_projection(
- left_schema_len: usize,
- right_schema_len: usize,
- projection: Option<&Vec<usize>>,
- join_type: &JoinType,
-) -> Option<Vec<usize>> {
- match join_type {
- // For Anti/Semi join types, projection should remain unmodified,
- // since these joins output schema remains the same after swap
- JoinType::LeftAnti
- | JoinType::LeftSemi
- | JoinType::RightAnti
- | JoinType::RightSemi => projection.cloned(),
-
- _ => projection.map(|p| {
- p.iter()
- .map(|i| {
- // If the index is less than the left schema length, it is from
- // the left schema, so we add the right schema length to it.
- // Otherwise, it is from the right schema, so we subtract the left
- // schema length from it.
- if *i < left_schema_len {
- *i + right_schema_len
- } else {
- *i - left_schema_len
- }
- })
- .collect()
- }),
- }
-}
impl DisplayAs for HashJoinExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
match t {
@@ -666,7 +634,7 @@ impl DisplayAs for HashJoinExec {
|| "".to_string(),
|f| format!(", filter={}", f.expression()),
);
- let display_projections = if self.contain_projection() {
+ let display_projections = if self.contains_projection() {
format!(
", projection=[{}]",
self.projection
diff --git a/datafusion/physical-plan/src/joins/nested_loop_join.rs b/datafusion/physical-plan/src/joins/nested_loop_join.rs
index 1366776c33..f416694e38 100644
--- a/datafusion/physical-plan/src/joins/nested_loop_join.rs
+++ b/datafusion/physical-plan/src/joins/nested_loop_join.rs
@@ -25,10 +25,11 @@ use std::task::Poll;
use super::utils::{
asymmetric_join_output_partitioning, get_final_indices_from_shared_bitmap,
- need_produce_result_in_final, reorder_output_after_swap, BatchSplitter,
- BatchTransformer, NoopBatchTransformer, StatefulStreamResult,
+ need_produce_result_in_final, reorder_output_after_swap, swap_join_projection,
+ BatchSplitter, BatchTransformer, NoopBatchTransformer, StatefulStreamResult,
};
use crate::coalesce_partitions::CoalescePartitionsExec;
+use crate::common::can_project;
use crate::execution_plan::{boundedness_from_children, EmissionType};
use crate::joins::utils::{
adjust_indices_by_join_type, apply_join_filter_to_indices, build_batch_from_indices,
@@ -47,12 +48,14 @@ use arrow::compute::concat_batches;
use arrow::datatypes::{Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::{
- exec_datafusion_err, internal_err, JoinSide, Result, Statistics,
+ exec_datafusion_err, internal_err, project_schema, JoinSide, Result, Statistics,
};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::TaskContext;
use datafusion_expr::JoinType;
-use datafusion_physical_expr::equivalence::join_equivalence_properties;
+use datafusion_physical_expr::equivalence::{
+ join_equivalence_properties, ProjectionMapping,
+};
use crate::joins::SharedBitmapBuilder;
use futures::{ready, Stream, StreamExt, TryStreamExt};
@@ -153,7 +156,7 @@ pub struct NestedLoopJoinExec {
/// How the join is performed
pub(crate) join_type: JoinType,
/// The schema once the join is applied
- schema: SchemaRef,
+ join_schema: SchemaRef,
/// Future that consumes left input and buffers it in memory
///
/// This structure is *shared* across all output streams.
@@ -163,6 +166,9 @@ pub struct NestedLoopJoinExec {
inner_table: OnceAsync<JoinLeftData>,
/// Information of index and left / right placement of columns
column_indices: Vec<ColumnIndex>,
+ /// Projection to apply to the output of the join
+ projection: Option<Vec<usize>>,
+
/// Execution metrics
metrics: ExecutionPlanMetricsSet,
/// Cache holding plan properties like equivalences, output partitioning etc.
@@ -176,24 +182,31 @@ impl NestedLoopJoinExec {
right: Arc<dyn ExecutionPlan>,
filter: Option<JoinFilter>,
join_type: &JoinType,
+ projection: Option<Vec<usize>>,
) -> Result<Self> {
let left_schema = left.schema();
let right_schema = right.schema();
check_join_is_valid(&left_schema, &right_schema, &[])?;
- let (schema, column_indices) =
+ let (join_schema, column_indices) =
build_join_schema(&left_schema, &right_schema, join_type);
- let schema = Arc::new(schema);
- let cache =
- Self::compute_properties(&left, &right, Arc::clone(&schema), *join_type);
+ let join_schema = Arc::new(join_schema);
+ let cache = Self::compute_properties(
+ &left,
+ &right,
+ Arc::clone(&join_schema),
+ *join_type,
+ projection.as_ref(),
+ )?;
Ok(NestedLoopJoinExec {
left,
right,
filter,
join_type: *join_type,
- schema,
+ join_schema,
inner_table: Default::default(),
column_indices,
+ projection,
metrics: Default::default(),
cache,
})
@@ -219,26 +232,31 @@ impl NestedLoopJoinExec {
&self.join_type
}
+ pub fn projection(&self) -> Option<&Vec<usize>> {
+ self.projection.as_ref()
+ }
+
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
fn compute_properties(
left: &Arc<dyn ExecutionPlan>,
right: &Arc<dyn ExecutionPlan>,
schema: SchemaRef,
join_type: JoinType,
- ) -> PlanProperties {
+ projection: Option<&Vec<usize>>,
+ ) -> Result<PlanProperties> {
// Calculate equivalence properties:
- let eq_properties = join_equivalence_properties(
+ let mut eq_properties = join_equivalence_properties(
left.equivalence_properties().clone(),
right.equivalence_properties().clone(),
&join_type,
- schema,
+ Arc::clone(&schema),
&Self::maintains_input_order(join_type),
None,
// No on columns in nested loop join
&[],
);
- let output_partitioning =
+ let mut output_partitioning =
asymmetric_join_output_partitioning(left, right, &join_type);
let emission_type = if left.boundedness().is_unbounded() {
@@ -263,12 +281,22 @@ impl NestedLoopJoinExec {
right.pipeline_behavior()
};
- PlanProperties::new(
+ if let Some(projection) = projection {
+ // construct a map from the input expressions to the output expression of the Projection
+ let projection_mapping =
+ ProjectionMapping::from_indices(projection, &schema)?;
+ let out_schema = project_schema(&schema, Some(projection))?;
+ output_partitioning =
+ output_partitioning.project(&projection_mapping, &eq_properties);
+ eq_properties = eq_properties.project(&projection_mapping, out_schema);
+ }
+
+ Ok(PlanProperties::new(
eq_properties,
output_partitioning,
emission_type,
boundedness_from_children([left, right]),
- )
+ ))
}
/// Returns a vector indicating whether the left and right inputs maintain their order.
@@ -296,17 +324,45 @@ impl NestedLoopJoinExec {
]
}
+ pub fn contains_projection(&self) -> bool {
+ self.projection.is_some()
+ }
+
+ pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
+ // check if the projection is valid
+ can_project(&self.schema(), projection.as_ref())?;
+ let projection = match projection {
+ Some(projection) => match &self.projection {
+ Some(p) => Some(projection.iter().map(|i| p[*i]).collect()),
+ None => Some(projection),
+ },
+ None => None,
+ };
+ Self::try_new(
+ Arc::clone(&self.left),
+ Arc::clone(&self.right),
+ self.filter.clone(),
+ &self.join_type,
+ projection,
+ )
+ }
+
/// Returns a new `ExecutionPlan` that runs NestedLoopsJoins with the left
/// and right inputs swapped.
pub fn swap_inputs(&self) -> Result<Arc<dyn ExecutionPlan>> {
- let new_filter = self.filter().map(JoinFilter::swap);
- let new_join_type = &self.join_type().swap();
-
+ let left = self.left();
+ let right = self.right();
let new_join = NestedLoopJoinExec::try_new(
- Arc::clone(self.right()),
- Arc::clone(self.left()),
- new_filter,
- new_join_type,
+ Arc::clone(right),
+ Arc::clone(left),
+ self.filter().map(JoinFilter::swap),
+ &self.join_type().swap(),
+ swap_join_projection(
+ left.schema().fields().len(),
+ right.schema().fields().len(),
+ self.projection.as_ref(),
+ self.join_type(),
+ ),
)?;
// For Semi/Anti joins, swap result will produce same output schema,
@@ -317,7 +373,8 @@ impl NestedLoopJoinExec {
| JoinType::RightSemi
| JoinType::LeftAnti
| JoinType::RightAnti
- ) {
+ ) || self.projection.is_some()
+ {
Arc::new(new_join)
} else {
reorder_output_after_swap(
@@ -339,10 +396,28 @@ impl DisplayAs for NestedLoopJoinExec {
|| "".to_string(),
|f| format!(", filter={}", f.expression()),
);
+ let display_projections = if self.contains_projection() {
+ format!(
+ ", projection=[{}]",
+ self.projection
+ .as_ref()
+ .unwrap()
+ .iter()
+ .map(|index| format!(
+ "{}@{}",
+ self.join_schema.fields().get(*index).unwrap().name(),
+ index
+ ))
+ .collect::<Vec<_>>()
+ .join(", ")
+ )
+ } else {
+ "".to_string()
+ };
write!(
f,
- "NestedLoopJoinExec: join_type={:?}{}",
- self.join_type, display_filter
+ "NestedLoopJoinExec: join_type={:?}{}{}",
+ self.join_type, display_filter, display_projections
)
}
}
@@ -386,6 +461,7 @@ impl ExecutionPlan for NestedLoopJoinExec {
Arc::clone(&children[1]),
self.filter.clone(),
&self.join_type,
+ self.projection.clone(),
)?))
}
@@ -424,14 +500,23 @@ impl ExecutionPlan for NestedLoopJoinExec {
let right_side_ordered =
self.maintains_input_order()[1] && self.right.output_ordering().is_some();
+ // update column indices to reflect the projection
+ let column_indices_after_projection = match &self.projection {
+ Some(projection) => projection
+ .iter()
+ .map(|i| self.column_indices[*i].clone())
+ .collect(),
+ None => self.column_indices.clone(),
+ };
+
if enforce_batch_size_in_joins {
Ok(Box::pin(NestedLoopJoinStream {
- schema: Arc::clone(&self.schema),
+ schema: self.schema(),
filter: self.filter.clone(),
join_type: self.join_type,
outer_table,
inner_table,
- column_indices: self.column_indices.clone(),
+ column_indices: column_indices_after_projection,
join_metrics,
indices_cache,
right_side_ordered,
@@ -441,12 +526,12 @@ impl ExecutionPlan for NestedLoopJoinExec {
}))
} else {
Ok(Box::pin(NestedLoopJoinStream {
- schema: Arc::clone(&self.schema),
+ schema: self.schema(),
filter: self.filter.clone(),
join_type: self.join_type,
outer_table,
inner_table,
- column_indices: self.column_indices.clone(),
+ column_indices: column_indices_after_projection,
join_metrics,
indices_cache,
right_side_ordered,
@@ -467,7 +552,7 @@ impl ExecutionPlan for NestedLoopJoinExec {
Arc::clone(&self.right),
vec![],
&self.join_type,
- &self.schema,
+ &self.join_schema,
)
}
}
@@ -1039,7 +1124,7 @@ pub(crate) mod tests {
// Use the required distribution for nested loop join to test partition data
let nested_loop_join =
- NestedLoopJoinExec::try_new(left, right, join_filter, join_type)?;
+ NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
let columns = columns(&nested_loop_join.schema());
let mut batches = vec![];
for i in 0..partition_count {
@@ -1475,6 +1560,7 @@ pub(crate) mod tests {
Arc::clone(&right),
Some(filter),
&join_type,
+ None,
)?) as Arc<dyn ExecutionPlan>;
assert_eq!(nested_loop_join.maintains_input_order(), vec![false, true]);
diff --git a/datafusion/physical-plan/src/joins/utils.rs b/datafusion/physical-plan/src/joins/utils.rs
index 22513144d4..0210035cc2 100644
--- a/datafusion/physical-plan/src/joins/utils.rs
+++ b/datafusion/physical-plan/src/joins/utils.rs
@@ -1784,6 +1784,39 @@ fn swap_reverting_projection(
left_cols.chain(right_cols).collect()
}
+/// This function swaps the given join's projection.
+pub(super) fn swap_join_projection(
+ left_schema_len: usize,
+ right_schema_len: usize,
+ projection: Option<&Vec<usize>>,
+ join_type: &JoinType,
+) -> Option<Vec<usize>> {
+ match join_type {
+ // For Anti/Semi join types, projection should remain unmodified,
+ // since these joins output schema remains the same after swap
+ JoinType::LeftAnti
+ | JoinType::LeftSemi
+ | JoinType::RightAnti
+ | JoinType::RightSemi => projection.cloned(),
+
+ _ => projection.map(|p| {
+ p.iter()
+ .map(|i| {
+ // If the index is less than the left schema length, it is from
+ // the left schema, so we add the right schema length to it.
+ // Otherwise, it is from the right schema, so we subtract the left
+ // schema length from it.
+ if *i < left_schema_len {
+ *i + right_schema_len
+ } else {
+ *i - left_schema_len
+ }
+ })
+ .collect()
+ }),
+ }
+}
+
#[cfg(test)]
mod tests {
use std::pin::Pin;
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 62ad0ec134..57c2f5f51b 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -1198,6 +1198,7 @@ message NestedLoopJoinExecNode {
PhysicalPlanNode right = 2;
datafusion_common.JoinType join_type = 3;
JoinFilter filter = 4;
+ repeated uint32 projection = 5;
}
message CoalesceBatchesExecNode {
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 229b4af915..0cf893cbc5 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -11695,6 +11695,9 @@ impl serde::Serialize for NestedLoopJoinExecNode {
if self.filter.is_some() {
len += 1;
}
+ if !self.projection.is_empty() {
+ len += 1;
+ }
let mut struct_ser = serializer.serialize_struct("datafusion.NestedLoopJoinExecNode", len)?;
if let Some(v) = self.left.as_ref() {
struct_ser.serialize_field("left", v)?;
@@ -11710,6 +11713,9 @@ impl serde::Serialize for NestedLoopJoinExecNode {
if let Some(v) = self.filter.as_ref() {
struct_ser.serialize_field("filter", v)?;
}
+ if !self.projection.is_empty() {
+ struct_ser.serialize_field("projection", &self.projection)?;
+ }
struct_ser.end()
}
}
@@ -11725,6 +11731,7 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
"join_type",
"joinType",
"filter",
+ "projection",
];
#[allow(clippy::enum_variant_names)]
@@ -11733,6 +11740,7 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
Right,
JoinType,
Filter,
+ Projection,
}
impl<'de> serde::Deserialize<'de> for GeneratedField {
fn deserialize<D>(deserializer: D) -> std::result::Result<GeneratedField, D::Error>
@@ -11758,6 +11766,7 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
"right" => Ok(GeneratedField::Right),
"joinType" | "join_type" => Ok(GeneratedField::JoinType),
"filter" => Ok(GeneratedField::Filter),
+ "projection" => Ok(GeneratedField::Projection),
_ => Err(serde::de::Error::unknown_field(value, FIELDS)),
}
}
@@ -11781,6 +11790,7 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
let mut right__ = None;
let mut join_type__ = None;
let mut filter__ = None;
+ let mut projection__ = None;
while let Some(k) = map_.next_key()? {
match k {
GeneratedField::Left => {
@@ -11807,6 +11817,15 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
}
filter__ = map_.next_value()?;
}
+ GeneratedField::Projection => {
+ if projection__.is_some() {
+ return Err(serde::de::Error::duplicate_field("projection"));
+ }
+ projection__ =
+ Some(map_.next_value::<Vec<::pbjson::private::NumberDeserialize<_>>>()?
+ .into_iter().map(|x| x.0).collect())
+ ;
+ }
}
}
Ok(NestedLoopJoinExecNode {
@@ -11814,6 +11833,7 @@ impl<'de> serde::Deserialize<'de> for NestedLoopJoinExecNode {
right: right__,
join_type: join_type__.unwrap_or_default(),
filter: filter__,
+ projection: projection__.unwrap_or_default(),
})
}
}
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index a143b2046a..26efb617e0 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -1790,6 +1790,8 @@ pub struct NestedLoopJoinExecNode {
pub join_type: i32,
#[prost(message, optional, tag = "4")]
pub filter: ::core::option::Option<JoinFilter>,
+ #[prost(uint32, repeated, tag = "5")]
+ pub projection: ::prost::alloc::vec::Vec<u32>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CoalesceBatchesExecNode {
diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs
index 9eee72925f..25fca611df 100644
--- a/datafusion/proto/src/physical_plan/mod.rs
+++ b/datafusion/proto/src/physical_plan/mod.rs
@@ -996,11 +996,23 @@ impl AsExecutionPlan for protobuf::PhysicalPlanNode {
})
.map_or(Ok(None), |v: Result<JoinFilter>| v.map(Some))?;
+ let projection = if !join.projection.is_empty() {
+ Some(
+ join.projection
+ .iter()
+ .map(|i| *i as usize)
+ .collect::<Vec<_>>(),
+ )
+ } else {
+ None
+ };
+
Ok(Arc::new(NestedLoopJoinExec::try_new(
left,
right,
filter,
&join_type.into(),
+ projection,
)?))
}
PhysicalPlanType::Analyze(analyze) => {
@@ -1837,6 +1849,9 @@ impl AsExecutionPlan for protobuf::PhysicalPlanNode {
right: Some(Box::new(right)),
join_type: join_type.into(),
filter,
+ projection: exec.projection().map_or_else(Vec::new, |v| {
+ v.iter().map(|x| *x as u32).collect::<Vec<u32>>()
+ }),
},
))),
});
diff --git a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
index 129566a3f9..157711b4e2 100644
--- a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
@@ -270,6 +270,7 @@ fn roundtrip_nested_loop_join() -> Result<()> {
Arc::new(EmptyExec::new(schema_right.clone())),
None,
join_type,
+ Some(vec![0]),
)?))?;
}
Ok(())
diff --git a/datafusion/sqllogictest/test_files/group_by.slt b/datafusion/sqllogictest/test_files/group_by.slt
index 63d285cc93..056f88450c 100644
--- a/datafusion/sqllogictest/test_files/group_by.slt
+++ b/datafusion/sqllogictest/test_files/group_by.slt
@@ -3429,11 +3429,10 @@ physical_plan
05)--------CoalesceBatchesExec: target_batch_size=4
06)----------RepartitionExec: partitioning=Hash([sn@0, amount@1], 8), input_partitions=8
07)------------AggregateExec: mode=Partial, gby=[sn@1 as sn, amount@2 as amount], aggr=[sum(l.amount)]
-08)--------------ProjectionExec: expr=[amount@1 as amount, sn@2 as sn, amount@3 as amount]
-09)----------------NestedLoopJoinExec: join_type=Inner, filter=sn@0 >= sn@1
-10)------------------MemoryExec: partitions=1, partition_sizes=[1]
-11)------------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1
-12)--------------------MemoryExec: partitions=1, partition_sizes=[1]
+08)--------------NestedLoopJoinExec: join_type=Inner, filter=sn@0 >= sn@1, projection=[amount@1, sn@2, amount@3]
+09)----------------MemoryExec: partitions=1, partition_sizes=[1]
+10)----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1
+11)------------------MemoryExec: partitions=1, partition_sizes=[1]
query IRR
SELECT r.sn, SUM(l.amount), r.amount
diff --git a/datafusion/sqllogictest/test_files/tpch/plans/q11.slt.part b/datafusion/sqllogictest/test_files/tpch/plans/q11.slt.part
index 80f9919cb4..6645ede2a7 100644
--- a/datafusion/sqllogictest/test_files/tpch/plans/q11.slt.part
+++ b/datafusion/sqllogictest/test_files/tpch/plans/q11.slt.part
@@ -75,7 +75,7 @@ logical_plan
physical_plan
01)SortExec: TopK(fetch=10), expr=[value@1 DESC], preserve_partitioning=[false]
02)--ProjectionExec: expr=[ps_partkey@0 as ps_partkey, sum(partsupp.ps_supplycost * partsupp.ps_availqty)@1 as value]
-03)----NestedLoopJoinExec: join_type=Inner, filter=CAST(sum(partsupp.ps_supplycost * partsupp.ps_availqty)@0 AS Decimal128(38, 15)) > sum(partsupp.ps_supplycost * partsupp.ps_availqty) * Float64(0.0001)@1
+03)----NestedLoopJoinExec: join_type=Inner, filter=CAST(sum(partsupp.ps_supplycost * partsupp.ps_availqty)@0 AS Decimal128(38, 15)) > sum(partsupp.ps_supplycost * partsupp.ps_availqty) * Float64(0.0001)@1, projection=[ps_partkey@0, sum(partsupp.ps_supplycost * partsupp.ps_availqty)@1]
04)------CoalescePartitionsExec
05)--------AggregateExec: mode=FinalPartitioned, gby=[ps_partkey@0 as ps_partkey], aggr=[sum(partsupp.ps_supplycost * partsupp.ps_availqty)]
06)----------CoalesceBatchesExec: target_batch_size=8192