alamb commented on a change in pull request #8709:
URL: https://github.com/apache/arrow/pull/8709#discussion_r527147571



##########
File path: rust/datafusion/src/physical_plan/hash_join.rs
##########
@@ -0,0 +1,507 @@
+// 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 join plan for executing partitions in parallel and then 
joining the results
+//! into a set of partitions.
+
+use std::sync::Arc;
+use std::{
+    any::Any,
+    collections::{HashMap, HashSet},
+};
+
+use async_trait::async_trait;
+use futures::{Stream, StreamExt, TryStreamExt};
+
+use arrow::array::{make_array, Array, MutableArrayData};
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{expressions::col, hash_aggregate::create_key};
+use super::{
+    hash_utils::{build_join_schema, check_join_is_valid, JoinType},
+    merge::MergeExec,
+};
+use crate::error::{DataFusionError, Result};
+
+use super::{
+    group_scalar::GroupByScalar, ExecutionPlan, Partitioning, 
RecordBatchStream,
+    SendableRecordBatchStream,
+};
+
+// An index of (batch, row) uniquely identifying a row in a part.
+type Index = (usize, usize);
+// A pair (left index, right index)
+// Note that while this is currently equal to `Index`, the `JoinIndex` is 
semantically different
+// as a left join may issue None indices, in which case
+type JoinIndex = Option<(usize, usize)>;
+// Maps ["on" value] -> [list of indices with this key's value]
+// E.g. [1, 2] -> [(0, 3), (1, 6), (0, 8)] indicates that (column1, column2) = 
[1, 2] is true
+// for rows 3 and 8 from batch 0 and row 6 from batch 1.
+type JoinHashMap = HashMap<Vec<GroupByScalar>, Vec<Index>>;
+type JoinLeftData = (JoinHashMap, Vec<RecordBatch>);
+
+/// join execution plan executes partitions in parallel and combines them into 
a set of
+/// partitions.
+#[derive(Debug)]
+pub struct HashJoinExec {
+    /// left side
+    left: Arc<dyn ExecutionPlan>,
+    /// right side
+    right: Arc<dyn ExecutionPlan>,

Review comment:
       "/// right (probe) side which are filtered by the hash table"

##########
File path: rust/datafusion/src/physical_plan/hash_join.rs
##########
@@ -0,0 +1,507 @@
+// 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 join plan for executing partitions in parallel and then 
joining the results
+//! into a set of partitions.
+
+use std::sync::Arc;
+use std::{
+    any::Any,
+    collections::{HashMap, HashSet},
+};
+
+use async_trait::async_trait;
+use futures::{Stream, StreamExt, TryStreamExt};
+
+use arrow::array::{make_array, Array, MutableArrayData};
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{expressions::col, hash_aggregate::create_key};
+use super::{
+    hash_utils::{build_join_schema, check_join_is_valid, JoinType},
+    merge::MergeExec,
+};
+use crate::error::{DataFusionError, Result};
+
+use super::{
+    group_scalar::GroupByScalar, ExecutionPlan, Partitioning, 
RecordBatchStream,
+    SendableRecordBatchStream,
+};
+
+// An index of (batch, row) uniquely identifying a row in a part.
+type Index = (usize, usize);
+// A pair (left index, right index)
+// Note that while this is currently equal to `Index`, the `JoinIndex` is 
semantically different
+// as a left join may issue None indices, in which case
+type JoinIndex = Option<(usize, usize)>;
+// Maps ["on" value] -> [list of indices with this key's value]
+// E.g. [1, 2] -> [(0, 3), (1, 6), (0, 8)] indicates that (column1, column2) = 
[1, 2] is true
+// for rows 3 and 8 from batch 0 and row 6 from batch 1.
+type JoinHashMap = HashMap<Vec<GroupByScalar>, Vec<Index>>;
+type JoinLeftData = (JoinHashMap, Vec<RecordBatch>);
+
+/// join execution plan executes partitions in parallel and combines them into 
a set of
+/// partitions.
+#[derive(Debug)]
+pub struct HashJoinExec {
+    /// left side

Review comment:
       "/// left (build) side which gets hashed"

##########
File path: rust/datafusion/src/physical_plan/hash_join.rs
##########
@@ -0,0 +1,507 @@
+// 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 join plan for executing partitions in parallel and then 
joining the results
+//! into a set of partitions.
+
+use std::sync::Arc;
+use std::{
+    any::Any,
+    collections::{HashMap, HashSet},
+};
+
+use async_trait::async_trait;
+use futures::{Stream, StreamExt, TryStreamExt};
+
+use arrow::array::{make_array, Array, MutableArrayData};
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{expressions::col, hash_aggregate::create_key};
+use super::{
+    hash_utils::{build_join_schema, check_join_is_valid, JoinType},
+    merge::MergeExec,
+};
+use crate::error::{DataFusionError, Result};
+
+use super::{
+    group_scalar::GroupByScalar, ExecutionPlan, Partitioning, 
RecordBatchStream,
+    SendableRecordBatchStream,
+};
+
+// An index of (batch, row) uniquely identifying a row in a part.
+type Index = (usize, usize);
+// A pair (left index, right index)
+// Note that while this is currently equal to `Index`, the `JoinIndex` is 
semantically different
+// as a left join may issue None indices, in which case
+type JoinIndex = Option<(usize, usize)>;
+// Maps ["on" value] -> [list of indices with this key's value]
+// E.g. [1, 2] -> [(0, 3), (1, 6), (0, 8)] indicates that (column1, column2) = 
[1, 2] is true
+// for rows 3 and 8 from batch 0 and row 6 from batch 1.
+type JoinHashMap = HashMap<Vec<GroupByScalar>, Vec<Index>>;
+type JoinLeftData = (JoinHashMap, Vec<RecordBatch>);
+
+/// join execution plan executes partitions in parallel and combines them into 
a set of
+/// partitions.
+#[derive(Debug)]
+pub struct HashJoinExec {
+    /// left side

Review comment:
       "left, build side  -- built into a hash table"

##########
File path: rust/datafusion/src/physical_plan/hash_join.rs
##########
@@ -0,0 +1,507 @@
+// 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 join plan for executing partitions in parallel and then 
joining the results
+//! into a set of partitions.
+
+use std::sync::Arc;
+use std::{
+    any::Any,
+    collections::{HashMap, HashSet},
+};
+
+use async_trait::async_trait;
+use futures::{Stream, StreamExt, TryStreamExt};
+
+use arrow::array::{make_array, Array, MutableArrayData};
+use arrow::datatypes::{Schema, SchemaRef};
+use arrow::error::Result as ArrowResult;
+use arrow::record_batch::RecordBatch;
+
+use super::{expressions::col, hash_aggregate::create_key};
+use super::{
+    hash_utils::{build_join_schema, check_join_is_valid, JoinType},
+    merge::MergeExec,
+};
+use crate::error::{DataFusionError, Result};
+
+use super::{
+    group_scalar::GroupByScalar, ExecutionPlan, Partitioning, 
RecordBatchStream,
+    SendableRecordBatchStream,
+};
+
+// An index of (batch, row) uniquely identifying a row in a part.
+type Index = (usize, usize);
+// A pair (left index, right index)
+// Note that while this is currently equal to `Index`, the `JoinIndex` is 
semantically different
+// as a left join may issue None indices, in which case
+type JoinIndex = Option<(usize, usize)>;
+// Maps ["on" value] -> [list of indices with this key's value]
+// E.g. [1, 2] -> [(0, 3), (1, 6), (0, 8)] indicates that (column1, column2) = 
[1, 2] is true
+// for rows 3 and 8 from batch 0 and row 6 from batch 1.
+type JoinHashMap = HashMap<Vec<GroupByScalar>, Vec<Index>>;
+type JoinLeftData = (JoinHashMap, Vec<RecordBatch>);
+
+/// join execution plan executes partitions in parallel and combines them into 
a set of
+/// partitions.
+#[derive(Debug)]
+pub struct HashJoinExec {
+    /// left side
+    left: Arc<dyn ExecutionPlan>,
+    /// right side
+    right: Arc<dyn ExecutionPlan>,
+    /// Set of common columns used to join on
+    on: HashSet<String>,
+    /// How the join is performed
+    join_type: JoinType,
+    /// The schema once the join is applied
+    schema: SchemaRef,
+}
+
+impl HashJoinExec {
+    /// Tries to create a new [HashJoinExec].
+    /// # Error
+    /// This function errors when it is not possible to join the left and 
right sides on keys `on`.
+    pub fn try_new(
+        left: Arc<dyn ExecutionPlan>,
+        right: Arc<dyn ExecutionPlan>,
+        on: &HashSet<String>,
+        join_type: &JoinType,
+    ) -> Result<Self> {
+        let left_schema = left.schema();
+        let right_schema = right.schema();
+        check_join_is_valid(&left_schema, &right_schema, &on)?;
+
+        let on = on.iter().map(|s| s.clone()).collect::<HashSet<_>>();
+
+        let schema = Arc::new(build_join_schema(
+            &left_schema,
+            &right_schema,
+            &on,
+            &join_type,
+        ));
+
+        Ok(HashJoinExec {
+            left,
+            right,
+            on: on.clone(),
+            join_type: join_type.clone(),
+            schema,
+        })
+    }
+}
+
+#[async_trait]
+impl ExecutionPlan for HashJoinExec {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn schema(&self) -> SchemaRef {
+        self.schema.clone()
+    }
+
+    fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+        vec![self.left.clone(), self.right.clone()]
+    }
+
+    fn with_new_children(
+        &self,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        match children.len() {
+            2 => Ok(Arc::new(HashJoinExec::try_new(
+                children[0].clone(),
+                children[1].clone(),
+                &self.on,
+                &self.join_type,
+            )?)),
+            _ => Err(DataFusionError::Internal(
+                "HashJoinExec wrong number of children".to_string(),
+            )),
+        }
+    }
+
+    fn output_partitioning(&self) -> Partitioning {
+        self.right.output_partitioning()
+    }
+
+    async fn execute(&self, partition: usize) -> 
Result<SendableRecordBatchStream> {
+        // merge all parts into a single stream
+        // this is currently expensive as we re-compute this for every part 
from the right
+        // TODO: Fix this issue: we can't share this state across parts on the 
right.
+        // We need to change this `execute` to allow sharing state across 
parts...
+        let merge = MergeExec::new(self.left.clone());
+        let stream = merge.execute(0).await?;
+
+        // This operation performs 2 steps at once:
+        // 1. creates a [JoinHashMap] of all batches from the stream
+        // 2. stores the batches in a vector.
+        let initial = (JoinHashMap::new(), Vec::new(), 0);
+        let left_data = stream
+            .try_fold(initial, |mut acc, batch| async {
+                let hash = &mut acc.0;
+                let values = &mut acc.1;
+                let index = acc.2;
+                update_hash(&self.on, &batch, hash, index).unwrap();
+                values.push(batch);
+                acc.2 += 1;
+                Ok(acc)
+            })
+            .await?;
+        // we have the batches and the hash map with their keys. We can how 
create a stream

Review comment:
       "how --> now"

##########
File path: rust/datafusion/src/physical_plan/hash_utils.rs
##########
@@ -0,0 +1,144 @@
+// 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.
+
+//! Functionality used both on logical and physical plans
+
+use crate::error::{DataFusionError, Result};
+use arrow::datatypes::{Field, Schema};
+use std::collections::HashSet;
+
+/// All valid types of joins.
+#[derive(Clone, Debug)]
+pub enum JoinType {
+    /// Inner join
+    Inner,
+}
+
+/// Checks whether the schemas "left" and "right" and columns "on" represent a 
valid join.
+/// They are valid whenever their columns' intersection equals the set `on`
+pub fn check_join_is_valid(
+    left: &Schema,
+    right: &Schema,
+    on: &HashSet<String>,

Review comment:
       This might be easier code to write if the `on` expresion was of the form:
   
   ```
   equality_expressions: Vec<(Expr, Expr)>
   other_expressions: Vec<Expr>
   ```
   
   Where the planner identifies quality expressions and breaks them up -- again 
I can help write this code. 




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

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to