jonathanc-n commented on code in PR #18392:
URL: https://github.com/apache/datafusion/pull/18392#discussion_r2479728047


##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -256,59 +256,75 @@ fn statistical_join_selection_subrule(
     collect_threshold_byte_size: usize,
     collect_threshold_num_rows: usize,
 ) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
-    let transformed =
-        if let Some(hash_join) = plan.as_any().downcast_ref::<HashJoinExec>() {
-            match hash_join.partition_mode() {
-                PartitionMode::Auto => try_collect_left(
-                    hash_join,
-                    false,
-                    collect_threshold_byte_size,
-                    collect_threshold_num_rows,
-                )?
+    let transformed = if let Some(hash_join) =
+        plan.as_any().downcast_ref::<HashJoinExec>()
+    {
+        match hash_join.partition_mode() {
+            PartitionMode::Auto => try_collect_left(
+                hash_join,
+                false,
+                collect_threshold_byte_size,
+                collect_threshold_num_rows,
+            )?
+            .map_or_else(
+                || partitioned_hash_join(hash_join).map(Some),
+                |v| Ok(Some(v)),
+            )?,
+            PartitionMode::CollectLeft => try_collect_left(hash_join, true, 0, 
0)?
                 .map_or_else(
                     || partitioned_hash_join(hash_join).map(Some),
                     |v| Ok(Some(v)),
                 )?,
-                PartitionMode::CollectLeft => try_collect_left(hash_join, 
true, 0, 0)?
-                    .map_or_else(
-                        || partitioned_hash_join(hash_join).map(Some),
-                        |v| Ok(Some(v)),
-                    )?,
-                PartitionMode::Partitioned => {
-                    let left = hash_join.left();
-                    let right = hash_join.right();
-                    if hash_join.join_type().supports_swap()
-                        && should_swap_join_order(&**left, &**right)?
-                    {
-                        hash_join
-                            .swap_inputs(PartitionMode::Partitioned)
-                            .map(Some)?
-                    } else {
-                        None
-                    }
+            PartitionMode::Partitioned => {
+                let left = hash_join.left();
+                let right = hash_join.right();
+                if hash_join.join_type().supports_swap()
+                    && should_swap_join_order(&**left, &**right)?
+                {
+                    hash_join
+                        .swap_inputs(PartitionMode::Partitioned)
+                        .map(Some)?
+                } else {
+                    None
                 }
             }
-        } else if let Some(cross_join) = 
plan.as_any().downcast_ref::<CrossJoinExec>() {
-            let left = cross_join.left();
-            let right = cross_join.right();
-            if should_swap_join_order(&**left, &**right)? {
-                cross_join.swap_inputs().map(Some)?
-            } else {
-                None
-            }
-        } else if let Some(nl_join) = 
plan.as_any().downcast_ref::<NestedLoopJoinExec>() {
-            let left = nl_join.left();
-            let right = nl_join.right();
-            if nl_join.join_type().supports_swap()
-                && should_swap_join_order(&**left, &**right)?
-            {
-                nl_join.swap_inputs().map(Some)?
-            } else {
-                None
-            }
+        }
+    } else if let Some(cross_join) = 
plan.as_any().downcast_ref::<CrossJoinExec>() {
+        let left = cross_join.left();
+        let right = cross_join.right();
+        if should_swap_join_order(&**left, &**right)? {
+            cross_join.swap_inputs().map(Some)?
         } else {
             None
-        };
+        }
+    } else if let Some(nl_join) = 
plan.as_any().downcast_ref::<NestedLoopJoinExec>() {
+        let left = nl_join.left();
+        let right = nl_join.right();
+        if nl_join.join_type().supports_swap()
+            && should_swap_join_order(&**left, &**right)?
+        {
+            nl_join.swap_inputs().map(Some)?
+        } else {
+            None
+        }
+    } else if let Some(pwmj) = 
plan.as_any().downcast_ref::<PiecewiseMergeJoinExec>() {
+        let left = pwmj.buffered();
+        let right = pwmj.streamed();
+        if pwmj.join_type().supports_swap()
+                // Put ! here because should_swap_join_order returns true if 
left > right but 
+                // PiecewiseMergeJoin wants the left side to be the larger 
one, so only swap if 
+                // left < right
+                && (!should_swap_join_order(&**left, &**right)?
+                || matches!(pwmj.join_type(), JoinType::RightSemi | 
JoinType::RightAnti))

Review Comment:
   LeftSemi and Left Anti do not swap and only right existence joins do. This 
is explained above `swap_inputs` in PiecewiseMergeJoinExec



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -291,34 +299,19 @@ impl PiecewiseMergeJoinExec {
         on: (Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>),
         operator: Operator,
         join_type: JoinType,
-        num_partitions: usize,
     ) -> Result<Self> {
-        // TODO: Implement existence joins for PiecewiseMergeJoin
-        if is_existence_join(join_type) {
-            return not_impl_err!(
-                "Existence Joins are currently not supported for 
PiecewiseMergeJoin"
-            );
-        }
+        let buffered_partitions = 
buffered.output_partitioning().partition_count();
+        let streamed_partitions = 
streamed.output_partitioning().partition_count();
 
         // Take the operator and enforce a sort order on the streamed + 
buffered side based on
         // the operator type.
         let sort_options = match operator {
             Operator::Lt | Operator::LtEq => {
                 // For left existence joins the inputs will be swapped so the 
sort
                 // options are switched
-                if is_right_existence_join(join_type) {
-                    SortOptions::new(false, true)
-                } else {
-                    SortOptions::new(true, true)
-                }
-            }
-            Operator::Gt | Operator::GtEq => {
-                if is_right_existence_join(join_type) {
-                    SortOptions::new(true, true)
-                } else {
-                    SortOptions::new(false, true)
-                }
+                SortOptions::new(true, true)

Review Comment:
   This was changed because for whatever reason I had thought that swapping 
happened before join creation :laughing:



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/classic_join.rs:
##########
@@ -40,19 +40,19 @@ use 
crate::joins::piecewise_merge_join::utils::need_produce_result_in_final;
 use crate::joins::utils::{compare_join_arrays, 
get_final_indices_from_shared_bitmap};
 use crate::joins::utils::{BuildProbeJoinMetrics, StatefulStreamResult};
 
-pub(super) enum PiecewiseMergeJoinStreamState {
+pub(super) enum ClassicPWMJStreamState {

Review Comment:
   Renamed to make it more distinct between Existence join streamstate and 
Classic join stream state.



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/existence_join.rs:
##########
@@ -0,0 +1,1062 @@
+// 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.
+
+//! Implementation for PiecewiseMergeJoin's Existence Join (Left, Right, Full, 
Inner)
+
+use arrow::array::Array;
+use arrow::array::{ArrayRef, RecordBatch};
+use arrow::compute::BatchCoalescer;
+use arrow_schema::{Schema, SchemaRef, SortOptions};
+use datafusion_common::NullEquality;
+use datafusion_common::{internal_err, Result};
+use datafusion_execution::{RecordBatchStream, SendableRecordBatchStream};
+use datafusion_expr::Accumulator;
+use datafusion_expr::{JoinType, Operator};
+use datafusion_functions_aggregate_common::min_max::{MaxAccumulator, 
MinAccumulator};
+use datafusion_physical_expr::PhysicalExprRef;
+use futures::{Stream, StreamExt};
+use std::{cmp::Ordering, task::ready};
+use std::{sync::Arc, task::Poll};
+
+use crate::handle_state;
+use crate::joins::piecewise_merge_join::exec::{BufferedSide, 
BufferedSideReadyState};
+use crate::joins::utils::compare_join_arrays;
+use crate::joins::utils::{BuildProbeJoinMetrics, StatefulStreamResult};
+
+pub(super) enum ExistencePWMJStreamState {
+    CollectBufferedSide,
+    FetchAndProcessStreamBatch,
+    ProcessMatched,
+    Completed,
+}
+
+pub(crate) struct ExistencePWMJStream {
+    // Output schema of the `PiecewiseMergeJoin`
+    pub schema: Arc<Schema>,
+
+    // Physical expression that is evaluated on the streamed side
+    // We do not need on_buffered as this is already evaluated when
+    // creating the buffered side which happens before initializing
+    // `PiecewiseMergeJoinStream`
+    pub on_streamed: PhysicalExprRef,
+    // Type of join
+    pub join_type: JoinType,
+    // Comparison operator
+    pub operator: Operator,
+    // Streamed batch
+    pub streamed: SendableRecordBatchStream,
+    // Buffered side data
+    buffered_side: BufferedSide,
+    // Tracks the state of the `PiecewiseMergeJoin`
+    state: ExistencePWMJStreamState,
+    // Metrics for build + probe joins
+    join_metrics: BuildProbeJoinMetrics,
+    // Tracking incremental state for emitting record batches
+    batch_process_state: BatchProcessState,
+}
+
+impl RecordBatchStream for ExistencePWMJStream {
+    fn schema(&self) -> SchemaRef {
+        Arc::clone(&self.schema)
+    }
+}
+
+// `ExistencePWMJStreamState` is separated into `CollectBufferedSide`, 
`FetchAndProcessStreamBatch`,

Review Comment:
   Read the main logic here, after the min//max value is found for the streamed 
side, then the buffered side is probed. After it finds the first match it will 
emit all rows from `matched_idx - buffered_batch_length` for Semi joins 
(matches) and `0 - matched_idx` for anti joins (non-matches)
   
   You can refer back to the `PiecewiseMergeJoinExec` docs if need a refresher.



##########
datafusion/physical-optimizer/src/join_selection.rs:
##########
@@ -256,59 +256,75 @@ fn statistical_join_selection_subrule(
     collect_threshold_byte_size: usize,
     collect_threshold_num_rows: usize,
 ) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
-    let transformed =
-        if let Some(hash_join) = plan.as_any().downcast_ref::<HashJoinExec>() {
-            match hash_join.partition_mode() {
-                PartitionMode::Auto => try_collect_left(
-                    hash_join,
-                    false,
-                    collect_threshold_byte_size,
-                    collect_threshold_num_rows,
-                )?
+    let transformed = if let Some(hash_join) =

Review Comment:
   I don't know why these showed a diff but there isn't anything different here 
except for the addition of the PiecewiseMergeJoin branch for swapping.



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -462,9 +446,35 @@ impl PiecewiseMergeJoinExec {
         }
     }
 
-    // TODO
+    // Inner, Outer, Left, Right joins are swapped so that left side is larger 
than right
+    // Left Semi/Anti joins are not swapped while Right Semi/Anti joins are 
always swapped. This

Review Comment:
   This will explain the logic for why only Right semi/anti joins are swapped.



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -493,18 +503,13 @@ impl ExecutionPlan for PiecewiseMergeJoinExec {
     }
 
     fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
-        // Existence joins don't need to be sorted on one side.
-        if is_right_existence_join(self.join_type) {
-            unimplemented!()
-        } else {
-            // Sort the right side in memory, so we do not need to enforce any 
sorting
-            vec![
-                Some(OrderingRequirements::from(
-                    self.left_child_plan_required_order.clone(),
-                )),
-                None,
-            ]
-        }
+        // Sort the right side in memory, so we do not need to enforce any 
sorting

Review Comment:
   ```suggestion
           // The left side is sorted for classic and existence joins.
           // For classic joins, the right side is sorted in memory so there is 
no need to sort
   ```



##########
datafusion/physical-plan/src/joins/piecewise_merge_join/exec.rs:
##########
@@ -339,13 +330,6 @@ impl PiecewiseMergeJoinExec {
                 "PiecewiseMergeJoinExec requires valid sort expressions for 
its left side"
             );
         };
-        let Some(right_batch_required_orders) =

Review Comment:
   No longer needed, only the left side needs to be sorted.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to