mingmwang commented on code in PR #4562: URL: https://github.com/apache/arrow-datafusion/pull/4562#discussion_r1045489211
########## datafusion/core/src/physical_plan/joins/nested_loop_join.rs: ########## @@ -0,0 +1,883 @@ +// 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. + +//! Defines the nested loop join plan, it supports all [`JoinType`]. +//! The nested loop join can execute in parallel by partitions and it is +//! determined by the [`JoinType`]. + +use crate::physical_plan::joins::utils::{ + adjust_indices_by_join_type, adjust_right_output_partitioning, + apply_join_filter_to_indices, build_batch_from_indices, build_join_schema, + check_join_is_valid, combine_join_equivalence_properties, estimate_join_statistics, + get_final_indices, need_produce_result_in_final, ColumnIndex, JoinFilter, OnceAsync, + OnceFut, +}; +use crate::physical_plan::{ + DisplayFormatType, Distribution, ExecutionPlan, Partitioning, RecordBatchStream, + SendableRecordBatchStream, +}; +use arrow::array::{ + BooleanBufferBuilder, UInt32Array, UInt32Builder, UInt64Array, UInt64Builder, +}; +use arrow::datatypes::{Schema, SchemaRef}; +use arrow::error::{ArrowError, Result as ArrowResult}; +use arrow::record_batch::RecordBatch; +use datafusion_common::Statistics; +use datafusion_expr::JoinType; +use datafusion_physical_expr::{EquivalenceProperties, PhysicalSortExpr}; +use futures::{ready, Stream, StreamExt, TryStreamExt}; +use log::debug; +use std::any::Any; +use std::fmt::Formatter; +use std::sync::Arc; +use std::task::Poll; +use std::time::Instant; + +use crate::error::Result; +use crate::execution::context::TaskContext; +use crate::physical_plan::coalesce_batches::concat_batches; + +/// Data of the left side +type JoinLeftData = RecordBatch; + +/// +#[derive(Debug)] +pub struct NestedLoopJoinExec { + /// left side + pub(crate) left: Arc<dyn ExecutionPlan>, + /// right side + pub(crate) right: Arc<dyn ExecutionPlan>, + /// Filters which are applied while finding matching rows + pub(crate) filter: Option<JoinFilter>, + /// How the join is performed + pub(crate) join_type: JoinType, + /// The schema once the join is applied + schema: SchemaRef, + /// Build-side data + left_fut: OnceAsync<JoinLeftData>, + /// Information of index and left / right placement of columns + column_indices: Vec<ColumnIndex>, +} + +impl NestedLoopJoinExec { + /// Try to create a nwe [`NestedLoopJoinExec`] + pub fn try_new( + left: Arc<dyn ExecutionPlan>, + right: Arc<dyn ExecutionPlan>, + filter: Option<JoinFilter>, + join_type: &JoinType, + ) -> Result<Self> { + let left_schema = left.schema(); + let right_schema = right.schema(); + check_join_is_valid(&left_schema, &right_schema, &[])?; + let (schema, column_indices) = + build_join_schema(&left_schema, &right_schema, join_type); + Ok(NestedLoopJoinExec { + left, + right, + filter, + join_type: *join_type, + schema: Arc::new(schema), + left_fut: Default::default(), + column_indices, + }) + } + + fn is_single_partition_for_left(&self) -> bool { + matches!( + self.required_input_distribution()[0], + Distribution::SinglePartition + ) + } +} + +impl ExecutionPlan for NestedLoopJoinExec { + fn as_any(&self) -> &dyn Any { + self + } + + fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn output_partitioning(&self) -> Partitioning { + // the partition of output is determined by the rule of `required_input_distribution` + // TODO we can replace it by `partitioned_join_output_partitioning` + match self.join_type { + // use the left partition + JoinType::Inner + | JoinType::Left + | JoinType::LeftSemi + | JoinType::LeftAnti + | JoinType::Full => self.left.output_partitioning(), + // use the right partition + JoinType::Right => { + // if the partition of right is hash, + // and the right partition should be adjusted the column index for the right expr + adjust_right_output_partitioning( + self.right.output_partitioning(), + self.left.schema().fields.len(), + ) + } + // use the right partition + JoinType::RightSemi | JoinType::RightAnti => self.right.output_partitioning(), + } + } + + fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> { + // no specified order for the output + None + } + + fn required_input_distribution(&self) -> Vec<Distribution> { + distribution_from_join_type(&self.join_type) + } + + fn equivalence_properties(&self) -> EquivalenceProperties { + let left_columns_len = self.left.schema().fields.len(); + combine_join_equivalence_properties( + self.join_type, + self.left.equivalence_properties(), + self.right.equivalence_properties(), + left_columns_len, + &[], // empty join keys + self.schema(), + ) + } + + fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> { + vec![self.left.clone(), self.right.clone()] + } + + fn with_new_children( + self: Arc<Self>, + children: Vec<Arc<dyn ExecutionPlan>>, + ) -> Result<Arc<dyn ExecutionPlan>> { + Ok(Arc::new(NestedLoopJoinExec::try_new( + children[0].clone(), + children[1].clone(), + self.filter.clone(), + &self.join_type, + )?)) + } + + fn execute( + &self, + partition: usize, + context: Arc<TaskContext>, + ) -> Result<SendableRecordBatchStream> { + // if the distribution of left is `SinglePartition`, just need to collect the left one + let left_is_single_partition = self.is_single_partition_for_left(); + // left side + let left_fut = if left_is_single_partition { + self.left_fut.once(|| { + // just one partition for the left side, and the first partition is all of data for left + load_left_specified_partition(0, self.left.clone(), context.clone()) + }) + } else { + // the distribution of left is not single partition, just need the specified partition for left + OnceFut::new(load_left_specified_partition( + partition, + self.left.clone(), + context.clone(), + )) + }; + // right side + let right_side = if left_is_single_partition { + self.right.execute(partition, context)? + } else { + // the distribution of right is `SinglePartition` + self.right.execute(0, context)? + }; + + Ok(Box::pin(NestedLoopJoinStream { + schema: self.schema.clone(), + filter: self.filter.clone(), + join_type: self.join_type, + left_fut, + right: right_side, + is_exhausted: false, + visited_left_side: None, + column_indices: self.column_indices.clone(), + })) + } + + fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result { + match t { + DisplayFormatType::Default => { + let display_filter = self.filter.as_ref().map_or_else( + || "".to_string(), + |f| format!(", filter={:?}", f.expression()), + ); + write!( + f, + "NestedLoopJoinExec: join_type={:?}{}", + self.join_type, display_filter + ) + } + } + } + + fn statistics(&self) -> Statistics { + estimate_join_statistics( + self.left.clone(), + self.right.clone(), + vec![], + &self.join_type, + ) + } +} + +// For the nested loop join, different join type need the different distribution for +// left and right node. +fn distribution_from_join_type(join_type: &JoinType) -> Vec<Distribution> { + match join_type { + JoinType::Inner | JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => { + // need the left data, and the right should be one partition + vec![ + Distribution::UnspecifiedDistribution, + Distribution::SinglePartition, + ] + } + JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => { + // need the right data, and the left should be one partition + vec![ + Distribution::SinglePartition, + Distribution::UnspecifiedDistribution, + ] + } + JoinType::Full => { + // need the left and right data, and the left and right should be one partition + vec![Distribution::SinglePartition, Distribution::SinglePartition] + } + } +} + Review Comment: Especially for FullOut join, if we enforce the both input sides coalesced to the single partition, we might encounter performance issue. ########## datafusion/core/src/physical_plan/joins/nested_loop_join.rs: ########## @@ -0,0 +1,883 @@ +// 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. + +//! Defines the nested loop join plan, it supports all [`JoinType`]. +//! The nested loop join can execute in parallel by partitions and it is +//! determined by the [`JoinType`]. + +use crate::physical_plan::joins::utils::{ + adjust_indices_by_join_type, adjust_right_output_partitioning, + apply_join_filter_to_indices, build_batch_from_indices, build_join_schema, + check_join_is_valid, combine_join_equivalence_properties, estimate_join_statistics, + get_final_indices, need_produce_result_in_final, ColumnIndex, JoinFilter, OnceAsync, + OnceFut, +}; +use crate::physical_plan::{ + DisplayFormatType, Distribution, ExecutionPlan, Partitioning, RecordBatchStream, + SendableRecordBatchStream, +}; +use arrow::array::{ + BooleanBufferBuilder, UInt32Array, UInt32Builder, UInt64Array, UInt64Builder, +}; +use arrow::datatypes::{Schema, SchemaRef}; +use arrow::error::{ArrowError, Result as ArrowResult}; +use arrow::record_batch::RecordBatch; +use datafusion_common::Statistics; +use datafusion_expr::JoinType; +use datafusion_physical_expr::{EquivalenceProperties, PhysicalSortExpr}; +use futures::{ready, Stream, StreamExt, TryStreamExt}; +use log::debug; +use std::any::Any; +use std::fmt::Formatter; +use std::sync::Arc; +use std::task::Poll; +use std::time::Instant; + +use crate::error::Result; +use crate::execution::context::TaskContext; +use crate::physical_plan::coalesce_batches::concat_batches; + +/// Data of the left side +type JoinLeftData = RecordBatch; + +/// +#[derive(Debug)] +pub struct NestedLoopJoinExec { + /// left side + pub(crate) left: Arc<dyn ExecutionPlan>, + /// right side + pub(crate) right: Arc<dyn ExecutionPlan>, + /// Filters which are applied while finding matching rows + pub(crate) filter: Option<JoinFilter>, + /// How the join is performed + pub(crate) join_type: JoinType, + /// The schema once the join is applied + schema: SchemaRef, + /// Build-side data + left_fut: OnceAsync<JoinLeftData>, + /// Information of index and left / right placement of columns + column_indices: Vec<ColumnIndex>, +} + +impl NestedLoopJoinExec { + /// Try to create a nwe [`NestedLoopJoinExec`] + pub fn try_new( + left: Arc<dyn ExecutionPlan>, + right: Arc<dyn ExecutionPlan>, + filter: Option<JoinFilter>, + join_type: &JoinType, + ) -> Result<Self> { + let left_schema = left.schema(); + let right_schema = right.schema(); + check_join_is_valid(&left_schema, &right_schema, &[])?; + let (schema, column_indices) = + build_join_schema(&left_schema, &right_schema, join_type); + Ok(NestedLoopJoinExec { + left, + right, + filter, + join_type: *join_type, + schema: Arc::new(schema), + left_fut: Default::default(), + column_indices, + }) + } + + fn is_single_partition_for_left(&self) -> bool { + matches!( + self.required_input_distribution()[0], + Distribution::SinglePartition + ) + } +} + +impl ExecutionPlan for NestedLoopJoinExec { + fn as_any(&self) -> &dyn Any { + self + } + + fn schema(&self) -> SchemaRef { + self.schema.clone() + } + + fn output_partitioning(&self) -> Partitioning { + // the partition of output is determined by the rule of `required_input_distribution` + // TODO we can replace it by `partitioned_join_output_partitioning` + match self.join_type { + // use the left partition + JoinType::Inner + | JoinType::Left + | JoinType::LeftSemi + | JoinType::LeftAnti + | JoinType::Full => self.left.output_partitioning(), + // use the right partition + JoinType::Right => { + // if the partition of right is hash, + // and the right partition should be adjusted the column index for the right expr + adjust_right_output_partitioning( + self.right.output_partitioning(), + self.left.schema().fields.len(), + ) + } + // use the right partition + JoinType::RightSemi | JoinType::RightAnti => self.right.output_partitioning(), + } + } + + fn output_ordering(&self) -> Option<&[PhysicalSortExpr]> { + // no specified order for the output + None + } + + fn required_input_distribution(&self) -> Vec<Distribution> { + distribution_from_join_type(&self.join_type) + } + + fn equivalence_properties(&self) -> EquivalenceProperties { + let left_columns_len = self.left.schema().fields.len(); + combine_join_equivalence_properties( + self.join_type, + self.left.equivalence_properties(), + self.right.equivalence_properties(), + left_columns_len, + &[], // empty join keys + self.schema(), + ) + } + + fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> { + vec![self.left.clone(), self.right.clone()] + } + + fn with_new_children( + self: Arc<Self>, + children: Vec<Arc<dyn ExecutionPlan>>, + ) -> Result<Arc<dyn ExecutionPlan>> { + Ok(Arc::new(NestedLoopJoinExec::try_new( + children[0].clone(), + children[1].clone(), + self.filter.clone(), + &self.join_type, + )?)) + } + + fn execute( + &self, + partition: usize, + context: Arc<TaskContext>, + ) -> Result<SendableRecordBatchStream> { + // if the distribution of left is `SinglePartition`, just need to collect the left one + let left_is_single_partition = self.is_single_partition_for_left(); + // left side + let left_fut = if left_is_single_partition { + self.left_fut.once(|| { + // just one partition for the left side, and the first partition is all of data for left + load_left_specified_partition(0, self.left.clone(), context.clone()) + }) + } else { + // the distribution of left is not single partition, just need the specified partition for left + OnceFut::new(load_left_specified_partition( + partition, + self.left.clone(), + context.clone(), + )) + }; + // right side + let right_side = if left_is_single_partition { + self.right.execute(partition, context)? + } else { + // the distribution of right is `SinglePartition` + self.right.execute(0, context)? + }; + + Ok(Box::pin(NestedLoopJoinStream { + schema: self.schema.clone(), + filter: self.filter.clone(), + join_type: self.join_type, + left_fut, + right: right_side, + is_exhausted: false, + visited_left_side: None, + column_indices: self.column_indices.clone(), + })) + } + + fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result { + match t { + DisplayFormatType::Default => { + let display_filter = self.filter.as_ref().map_or_else( + || "".to_string(), + |f| format!(", filter={:?}", f.expression()), + ); + write!( + f, + "NestedLoopJoinExec: join_type={:?}{}", + self.join_type, display_filter + ) + } + } + } + + fn statistics(&self) -> Statistics { + estimate_join_statistics( + self.left.clone(), + self.right.clone(), + vec![], + &self.join_type, + ) + } +} + +// For the nested loop join, different join type need the different distribution for +// left and right node. +fn distribution_from_join_type(join_type: &JoinType) -> Vec<Distribution> { + match join_type { + JoinType::Inner | JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => { + // need the left data, and the right should be one partition + vec![ + Distribution::UnspecifiedDistribution, + Distribution::SinglePartition, + ] + } + JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => { + // need the right data, and the left should be one partition + vec![ + Distribution::SinglePartition, + Distribution::UnspecifiedDistribution, + ] + } + JoinType::Full => { + // need the left and right data, and the left and right should be one partition + vec![Distribution::SinglePartition, Distribution::SinglePartition] + } + } +} + Review Comment: Especially for FullOut join, if we enforce the both input sides coalesced to the single partition, we might encounter performance issue. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
