Apache DataFusion SQL Query Engine
ARROW-12190: [Rust][DataFusion] Implement parallel / partitioned hash join
Heres, Daniel2daa40127e21
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rsindex 46f4516da1..328a68dd6a 100644--- a/rust/benchmarks/src/bin/tpch.rs+++ b/rust/benchmarks/src/bin/tpch.rs@@ -1459,7 +1459,7 @@ mod tests {3 => Schema::new(vec![Field::new("l_orderkey", DataType::Int32, true),Field::new("revenue", DataType::Float64, true),- Field::new("o_orderdat", DataType::Date32, true),+ Field::new("o_orderdate", DataType::Date32, true),Field::new("o_shippriority", DataType::Int32, true),]),@@ -1537,7 +1537,7 @@ mod tests {Field::new("c_name", DataType::Utf8, true),Field::new("c_custkey", DataType::Int32, true),Field::new("o_orderkey", DataType::Int32, true),- Field::new("o_orderdat", DataType::Date32, true),+ Field::new("o_orderdate", DataType::Date32, true),Field::new("o_totalprice", DataType::Float64, true),Field::new("sum_l_quantity", DataType::Float64, true),]),diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 041fe2445b..1c319a801d 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -616,6 +616,9 @@ pub struct ExecutionConfig {/// Should DataFusion provide access to `information_schema`/// virtual tables for displaying schema informationinformation_schema: bool,+ /// Should DataFusion repartition data using the join keys to execute joins in parallel+ /// using the provided `concurrency` level+ pub repartition_joins: bool,}impl ExecutionConfig {@@ -636,6 +639,7 @@ impl ExecutionConfig {default_schema: "public".to_owned(),create_default_catalog_and_schema: true,information_schema: false,+ repartition_joins: true,}}@@ -695,6 +699,12 @@ impl ExecutionConfig {self.information_schema = enabled;self}++ /// Enables or disables the use of repartitioning for joins to improve parallelism+ pub fn with_repartition_joins(mut self, enabled: bool) -> Self {+ self.repartition_joins = enabled;+ self+ }}/// Execution context for registering data sources and executing queries@@ -1390,6 +1400,23 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn join_partitioned() -> Result<()> {+ // self join on partition id (workaround for duplicate column name)+ let results = execute(+ "SELECT 1 FROM test JOIN (SELECT c1 AS id1 FROM test) ON c1=id1",+ 4,+ )+ .await?;++ assert_eq!(+ results.iter().map(|b| b.num_rows()).sum::<usize>(),+ 4 * 10 * 10+ );++ Ok(())+ }+#[tokio::test]async fn count_basic() -> Result<()> {let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 1).await?;@@ -2906,7 +2933,8 @@ mod tests {/// Generate a partitioned CSV file and register it with an execution contextfn create_ctx(tmp_dir: &TempDir, partition_count: usize) -> Result<ExecutionContext> {- let mut ctx = ExecutionContext::new();+ let mut ctx =+ ExecutionContext::with_config(ExecutionConfig::new().with_concurrency(8));let schema = populate_csv_partitions(tmp_dir, partition_count, ".csv")?;diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex dfc7a66570..2a0c39aa48 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -254,12 +254,9 @@ mod tests {let right_rows = right.collect().await?;let join = left.join(right, JoinType::Inner, &["c1"], &["c1"])?;let join_rows = join.collect().await?;- assert_eq!(1, left_rows.len());- assert_eq!(100, left_rows[0].num_rows());- assert_eq!(1, right_rows.len());- assert_eq!(100, right_rows[0].num_rows());- assert_eq!(1, join_rows.len());- assert_eq!(2008, join_rows[0].num_rows());+ assert_eq!(100, left_rows.iter().map(|x| x.num_rows()).sum::<usize>());+ assert_eq!(100, right_rows.iter().map(|x| x.num_rows()).sum::<usize>());+ assert_eq!(2008, join_rows.iter().map(|x| x.num_rows()).sum::<usize>());Ok(())}diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex e748872882..fed82fd23b 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -264,11 +264,7 @@ impl LogicalPlanBuilder {Ok(Self::from(&LogicalPlan::Join {left: Arc::new(self.plan.clone()),right: Arc::new(right.clone()),- on: left_keys- .iter()- .zip(right_keys.iter())- .map(|(l, r)| (l.to_string(), r.to_string()))- .collect(),+ on,join_type,schema: DFSchemaRef::new(join_schema),}))diff --git a/rust/datafusion/src/physical_plan/hash_join.rs b/rust/datafusion/src/physical_plan/hash_join.rsindex 91c01c4286..401fe6580a 100644--- a/rust/datafusion/src/physical_plan/hash_join.rs+++ b/rust/datafusion/src/physical_plan/hash_join.rs@@ -86,6 +86,17 @@ pub struct HashJoinExec {build_side: Arc<Mutex<Option<JoinLeftData>>>,/// Shares the `RandomState` for the hashing algorithmrandom_state: RandomState,+ /// Partitioning mode to use+ mode: PartitionMode,+}++#[derive(Clone, Copy, Debug, PartialEq)]+/// Partitioning mode to use for hash join+pub enum PartitionMode {+ /// Left/right children are partitioned using the left and right keys+ Partitioned,+ /// Left side will collected into one partition+ CollectLeft,}/// Information about the index and placement (left or right) of the columns@@ -105,6 +116,7 @@ impl HashJoinExec {right: Arc<dyn ExecutionPlan>,on: &JoinOn,join_type: &JoinType,+ partition_mode: PartitionMode,) -> Result<Self> {let left_schema = left.schema();let right_schema = right.schema();@@ -122,7 +134,7 @@ impl HashJoinExec {.map(|(l, r)| (l.to_string(), r.to_string())).collect();- let random_state = RandomState::new();+ let random_state = RandomState::with_seeds(0, 0, 0, 0);Ok(HashJoinExec {left,@@ -132,6 +144,7 @@ impl HashJoinExec {schema,build_side: Arc::new(Mutex::new(None)),random_state,+ mode: partition_mode,})}@@ -210,6 +223,7 @@ impl ExecutionPlan for HashJoinExec {children[1].clone(),&self.on,&self.join_type,+ self.mode,)?)),_ => Err(DataFusionError::Internal("HashJoinExec wrong number of children".to_string(),@@ -223,18 +237,76 @@ impl ExecutionPlan for HashJoinExec {async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {let on_left = self.on.iter().map(|on| on.0.clone()).collect::<Vec<_>>();-- // we only want to compute the build side once+ // we only want to compute the build side once for PartitionMode::CollectLeftlet left_data = {- let mut build_side = self.build_side.lock().await;- match build_side.as_ref() {- Some(stream) => stream.clone(),- None => {+ match self.mode {+ PartitionMode::CollectLeft => {+ let mut build_side = self.build_side.lock().await;++ match build_side.as_ref() {+ Some(stream) => stream.clone(),+ None => {+ let start = Instant::now();++ // merge all left parts into a single stream+ 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::with_hasher(IdHashBuilder {}),+ Vec::new(),+ 0,+ Vec::new(),+ );+ let (hashmap, batches, num_rows, _) = stream+ .try_fold(initial, |mut acc, batch| async {+ let hash = &mut acc.0;+ let values = &mut acc.1;+ let offset = acc.2;+ acc.3.clear();+ acc.3.resize(batch.num_rows(), 0);+ update_hash(+ &on_left,+ &batch,+ hash,+ offset,+ &self.random_state,+ &mut acc.3,+ )+ .unwrap();+ acc.2 += batch.num_rows();+ values.push(batch);+ Ok(acc)+ })+ .await?;++ // Merge all batches into a single batch, so we+ // can directly index into the arrays+ let single_batch =+ concat_batches(&self.left.schema(), &batches, num_rows)?;++ let left_side = Arc::new((hashmap, single_batch));++ *build_side = Some(left_side.clone());++ debug!(+ "Built build-side of hash join containing {} rows in {} ms",+ num_rows,+ start.elapsed().as_millis()+ );++ left_side+ }+ }+ }+ PartitionMode::Partitioned => {let start = Instant::now();- // merge all left parts into a single stream- let merge = MergeExec::new(self.left.clone());- let stream = merge.execute(0).await?;+ // Load 1 partition of left side in memory+ let stream = self.left.execute(partition).await?;// This operation performs 2 steps at once:// 1. creates a [JoinHashMap] of all batches from the stream@@ -274,10 +346,9 @@ impl ExecutionPlan for HashJoinExec {let left_side = Arc::new((hashmap, single_batch));- *build_side = Some(left_side.clone());-debug!(- "Built build-side of hash join containing {} rows in {} ms",+ "Built build-side {} of hash join containing {} rows in {} ms",+ partition,num_rows,start.elapsed().as_millis());@@ -849,7 +920,7 @@ mod tests {.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect();- HashJoinExec::try_new(left, right, &on, join_type)+ HashJoinExec::try_new(left, right, &on, join_type, PartitionMode::CollectLeft)}#[tokio::test]diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex a24ef2942e..0ab67c41a5 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -20,7 +20,8 @@use std::sync::Arc;use super::{- aggregates, empty::EmptyExec, expressions::binary, functions, udaf, union::UnionExec,+ aggregates, empty::EmptyExec, expressions::binary, functions,+ hash_join::PartitionMode, udaf, union::UnionExec,};use crate::error::{DataFusionError, Result};use crate::execution::context::ExecutionContextState;@@ -344,13 +345,34 @@ impl DefaultPhysicalPlanner {JoinType::Left => hash_utils::JoinType::Left,JoinType::Right => hash_utils::JoinType::Right,};-- Ok(Arc::new(HashJoinExec::try_new(- left,- right,- &keys,- &physical_join_type,- )?))+ if ctx_state.config.concurrency > 1 && ctx_state.config.repartition_joins+ {+ let left_expr = keys.iter().map(|x| col(&x.0)).collect();+ let right_expr = keys.iter().map(|x| col(&x.1)).collect();++ // Use hash partition by defualt to parallelize hash joins+ Ok(Arc::new(HashJoinExec::try_new(+ Arc::new(RepartitionExec::try_new(+ left,+ Partitioning::Hash(left_expr, ctx_state.config.concurrency),+ )?),+ Arc::new(RepartitionExec::try_new(+ right,+ Partitioning::Hash(right_expr, ctx_state.config.concurrency),+ )?),+ &keys,+ &physical_join_type,+ PartitionMode::Partitioned,+ )?))+ } else {+ Ok(Arc::new(HashJoinExec::try_new(+ left,+ right,+ &keys,+ &physical_join_type,+ PartitionMode::CollectLeft,+ )?))+ }}LogicalPlan::EmptyRelation {produce_one_row,diff --git a/rust/datafusion/src/physical_plan/repartition.rs b/rust/datafusion/src/physical_plan/repartition.rsindex f21a1443db..7243550127 100644--- a/rust/datafusion/src/physical_plan/repartition.rs+++ b/rust/datafusion/src/physical_plan/repartition.rs@@ -129,7 +129,8 @@ impl ExecutionPlan for RepartitionExec {>();channels.insert(partition, (sender, receiver));}- let random = ahash::RandomState::new();+ // Use fixed random state+ let random = ahash::RandomState::with_seeds(0, 0, 0, 0);// launch one async task per *input* partitionfor i in 0..num_input_partitions {@@ -143,6 +144,8 @@ impl ExecutionPlan for RepartitionExec {let _: JoinHandle<Result<()>> = tokio::spawn(async move {let mut stream = input.execute(i).await?;let mut counter = 0;+ let hashes_buf = &mut vec![];+while let Some(result) = stream.next().await {match &partitioning {Partitioning::RoundRobinBatch(_) => {@@ -162,8 +165,9 @@ impl ExecutionPlan for RepartitionExec {.into_array(input_batch.num_rows()))}).collect::<Result<Vec<_>>>()?;+ hashes_buf.clear();+ hashes_buf.resize(arrays[0].len(), 0);// Hash arrays and compute buckets based on number of partitions- let hashes_buf = &mut vec![0; arrays[0].len()];let hashes =create_hashes(&arrays, &random_state, hashes_buf)?;let mut indices = vec![vec![]; num_output_partitions];diff --git a/rust/datafusion/tests/dataframe.rs b/rust/datafusion/tests/dataframe.rsindex 9d5f92a775..b93e21f4ab 100644--- a/rust/datafusion/tests/dataframe.rs+++ b/rust/datafusion/tests/dataframe.rs@@ -72,7 +72,8 @@ async fn join() -> Result<()> {let a = df1.join(df2, JoinType::Inner, &["a"], &["a"])?;let batches = a.collect().await?;- assert_eq!(batches.len(), 1);++ assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 4);Ok(())}