Apache DataFusion SQL Query Engine
ARROW-10717 [Rust] [DataFusion] Add support for right join
Jorge C. Leitao7c442a29c143
diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex b36a189203..37b82b1a80 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -204,6 +204,7 @@ impl LogicalPlanBuilder {let physical_join_type = match join_type {JoinType::Inner => hash_utils::JoinType::Inner,JoinType::Left => hash_utils::JoinType::Left,+ JoinType::Right => hash_utils::JoinType::Right,};let physical_schema = hash_utils::build_join_schema(self.plan.schema(),diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rsindex 9378fc01a7..075c9dd436 100644--- a/rust/datafusion/src/logical_plan/plan.rs+++ b/rust/datafusion/src/logical_plan/plan.rs@@ -48,6 +48,8 @@ pub enum JoinType {Inner,/// Left joinLeft,+ /// Right join+ Right,}/// A LogicalPlan represents the different types of relationaldiff --git a/rust/datafusion/src/physical_plan/hash_join.rs b/rust/datafusion/src/physical_plan/hash_join.rsindex b36b9eead8..22dcf84986 100644--- a/rust/datafusion/src/physical_plan/hash_join.rs+++ b/rust/datafusion/src/physical_plan/hash_join.rs@@ -252,6 +252,7 @@ fn build_batch_from_indices(schema: &Schema,left: &Vec<RecordBatch>,right: &RecordBatch,+ join_type: &JoinType,indices: &[(JoinIndex, JoinIndex)],) -> ArrowResult<RecordBatch> {if left.is_empty() {@@ -260,6 +261,11 @@ fn build_batch_from_indices(// this is just for symmetry of the code below.let right = vec![right.clone()];+ let (primary_is_left, primary, secondary) = match join_type {+ JoinType::Inner | JoinType::Left => (true, left, &right),+ JoinType::Right => (false, &right, left),+ };+// build the columns of the new [RecordBatch]:// 1. pick whether the column is from the left or right// 2. based on the pick, `take` items from the different recordBatches@@ -267,11 +273,11 @@ fn build_batch_from_indices(for field in schema.fields() {// pick the column (left or right) based on the field name.// Note that we take `.data()` to gather the [ArrayData] of each array.- let (is_left, arrays) = match left[0].schema().index_of(field.name()) {- Ok(i) => Ok((true, left.iter().map(|batch| batch.column(i).data()).collect::<Vec<_>>())),+ let (is_primary, arrays) = match primary[0].schema().index_of(field.name()) {+ Ok(i) => Ok((true, primary.iter().map(|batch| batch.column(i).data()).collect::<Vec<_>>())),Err(_) => {- match right[0].schema().index_of(field.name()) {- Ok(i) => Ok((false, right.iter().map(|batch| batch.column(i).data()).collect::<Vec<_>>())),+ match secondary[0].schema().index_of(field.name()) {+ Ok(i) => Ok((false, secondary.iter().map(|batch| batch.column(i).data()).collect::<Vec<_>>())),_ => Err(DataFusionError::Internal(format!("During execution, the column {} was not found in neither the left or right side of the join", field.name()).to_string()))@@ -287,25 +293,26 @@ fn build_batch_from_indices(let capacity = arrays.iter().map(|array| array.len()).sum();let mut mutable = MutableArrayData::new(arrays, true, capacity);- let array = if is_left {- // build the array using the left+ let is_left =+ (is_primary && primary_is_left) || (!is_primary && !primary_is_left);+ if is_left {+ // use the left indicesfor (join_index, _) in indices {match join_index {Some((batch, row)) => mutable.extend(*batch, *row, *row + 1),None => mutable.extend_nulls(1),}}- make_array(Arc::new(mutable.freeze()))} else {- // build the array using the right+ // use the right indicesfor (_, join_index) in indices {match join_index {Some((batch, row)) => mutable.extend(*batch, *row, *row + 1),None => mutable.extend_nulls(1),}}- make_array(Arc::new(mutable.freeze()))};+ let array = make_array(Arc::new(mutable.freeze()));columns.push(array);}Ok(RecordBatch::try_new(Arc::new(schema.clone()), columns)?)@@ -323,7 +330,7 @@ fn build_batch(let indices = build_join_indexes(&left_data.0, &right_hash, join_type).unwrap();- build_batch_from_indices(schema, &left_data.1, &batch, &indices)+ build_batch_from_indices(schema, &left_data.1, &batch, join_type, &indices)}/// returns a vector with (index from left, index from right).@@ -384,12 +391,8 @@ fn build_join_indexes(}JoinType::Left => {// left => left keys- let keys = left.keys();-let mut indexes = Vec::new(); // unknown a prior size- for key in keys {- let left_indexes = left.get(key).unwrap();-+ for (key, left_indexes) in left {// for every item on the left and right with this key, add the respective pairif let Some(right_indexes) = right.get(key) {left_indexes.iter().for_each(|x| {@@ -407,6 +410,27 @@ fn build_join_indexes(}Ok(indexes)}+ JoinType::Right => {+ // right => right keys+ let mut indexes = Vec::new(); // unknown a prior size+ for (key, right_indexes) in right {+ // for every item on the left and right with this key, add the respective pair+ if let Some(left_indexes) = left.get(key) {+ left_indexes.iter().for_each(|x| {+ right_indexes.iter().for_each(|y| {+ // on an inner join, left and right indices are present+ indexes.push((Some(*x), Some(*y)));+ })+ })+ } else {+ // key not on the left => push Nones+ right_indexes.iter().for_each(|x| {+ indexes.push((None, Some(*x)));+ })+ }+ }+ Ok(indexes)+ }}}@@ -688,4 +712,34 @@ mod tests {Ok(())}++ #[tokio::test]+ async fn join_right_one() -> Result<()> {+ let left = build_table(+ ("a1", &vec![1, 2, 3]),+ ("b1", &vec![4, 5, 7]),+ ("c1", &vec![7, 8, 9]),+ );+ let right = build_table(+ ("a2", &vec![10, 20, 30]),+ ("b1", &vec![4, 5, 6]), // 6 does not exist on the left+ ("c2", &vec![70, 80, 90]),+ );+ let on = &[("b1", "b1")];++ let join = join(left, right, on, &JoinType::Right)?;++ let columns = columns(&join.schema());+ assert_eq!(columns, vec!["a1", "c1", "a2", "b1", "c2"]);++ let stream = join.execute(0).await?;+ let batches = common::collect(stream).await?;++ let result = format_batch(&batches[0]);+ let expected = vec!["1,7,10,4,70", "2,8,20,5,80", "NULL,NULL,30,6,90"];++ assert_same_rows(&result, &expected);++ Ok(())+ }}diff --git a/rust/datafusion/src/physical_plan/hash_utils.rs b/rust/datafusion/src/physical_plan/hash_utils.rsindex f41b811472..03d37bd702 100644--- a/rust/datafusion/src/physical_plan/hash_utils.rs+++ b/rust/datafusion/src/physical_plan/hash_utils.rs@@ -28,6 +28,8 @@ pub enum JoinType {Inner,/// LeftLeft,+ /// Right+ Right,}/// The on clause of the join, as vector of (left, right) columns.@@ -110,6 +112,24 @@ pub fn build_join_schema(.iter().filter(|f| !duplicate_keys.contains(f.name()));+ // left then right+ left_fields.chain(right_fields).cloned().collect()+ }+ JoinType::Right => {+ // remove left-side join keys if they have the same names as the right-side+ let duplicate_keys = &on+ .iter()+ .filter(|(l, r)| l == r)+ .map(|on| on.1.to_string())+ .collect::<HashSet<_>>();++ let left_fields = left+ .fields()+ .iter()+ .filter(|f| !duplicate_keys.contains(f.name()));++ let right_fields = right.fields().iter();+// left then rightleft_fields.chain(right_fields).cloned().collect()}diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex 3b2488b3fa..7efeaf2a06 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -302,6 +302,7 @@ impl DefaultPhysicalPlanner {let physical_join_type = match join_type {JoinType::Inner => hash_utils::JoinType::Inner,JoinType::Left => hash_utils::JoinType::Left,+ JoinType::Right => hash_utils::JoinType::Right,};Ok(Arc::new(HashJoinExec::try_new(left,