jackwener commented on code in PR #4562:
URL: https://github.com/apache/arrow-datafusion/pull/4562#discussion_r1045762035


##########
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(),
+            ))
+        };

Review Comment:
   I'm not sure about how to design for different kind partition.
   I need to investigate about this.



-- 
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]

Reply via email to