Skip to content

Apache DataFusion SQL Query Engine

Support for non equality predicates in `ON` clause of `LEFT`, `RIGHT, `and `FULL` joins (#2591)

Eduard Karacharovb6fb0dd52c2a
diff --git a/datafusion/core/src/dataframe.rs b/datafusion/core/src/dataframe.rs
index 10d06ca470..c8e0eef303 100644
--- a/datafusion/core/src/dataframe.rs
+++ b/datafusion/core/src/dataframe.rs
@@ -295,7 +295,11 @@ impl DataFrame {
Ok(Arc::new(DataFrame::new(self.session_state.clone(), &plan)))
}
- /// Join this DataFrame with another DataFrame using the specified columns as join keys
+ /// Join this DataFrame with another DataFrame using the specified columns as join keys.
+ ///
+ /// Filter expression expected to contain non-equality predicates that can not be pushed
+ /// down to any of join inputs.
+ /// In case of outer join, filter applied to only matched rows.
///
/// ```
/// # use datafusion::prelude::*;
@@ -309,7 +313,7 @@ impl DataFrame {
/// col("a").alias("a2"),
/// col("b").alias("b2"),
/// col("c").alias("c2")])?;
- /// let join = left.join(right, JoinType::Inner, &["a", "b"], &["a2", "b2"])?;
+ /// let join = left.join(right, JoinType::Inner, &["a", "b"], &["a2", "b2"], None)?;
/// let batches = join.collect().await?;
/// # Ok(())
/// # }
@@ -320,12 +324,14 @@ impl DataFrame {
join_type: JoinType,
left_cols: &[&str],
right_cols: &[&str],
+ filter: Option<Expr>,
) -> Result<Arc<DataFrame>> {
let plan = LogicalPlanBuilder::from(self.plan.clone())
.join(
&right.plan.clone(),
join_type,
(left_cols.to_vec(), right_cols.to_vec()),
+ filter,
)?
.build()?;
Ok(Arc::new(DataFrame::new(self.session_state.clone(), &plan)))
@@ -779,7 +785,7 @@ mod tests {
.select_columns(&["c1", "c3"])?;
let left_rows = left.collect().await?;
let right_rows = right.collect().await?;
- let join = left.join(right, JoinType::Inner, &["c1"], &["c1"])?;
+ let join = left.join(right, JoinType::Inner, &["c1"], &["c1"], None)?;
let join_rows = join.collect().await?;
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>());
diff --git a/datafusion/core/src/optimizer/filter_push_down.rs b/datafusion/core/src/optimizer/filter_push_down.rs
index 9135c31cf7..abfb15dd1b 100644
--- a/datafusion/core/src/optimizer/filter_push_down.rs
+++ b/datafusion/core/src/optimizer/filter_push_down.rs
@@ -1021,6 +1021,7 @@ mod tests {
&right,
JoinType::Inner,
(vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ None,
)?
.filter(col("a").lt_eq(lit(1i64)))?
.build()?;
@@ -1105,6 +1106,7 @@ mod tests {
&right,
JoinType::Inner,
(vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ None,
)?
// "b" and "c" are not shared by either side: they are only available together after the join
.filter(col("c").lt_eq(col("b")))?
@@ -1145,6 +1147,7 @@ mod tests {
&right,
JoinType::Inner,
(vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ None,
)?
.filter(col("b").lt_eq(lit(1i64)))?
.build()?;
@@ -1336,6 +1339,191 @@ mod tests {
Ok(())
}
+ /// single table predicate parts of ON condition should be pushed to both inputs
+ #[ignore]
+ #[test]
+ fn join_on_with_filter() -> Result<()> {
+ let table_scan = test_table_scan()?;
+ let left = LogicalPlanBuilder::from(table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let right_table_scan = test_table_scan_with_name("test2")?;
+ let right = LogicalPlanBuilder::from(right_table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let filter = col("test.a")
+ .gt(lit(1u32))
+ .and(col("test.b").lt(col("test2.b")))
+ .and(col("test2.c").gt(lit(4u32)));
+ let plan = LogicalPlanBuilder::from(left)
+ .join(
+ &right,
+ JoinType::Inner,
+ (vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ Some(filter),
+ )?
+ .build()?;
+
+ // not part of the test, just good to know:
+ assert_eq!(
+ format!("{:?}", plan),
+ "\
+ Inner Join: #test.a = #test2.a Filter: #test.a > UInt32(1) AND #test.b < #test2.b AND #test2.c > UInt32(4)\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n TableScan: test2 projection=None"
+ );
+
+ let expected = "\
+ Inner Join: #test.a = #test2.a Filter: #test.b < #test2.b\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n Filter: #test.a > UInt32(1)\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n Filter: #test2.c > UInt32(4)\
+ \n TableScan: test2 projection=None";
+ assert_optimized_plan_eq(&plan, expected);
+ Ok(())
+ }
+
+ /// single table predicate parts of ON condition should be pushed to right input
+ /// https://github.com/apache/arrow-datafusion/issues/2619
+ #[ignore]
+ #[test]
+ fn left_join_on_with_filter() -> Result<()> {
+ let table_scan = test_table_scan()?;
+ let left = LogicalPlanBuilder::from(table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let right_table_scan = test_table_scan_with_name("test2")?;
+ let right = LogicalPlanBuilder::from(right_table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let filter = col("test.a")
+ .gt(lit(1u32))
+ .and(col("test.b").lt(col("test2.b")))
+ .and(col("test2.c").gt(lit(4u32)));
+ let plan = LogicalPlanBuilder::from(left)
+ .join(
+ &right,
+ JoinType::Left,
+ (vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ Some(filter),
+ )?
+ .build()?;
+
+ // not part of the test, just good to know:
+ assert_eq!(
+ format!("{:?}", plan),
+ "\
+ Left Join: #test.a = #test2.a Filter: #test.a > UInt32(1) AND #test.b < #test2.b AND #test2.c > UInt32(4)\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n TableScan: test2 projection=None"
+ );
+
+ let expected = "\
+ Left Join: #test.a = #test2.a Filter: #test.a > UInt32(1) AND #test.b < #test2.b\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n Filter: #test2.c > UInt32(4)\
+ \n TableScan: test2 projection=None";
+ assert_optimized_plan_eq(&plan, expected);
+ Ok(())
+ }
+
+ /// single table predicate parts of ON condition should be pushed to left input
+ /// https://github.com/apache/arrow-datafusion/issues/2619
+ #[ignore]
+ #[test]
+ fn right_join_on_with_filter() -> Result<()> {
+ let table_scan = test_table_scan()?;
+ let left = LogicalPlanBuilder::from(table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let right_table_scan = test_table_scan_with_name("test2")?;
+ let right = LogicalPlanBuilder::from(right_table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let filter = col("test.a")
+ .gt(lit(1u32))
+ .and(col("test.b").lt(col("test2.b")))
+ .and(col("test2.c").gt(lit(4u32)));
+ let plan = LogicalPlanBuilder::from(left)
+ .join(
+ &right,
+ JoinType::Right,
+ (vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ Some(filter),
+ )?
+ .build()?;
+
+ // not part of the test, just good to know:
+ assert_eq!(
+ format!("{:?}", plan),
+ "\
+ Right Join: #test.a = #test2.a Filter: #test.a > UInt32(1) AND #test.b < #test2.b AND #test2.c > UInt32(4)\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n TableScan: test2 projection=None"
+ );
+
+ let expected = "\
+ Right Join: #test.a = #test2.a Filter: #test.b < #test2.b AND #test2.c > UInt32(4)\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n Filter: #test.a > UInt32(1)\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n TableScan: test2 projection=None";
+ assert_optimized_plan_eq(&plan, expected);
+ Ok(())
+ }
+
+ /// single table predicate parts of ON condition should not be pushed
+ /// https://github.com/apache/arrow-datafusion/issues/2619
+ #[test]
+ fn full_join_on_with_filter() -> Result<()> {
+ let table_scan = test_table_scan()?;
+ let left = LogicalPlanBuilder::from(table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let right_table_scan = test_table_scan_with_name("test2")?;
+ let right = LogicalPlanBuilder::from(right_table_scan)
+ .project(vec![col("a"), col("b"), col("c")])?
+ .build()?;
+ let filter = col("test.a")
+ .gt(lit(1u32))
+ .and(col("test.b").lt(col("test2.b")))
+ .and(col("test2.c").gt(lit(4u32)));
+ let plan = LogicalPlanBuilder::from(left)
+ .join(
+ &right,
+ JoinType::Full,
+ (vec![Column::from_name("a")], vec![Column::from_name("a")]),
+ Some(filter),
+ )?
+ .build()?;
+
+ // not part of the test, just good to know:
+ assert_eq!(
+ format!("{:?}", plan),
+ "\
+ Full Join: #test.a = #test2.a Filter: #test.a > UInt32(1) AND #test.b < #test2.b AND #test2.c > UInt32(4)\
+ \n Projection: #test.a, #test.b, #test.c\
+ \n TableScan: test projection=None\
+ \n Projection: #test2.a, #test2.b, #test2.c\
+ \n TableScan: test2 projection=None"
+ );
+
+ let expected = &format!("{:?}", plan);
+ assert_optimized_plan_eq(&plan, expected);
+ Ok(())
+ }
+
struct PushDownProvider {
pub filter_support: TableProviderFilterPushDown,
}
diff --git a/datafusion/core/src/optimizer/limit_push_down.rs b/datafusion/core/src/optimizer/limit_push_down.rs
index 31748d326b..725e00a004 100644
--- a/datafusion/core/src/optimizer/limit_push_down.rs
+++ b/datafusion/core/src/optimizer/limit_push_down.rs
@@ -199,6 +199,7 @@ fn generate_push_down_join(
left,
right,
on,
+ filter,
join_type,
join_constraint,
schema,
@@ -221,6 +222,7 @@ fn generate_push_down_join(
true,
)?),
on: on.clone(),
+ filter: filter.clone(),
join_type: *join_type,
join_constraint: *join_constraint,
schema: schema.clone(),
@@ -506,6 +508,7 @@ mod test {
&LogicalPlanBuilder::from(table_scan_2).build()?,
JoinType::Inner,
(vec!["a"], vec!["a"]),
+ None,
)?
.limit(1000)?
.offset(10)?
@@ -564,6 +567,7 @@ mod test {
&LogicalPlanBuilder::from(table_scan_2).build()?,
JoinType::Left,
(vec!["a"], vec!["a"]),
+ None,
)?
.limit(1000)?
.build()?;
@@ -589,6 +593,7 @@ mod test {
&LogicalPlanBuilder::from(table_scan_2).build()?,
JoinType::Right,
(vec!["a"], vec!["a"]),
+ None,
)?
.limit(1000)?
.build()?;
diff --git a/datafusion/core/src/optimizer/projection_push_down.rs b/datafusion/core/src/optimizer/projection_push_down.rs
index 5a127df6da..494b7dd640 100644
--- a/datafusion/core/src/optimizer/projection_push_down.rs
+++ b/datafusion/core/src/optimizer/projection_push_down.rs
@@ -206,6 +206,7 @@ fn optimize_plan(
left,
right,
on,
+ filter,
join_type,
join_constraint,
null_equals_null,
@@ -216,6 +217,10 @@ fn optimize_plan(
new_required_columns.insert(r.clone());
}
+ if let Some(expr) = filter {
+ expr_to_columns(expr, &mut new_required_columns)?;
+ }
+
let optimized_left = Arc::new(optimize_plan(
_optimizer,
left,
@@ -244,6 +249,7 @@ fn optimize_plan(
join_type: *join_type,
join_constraint: *join_constraint,
on: on.clone(),
+ filter: filter.clone(),
schema: DFSchemaRef::new(schema),
null_equals_null: *null_equals_null,
}))
@@ -650,7 +656,7 @@ mod tests {
let table2_scan = scan_empty(Some("test2"), &schema, None)?.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
- .join(&table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]))?
+ .join(&table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]), None)?
.project(vec![col("a"), col("b"), col("c1")])?
.build()?;
@@ -691,7 +697,7 @@ mod tests {
let table2_scan = scan_empty(Some("test2"), &schema, None)?.build()?;
let plan = LogicalPlanBuilder::from(table_scan)
- .join(&table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]))?
+ .join(&table2_scan, JoinType::Left, (vec!["a"], vec!["c1"]), None)?
// projecting joined column `a` should push the right side column `c1` projection as
// well into test2 table even though `c1` is not referenced in projection.
.project(vec![col("a"), col("b")])?
diff --git a/datafusion/core/src/optimizer/subquery_filter_to_join.rs b/datafusion/core/src/optimizer/subquery_filter_to_join.rs
index 5f4583c28f..6454425191 100644
--- a/datafusion/core/src/optimizer/subquery_filter_to_join.rs
+++ b/datafusion/core/src/optimizer/subquery_filter_to_join.rs
@@ -132,6 +132,7 @@ impl OptimizerRule for SubqueryFilterToJoin {
left: Arc::new(input),
right: Arc::new(right_input),
on: vec![(left_key, right_key)],
+ filter: None,
join_type,
join_constraint: JoinConstraint::On,
schema: Arc::new(schema),
diff --git a/datafusion/core/src/physical_optimizer/hash_build_probe_order.rs b/datafusion/core/src/physical_optimizer/hash_build_probe_order.rs
index 565a955235..da626972f7 100644
--- a/datafusion/core/src/physical_optimizer/hash_build_probe_order.rs
+++ b/datafusion/core/src/physical_optimizer/hash_build_probe_order.rs
@@ -25,6 +25,7 @@ use crate::logical_plan::JoinType;
use crate::physical_plan::cross_join::CrossJoinExec;
use crate::physical_plan::expressions::Column;
use crate::physical_plan::hash_join::HashJoinExec;
+use crate::physical_plan::join_utils::{ColumnIndex, JoinFilter, JoinSide};
use crate::physical_plan::projection::ProjectionExec;
use crate::physical_plan::{ExecutionPlan, PhysicalExpr};
@@ -109,6 +110,36 @@ fn swap_reverting_projection(
left_cols.chain(right_cols).collect()
}
+/// Swaps join sides for filter column indices and produces new JoinFilter
+fn swap_join_filter(filter: &Option<JoinFilter>) -> Option<JoinFilter> {
+ match filter {
+ Some(filter) => {
+ let column_indices = filter
+ .column_indices()
+ .iter()
+ .map(|idx| {
+ let side = if matches!(idx.side, JoinSide::Left) {
+ JoinSide::Right
+ } else {
+ JoinSide::Left
+ };
+ ColumnIndex {
+ index: idx.index,
+ side,
+ }
+ })
+ .collect();
+
+ Some(JoinFilter::new(
+ filter.expression().clone(),
+ column_indices,
+ filter.schema().clone(),
+ ))
+ }
+ None => None,
+ }
+}
+
impl PhysicalOptimizerRule for HashBuildProbeOrder {
fn optimize(
&self,
@@ -130,6 +161,7 @@ impl PhysicalOptimizerRule for HashBuildProbeOrder {
.iter()
.map(|(l, r)| (r.clone(), l.clone()))
.collect(),
+ swap_join_filter(hash_join.filter()),
&swap_join_type(*hash_join.join_type()),
*hash_join.partition_mode(),
hash_join.null_equals_null(),
@@ -205,6 +237,7 @@ mod tests {
Column::new_with_schema("big_col", &big.schema()).unwrap(),
Column::new_with_schema("small_col", &small.schema()).unwrap(),
)],
+ None,
&JoinType::Left,
PartitionMode::CollectLeft,
&false,
@@ -252,6 +285,7 @@ mod tests {
Column::new_with_schema("small_col", &small.schema()).unwrap(),
Column::new_with_schema("big_col", &big.schema()).unwrap(),
)],
+ None,
&JoinType::Left,
PartitionMode::CollectLeft,
&false,
diff --git a/datafusion/core/src/physical_plan/hash_join.rs b/datafusion/core/src/physical_plan/hash_join.rs
index ee763241ae..155d1c740b 100644
--- a/datafusion/core/src/physical_plan/hash_join.rs
+++ b/datafusion/core/src/physical_plan/hash_join.rs
@@ -36,7 +36,7 @@ use std::{time::Instant, vec};
use futures::{ready, Stream, StreamExt, TryStreamExt};
-use arrow::array::{new_null_array, Array};
+use arrow::array::{as_boolean_array, new_null_array, Array};
use arrow::datatypes::DataType;
use arrow::datatypes::{Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
@@ -53,7 +53,9 @@ use hashbrown::raw::RawTable;
use super::{
coalesce_partitions::CoalescePartitionsExec,
expressions::PhysicalSortExpr,
- join_utils::{build_join_schema, check_join_is_valid, ColumnIndex, JoinOn, JoinSide},
+ join_utils::{
+ build_join_schema, check_join_is_valid, ColumnIndex, JoinFilter, JoinOn, JoinSide,
+ },
};
use super::{
expressions::Column,
@@ -75,6 +77,7 @@ use crate::physical_plan::PhysicalExpr;
use crate::physical_plan::join_utils::{OnceAsync, OnceFut};
use log::debug;
+use std::cmp;
use std::fmt;
use std::task::Poll;
@@ -100,8 +103,12 @@ impl fmt::Debug for JoinHashMap {
type JoinLeftData = (JoinHashMap, RecordBatch);
-/// join execution plan executes partitions in parallel and combines them into a set of
+/// Join execution plan executes partitions in parallel and combines them into a set of
/// partitions.
+///
+/// Filter expression expected to contain non-equality predicates that can not be pushed
+/// down to any of join inputs.
+/// In case of outer join, filter applied to only matched rows.
#[derive(Debug)]
pub struct HashJoinExec {
/// left (build) side which gets hashed
@@ -110,6 +117,8 @@ pub struct HashJoinExec {
right: Arc<dyn ExecutionPlan>,
/// Set of common columns used to join on
on: Vec<(Column, Column)>,
+ /// Filters which are applied while finding matching rows
+ filter: Option<JoinFilter>,
/// How the join is performed
join_type: JoinType,
/// The schema once the join is applied
@@ -184,6 +193,7 @@ impl HashJoinExec {
left: Arc<dyn ExecutionPlan>,
right: Arc<dyn ExecutionPlan>,
on: JoinOn,
+ filter: Option<JoinFilter>,
join_type: &JoinType,
partition_mode: PartitionMode,
null_equals_null: &bool,
@@ -207,6 +217,7 @@ impl HashJoinExec {
left,
right,
on,
+ filter,
join_type: *join_type,
schema: Arc::new(schema),
left_fut: Default::default(),
@@ -233,6 +244,11 @@ impl HashJoinExec {
&self.on
}
+ /// Filters applied before join output
+ pub fn filter(&self) -> &Option<JoinFilter> {
+ &self.filter
+ }
+
/// How the join is performed
pub fn join_type(&self) -> &JoinType {
&self.join_type
@@ -270,6 +286,7 @@ impl ExecutionPlan for HashJoinExec {
children[0].clone(),
children[1].clone(),
self.on.clone(),
+ self.filter.clone(),
&self.join_type,
self.mode,
&self.null_equals_null,
@@ -322,6 +339,7 @@ impl ExecutionPlan for HashJoinExec {
schema: self.schema(),
on_left,
on_right,
+ filter: self.filter.clone(),
join_type: self.join_type,
left_fut,
visited_left_side: None,
@@ -341,10 +359,14 @@ impl ExecutionPlan for HashJoinExec {
) -> std::fmt::Result {
match t {
DisplayFormatType::Default => {
+ let display_filter = self.filter.as_ref().map_or_else(
+ || "".to_string(),
+ |f| format!(", filter={:?}", f.expression()),
+ );
write!(
f,
- "HashJoinExec: mode={:?}, join_type={:?}, on={:?}",
- self.mode, self.join_type, self.on
+ "HashJoinExec: mode={:?}, join_type={:?}, on={:?}{}",
+ self.mode, self.join_type, self.on, display_filter
)
}
}
@@ -517,6 +539,8 @@ struct HashJoinStream {
on_left: Vec<Column>,
/// columns from the right used to compute the hash
on_right: Vec<Column>,
+ /// join filter
+ filter: Option<JoinFilter>,
/// type of the join
join_type: JoinType,
/// future for data from left side
@@ -596,6 +620,7 @@ fn build_batch(
left_data: &JoinLeftData,
on_left: &[Column],
on_right: &[Column],
+ filter: &Option<JoinFilter>,
join_type: JoinType,
schema: &Schema,
column_indices: &[ColumnIndex],
@@ -620,12 +645,26 @@ fn build_batch(
));
}
+ let (left_filtered_indices, right_filtered_indices) = if let Some(filter) = filter {
+ apply_join_filter(
+ &left_data.1,
+ batch,
+ join_type,
+ left_indices,
+ right_indices,
+ filter,
+ )
+ .unwrap()
+ } else {
+ (left_indices, right_indices)
+ };
+
build_batch_from_indices(
schema,
&left_data.1,
batch,
- left_indices,
- right_indices,
+ left_filtered_indices,
+ right_filtered_indices,
column_indices,
)
}
@@ -791,6 +830,109 @@ fn build_join_indexes(
}
}
+fn apply_join_filter(
+ left: &RecordBatch,
+ right: &RecordBatch,
+ join_type: JoinType,
+ left_indices: UInt64Array,
+ right_indices: UInt32Array,
+ filter: &JoinFilter,
+) -> Result<(UInt64Array, UInt32Array)> {
+ if left_indices.is_empty() {
+ return Ok((left_indices, right_indices));
+ };
+
+ let (intermediate_batch, _) = build_batch_from_indices(
+ filter.schema(),
+ left,
+ right,
+ PrimitiveArray::from(left_indices.data().clone()),
+ PrimitiveArray::from(right_indices.data().clone()),
+ filter.column_indices(),
+ )?;
+
+ match join_type {
+ JoinType::Inner | JoinType::Left => {
+ // For both INNER and LEFT joins, input arrays contains only indices for matched data.
+ // Due to this fact it's correct to simply apply filter to intermediate batch and return
+ // indices for left/right rows satisfying filter predicate
+ let filter_result = filter
+ .expression()
+ .evaluate(&intermediate_batch)?
+ .into_array(intermediate_batch.num_rows());
+ let mask = as_boolean_array(&filter_result);
+
+ let left_filtered = PrimitiveArray::<UInt64Type>::from(
+ compute::filter(&left_indices, mask)?.data().clone(),
+ );
+ let right_filtered = PrimitiveArray::<UInt32Type>::from(
+ compute::filter(&right_indices, mask)?.data().clone(),
+ );
+
+ Ok((left_filtered, right_filtered))
+ }
+ JoinType::Right | JoinType::Full => {
+ // In case of RIGHT and FULL join, left_indices could contain null values - these rows,
+ // where no match has been found, should retain in result arrays (thus join condition is satified)
+ //
+ // So, filter should be applied only to matched rows, and in case right (outer, batch) index
+ // doesn't have a single match after filtering, it should be added back to result arrays as
+ // (null, idx) pair.
+ let has_match = compute::is_not_null(&left_indices)?;
+ let filter_result = filter
+ .expression()
+ .evaluate_selection(&intermediate_batch, &has_match)?
+ .into_array(intermediate_batch.num_rows());
+ let mask = as_boolean_array(&filter_result);
+
+ let mut left_rebuilt = UInt64Builder::new(0);
+ let mut right_rebuilt = UInt32Builder::new(0);
+
+ (0..right_indices.len())
+ .into_iter()
+ .try_fold::<_, _, Result<_>>(
+ (right_indices.value(0), false),
+ |state, pos| {
+ // If row index changes and row doesnt have match
+ // append (idx, null)
+ if right_indices.value(pos) != state.0 && !state.1 {
+ right_rebuilt.append_value(state.0)?;
+ left_rebuilt.append_null()?;
+ }
+ // If has match append matched row indices
+ if mask.value(pos) {
+ right_rebuilt.append_value(right_indices.value(pos))?;
+ left_rebuilt.append_value(left_indices.value(pos))?;
+ };
+
+ // Calculate if current row index has match
+ let has_match = if right_indices.value(pos) != state.0 {
+ mask.value(pos)
+ } else {
+ cmp::max(mask.value(pos), state.1)
+ };
+
+ Ok((right_indices.value(pos), has_match))
+ },
+ )
+ // Append last row from right side if no match found
+ .and_then(|(row_idx, has_match)| {
+ if !has_match {
+ right_rebuilt.append_value(row_idx)?;
+ left_rebuilt.append_null()?;
+ }
+ Ok(())
+ })?;
+
+ Ok((left_rebuilt.finish(), right_rebuilt.finish()))
+ }
+ _ => Err(DataFusionError::NotImplemented(format!(
+ "Unexpected filter in {} join",
+ join_type
+ ))),
+ }
+}
+
macro_rules! equal_rows_elem {
($array_type:ident, $l: ident, $r: ident, $left: ident, $right: ident, $null_equals_null: ident) => {{
let left_array = $l.as_any().downcast_ref::<$array_type>().unwrap();
@@ -991,6 +1133,7 @@ impl HashJoinStream {
left_data,
&self.on_left,
&self.on_right,
+ &self.filter,
self.join_type,
&self.schema,
&self.column_indices,
@@ -1074,6 +1217,7 @@ impl Stream for HashJoinStream {
#[cfg(test)]
mod tests {
+ use crate::physical_expr::expressions::BinaryExpr;
use crate::{
assert_batches_sorted_eq,
physical_plan::{
@@ -1081,6 +1225,8 @@ mod tests {
},
test::{build_table_i32, columns},
};
+ use arrow::datatypes::Field;
+ use datafusion_expr::Operator;
use super::*;
use crate::prelude::SessionContext;
@@ -1107,6 +1253,26 @@ mod tests {
left,
right,
on,
+ None,
+ join_type,
+ PartitionMode::CollectLeft,
+ &null_equals_null,
+ )
+ }
+
+ fn join_with_filter(
+ left: Arc<dyn ExecutionPlan>,
+ right: Arc<dyn ExecutionPlan>,
+ on: JoinOn,
+ filter: JoinFilter,
+ join_type: &JoinType,
+ null_equals_null: bool,
+ ) -> Result<HashJoinExec> {
+ HashJoinExec::try_new(
+ left,
+ right,
+ on,
+ Some(filter),
join_type,
PartitionMode::CollectLeft,
&null_equals_null,
@@ -1160,6 +1326,7 @@ mod tests {
Partitioning::Hash(right_expr, partition_count),
)?),
on,
+ None,
join_type,
PartitionMode::Partitioned,
&null_equals_null,
@@ -2031,4 +2198,202 @@ mod tests {
Ok(())
}
+
+ fn prepare_join_filter() -> JoinFilter {
+ let column_indices = vec![
+ ColumnIndex {
+ index: 2,
+ side: JoinSide::Left,
+ },
+ ColumnIndex {
+ index: 2,
+ side: JoinSide::Right,
+ },
+ ];
+ let intermediate_schema = Schema::new(vec![
+ Field::new("c", DataType::Int32, false),
+ Field::new("c", DataType::Int32, false),
+ ]);
+ let filter_expression = Arc::new(BinaryExpr::new(
+ Arc::new(Column::new("c", 0)),
+ Operator::Gt,
+ Arc::new(Column::new("c", 1)),
+ )) as Arc<dyn PhysicalExpr>;
+
+ JoinFilter::new(filter_expression, column_indices, intermediate_schema)
+ }
+
+ #[tokio::test]
+ async fn join_inner_with_filter() -> Result<()> {
+ let session_ctx = SessionContext::new();
+ let task_ctx = session_ctx.task_ctx();
+ let left = build_table(
+ ("a", &vec![0, 1, 2, 2]),
+ ("b", &vec![4, 5, 7, 8]),
+ ("c", &vec![7, 8, 9, 1]),
+ );
+ let right = build_table(
+ ("a", &vec![10, 20, 30, 40]),
+ ("b", &vec![2, 2, 3, 4]),
+ ("c", &vec![7, 5, 6, 4]),
+ );
+ let on = vec![(
+ Column::new_with_schema("a", &left.schema()).unwrap(),
+ Column::new_with_schema("b", &right.schema()).unwrap(),
+ )];
+ let filter = prepare_join_filter();
+
+ let join = join_with_filter(left, right, on, filter, &JoinType::Inner, false)?;
+
+ let columns = columns(&join.schema());
+ assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
+
+ let stream = join.execute(0, task_ctx)?;
+ let batches = common::collect(stream).await?;
+
+ let expected = vec![
+ "+---+---+---+----+---+---+",
+ "| a | b | c | a | b | c |",
+ "+---+---+---+----+---+---+",
+ "| 2 | 7 | 9 | 10 | 2 | 7 |",
+ "| 2 | 7 | 9 | 20 | 2 | 5 |",
+ "+---+---+---+----+---+---+",
+ ];
+ assert_batches_sorted_eq!(expected, &batches);
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn join_left_with_filter() -> Result<()> {
+ let session_ctx = SessionContext::new();
+ let task_ctx = session_ctx.task_ctx();
+ let left = build_table(
+ ("a", &vec![0, 1, 2, 2]),
+ ("b", &vec![4, 5, 7, 8]),
+ ("c", &vec![7, 8, 9, 1]),
+ );
+ let right = build_table(
+ ("a", &vec![10, 20, 30, 40]),
+ ("b", &vec![2, 2, 3, 4]),
+ ("c", &vec![7, 5, 6, 4]),
+ );
+ let on = vec![(
+ Column::new_with_schema("a", &left.schema()).unwrap(),
+ Column::new_with_schema("b", &right.schema()).unwrap(),
+ )];
+ let filter = prepare_join_filter();
+
+ let join = join_with_filter(left, right, on, filter, &JoinType::Left, false)?;
+
+ let columns = columns(&join.schema());
+ assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
+
+ let stream = join.execute(0, task_ctx)?;
+ let batches = common::collect(stream).await?;
+
+ let expected = vec![
+ "+---+---+---+----+---+---+",
+ "| a | b | c | a | b | c |",
+ "+---+---+---+----+---+---+",
+ "| 0 | 4 | 7 | | | |",
+ "| 1 | 5 | 8 | | | |",
+ "| 2 | 7 | 9 | 10 | 2 | 7 |",
+ "| 2 | 7 | 9 | 20 | 2 | 5 |",
+ "| 2 | 8 | 1 | | | |",
+ "+---+---+---+----+---+---+",
+ ];
+ assert_batches_sorted_eq!(expected, &batches);
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn join_right_with_filter() -> Result<()> {
+ let session_ctx = SessionContext::new();
+ let task_ctx = session_ctx.task_ctx();
+ let left = build_table(
+ ("a", &vec![0, 1, 2, 2]),
+ ("b", &vec![4, 5, 7, 8]),
+ ("c", &vec![7, 8, 9, 1]),
+ );
+ let right = build_table(
+ ("a", &vec![10, 20, 30, 40]),
+ ("b", &vec![2, 2, 3, 4]),
+ ("c", &vec![7, 5, 6, 4]),
+ );
+ let on = vec![(
+ Column::new_with_schema("a", &left.schema()).unwrap(),
+ Column::new_with_schema("b", &right.schema()).unwrap(),
+ )];
+ let filter = prepare_join_filter();
+
+ let join = join_with_filter(left, right, on, filter, &JoinType::Right, false)?;
+
+ let columns = columns(&join.schema());
+ assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
+
+ let stream = join.execute(0, task_ctx)?;
+ let batches = common::collect(stream).await?;
+
+ let expected = vec![
+ "+---+---+---+----+---+---+",
+ "| a | b | c | a | b | c |",
+ "+---+---+---+----+---+---+",
+ "| | | | 30 | 3 | 6 |",
+ "| | | | 40 | 4 | 4 |",
+ "| 2 | 7 | 9 | 10 | 2 | 7 |",
+ "| 2 | 7 | 9 | 20 | 2 | 5 |",
+ "+---+---+---+----+---+---+",
+ ];
+ assert_batches_sorted_eq!(expected, &batches);
+
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn join_full_with_filter() -> Result<()> {
+ let session_ctx = SessionContext::new();
+ let task_ctx = session_ctx.task_ctx();
+ let left = build_table(
+ ("a", &vec![0, 1, 2, 2]),
+ ("b", &vec![4, 5, 7, 8]),
+ ("c", &vec![7, 8, 9, 1]),
+ );
+ let right = build_table(
+ ("a", &vec![10, 20, 30, 40]),
+ ("b", &vec![2, 2, 3, 4]),
+ ("c", &vec![7, 5, 6, 4]),
+ );
+ let on = vec![(
+ Column::new_with_schema("a", &left.schema()).unwrap(),
+ Column::new_with_schema("b", &right.schema()).unwrap(),
+ )];
+ let filter = prepare_join_filter();
+
+ let join = join_with_filter(left, right, on, filter, &JoinType::Full, false)?;
+
+ let columns = columns(&join.schema());
+ assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);
+
+ let stream = join.execute(0, task_ctx)?;
+ let batches = common::collect(stream).await?;
+
+ let expected = vec![
+ "+---+---+---+----+---+---+",
+ "| a | b | c | a | b | c |",
+ "+---+---+---+----+---+---+",
+ "| | | | 30 | 3 | 6 |",
+ "| | | | 40 | 4 | 4 |",
+ "| 2 | 7 | 9 | 10 | 2 | 7 |",
+ "| 2 | 7 | 9 | 20 | 2 | 5 |",
+ "| 0 | 4 | 7 | | | |",
+ "| 1 | 5 | 8 | | | |",
+ "| 2 | 8 | 1 | | | |",
+ "+---+---+---+----+---+---+",
+ ];
+ assert_batches_sorted_eq!(expected, &batches);
+
+ Ok(())
+ }
}
diff --git a/datafusion/core/src/physical_plan/join_utils.rs b/datafusion/core/src/physical_plan/join_utils.rs
index 71349ef145..b2cc5654a6 100644
--- a/datafusion/core/src/physical_plan/join_utils.rs
+++ b/datafusion/core/src/physical_plan/join_utils.rs
@@ -22,6 +22,7 @@ use crate::logical_plan::JoinType;
use crate::physical_plan::expressions::Column;
use arrow::datatypes::{Field, Schema};
use arrow::error::ArrowError;
+use datafusion_physical_expr::PhysicalExpr;
use futures::future::{BoxFuture, Shared};
use futures::{ready, FutureExt};
use parking_lot::Mutex;
@@ -96,6 +97,65 @@ pub struct ColumnIndex {
pub side: JoinSide,
}
+/// Filter applied before join output
+#[derive(Debug, Clone)]
+pub struct JoinFilter {
+ /// Filter expression
+ expression: Arc<dyn PhysicalExpr>,
+ /// Column indices required to construct intermediate batch for filtering
+ column_indices: Vec<ColumnIndex>,
+ /// Physical schema of intermediate batch
+ schema: Schema,
+}
+
+impl JoinFilter {
+ /// Creates new JoinFilter
+ pub fn new(
+ expression: Arc<dyn PhysicalExpr>,
+ column_indices: Vec<ColumnIndex>,
+ schema: Schema,
+ ) -> JoinFilter {
+ JoinFilter {
+ expression,
+ column_indices,
+ schema,
+ }
+ }
+
+ /// Helper for building ColumnIndex vector from left and right indices
+ pub fn build_column_indices(
+ left_indices: Vec<usize>,
+ right_indices: Vec<usize>,
+ ) -> Vec<ColumnIndex> {
+ left_indices
+ .into_iter()
+ .map(|i| ColumnIndex {
+ index: i,
+ side: JoinSide::Left,
+ })
+ .chain(right_indices.into_iter().map(|i| ColumnIndex {
+ index: i,
+ side: JoinSide::Right,
+ }))
+ .collect()
+ }
+
+ /// Filter expression
+ pub fn expression(&self) -> &Arc<dyn PhysicalExpr> {
+ &self.expression
+ }
+
+ /// Column indices for intermediate batch creation
+ pub fn column_indices(&self) -> &[ColumnIndex] {
+ &self.column_indices
+ }
+
+ /// Intermediate batch schema
+ pub fn schema(&self) -> &Schema {
+ &self.schema
+ }
+}
+
/// Creates a schema for a join operation.
/// The fields from the left side are first
pub fn build_join_schema(
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index 50e86e1712..39e5e0000b 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -62,12 +62,13 @@ use arrow::compute::SortOptions;
use arrow::datatypes::{Schema, SchemaRef};
use arrow::{compute::can_cast_types, datatypes::DataType};
use async_trait::async_trait;
-use datafusion_expr::expr::GroupingSet;
+use datafusion_expr::{expr::GroupingSet, utils::expr_to_columns};
use datafusion_physical_expr::expressions::DateIntervalExpr;
use datafusion_sql::utils::window_expr_common_partition_keys;
use futures::future::BoxFuture;
use futures::{FutureExt, StreamExt, TryStreamExt};
use log::{debug, trace};
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
fn create_function_physical_name(
@@ -755,6 +756,7 @@ impl DefaultPhysicalPlanner {
left,
right,
on: keys,
+ filter,
join_type,
null_equals_null,
..
@@ -773,6 +775,65 @@ impl DefaultPhysicalPlanner {
})
.collect::<Result<join_utils::JoinOn>>()?;
+ let join_filter = match filter {
+ Some(expr) => {
+ // Extract columns from filter expression
+ let mut cols = HashSet::new();
+ expr_to_columns(expr, &mut cols)?;
+
+ // Collect left & right field indices
+ let left_field_indices = cols.iter()
+ .filter_map(|c| match left_df_schema.index_of_column(c) {
+ Ok(idx) => Some(idx),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ let right_field_indices = cols.iter()
+ .filter_map(|c| match right_df_schema.index_of_column(c) {
+ Ok(idx) => Some(idx),
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+
+ // Collect DFFields and Fields required for intermediate schemas
+ let (filter_df_fields, filter_fields): (Vec<_>, Vec<_>) = left_field_indices.clone()
+ .into_iter()
+ .map(|i| (
+ left_df_schema.field(i).clone(),
+ physical_left.schema().field(i).clone(),
+ ))
+ .chain(
+ right_field_indices.clone()
+ .into_iter()
+ .map(|i| (
+ right_df_schema.field(i).clone(),
+ physical_right.schema().field(i).clone(),
+ ))
+ )
+ .unzip();
+
+
+ // Construct intermediate schemas used for filtering data and
+ // convert logical expression to physical according to filter schema
+ let filter_df_schema = DFSchema::new_with_metadata(filter_df_fields, HashMap::new())?;
+ let filter_schema = Schema::new_with_metadata(filter_fields, HashMap::new());
+ let filter_expr = create_physical_expr(
+ expr,
+ &filter_df_schema,
+ &filter_schema,
+ &session_state.execution_props
+ )?;
+ let column_indices = join_utils::JoinFilter::build_column_indices(left_field_indices, right_field_indices);
+
+ Some(join_utils::JoinFilter::new(
+ filter_expr,
+ column_indices,
+ filter_schema
+ ))
+ }
+ _ => None
+ };
+
if session_state.config.target_partitions > 1
&& session_state.config.repartition_joins
{
@@ -803,6 +864,7 @@ impl DefaultPhysicalPlanner {
),
)?),
join_on,
+ join_filter,
join_type,
PartitionMode::Partitioned,
null_equals_null,
@@ -812,6 +874,7 @@ impl DefaultPhysicalPlanner {
physical_left,
physical_right,
join_on,
+ join_filter,
join_type,
PartitionMode::CollectLeft,
null_equals_null,
diff --git a/datafusion/core/tests/dataframe.rs b/datafusion/core/tests/dataframe.rs
index 234178e748..38f54a2a78 100644
--- a/datafusion/core/tests/dataframe.rs
+++ b/datafusion/core/tests/dataframe.rs
@@ -71,7 +71,7 @@ async fn join() -> Result<()> {
let df2 = ctx.table("aaa")?;
- let a = df1.join(df2, JoinType::Inner, &["a"], &["a"])?;
+ let a = df1.join(df2, JoinType::Inner, &["a"], &["a"], None)?;
let batches = a.collect().await?;
diff --git a/datafusion/core/tests/join_fuzz.rs b/datafusion/core/tests/join_fuzz.rs
index 2f47356236..af42c7785c 100644
--- a/datafusion/core/tests/join_fuzz.rs
+++ b/datafusion/core/tests/join_fuzz.rs
@@ -152,6 +152,7 @@ async fn run_join_test(
left,
right,
on_columns.clone(),
+ None,
&join_type,
PartitionMode::Partitioned,
&false,
diff --git a/datafusion/core/tests/sql/joins.rs b/datafusion/core/tests/sql/joins.rs
index 312b687a60..df853b7c9f 100644
--- a/datafusion/core/tests/sql/joins.rs
+++ b/datafusion/core/tests/sql/joins.rs
@@ -149,15 +149,88 @@ async fn equijoin_right_and_condition_from_left() -> Result<()> {
}
#[tokio::test]
-async fn equijoin_and_unsupported_condition() -> Result<()> {
+async fn equijoin_left_and_condition_from_left() -> Result<()> {
let ctx = create_join_context("t1_id", "t2_id")?;
let sql =
- "SELECT t1_id, t1_name, t2_name FROM t1 LEFT JOIN t2 ON t1_id = t2_id AND t1_id >= '44' ORDER BY t1_id";
- let res = ctx.create_logical_plan(sql);
+ "SELECT t1_id, t1_name, t2_name FROM t1 LEFT JOIN t2 ON t1_id = t2_id AND t1_id >= 44 ORDER BY t1_id";
+ let expected = vec![
+ "+-------+---------+---------+",
+ "| t1_id | t1_name | t2_name |",
+ "+-------+---------+---------+",
+ "| 11 | a | |",
+ "| 22 | b | |",
+ "| 33 | c | |",
+ "| 44 | d | x |",
+ "+-------+---------+---------+",
+ ];
+ let actual = execute_to_batches(&ctx, sql).await;
+ assert_batches_eq!(expected, &actual);
- assert!(res.is_err());
- assert_eq!(format!("{}", res.unwrap_err()), "This feature is not implemented: Unsupported expressions in Left JOIN: [#t1_id >= Utf8(\"44\")]");
+ Ok(())
+}
+#[tokio::test]
+async fn equijoin_left_and_condition_from_both() -> Result<()> {
+ let ctx = create_join_context("t1_id", "t2_id")?;
+ let sql =
+ "SELECT t1_id, t1_int, t2_int FROM t1 LEFT JOIN t2 ON t1_id = t2_id AND t1_int >= t2_int ORDER BY t1_id";
+ let expected = vec![
+ "+-------+--------+--------+",
+ "| t1_id | t1_int | t2_int |",
+ "+-------+--------+--------+",
+ "| 11 | 1 | |",
+ "| 22 | 2 | 1 |",
+ "| 33 | 3 | |",
+ "| 44 | 4 | 3 |",
+ "+-------+--------+--------+",
+ ];
+ let actual = execute_to_batches(&ctx, sql).await;
+ assert_batches_eq!(expected, &actual);
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn equijoin_right_and_condition_from_right() -> Result<()> {
+ let ctx = create_join_context("t1_id", "t2_id")?;
+ let sql =
+ "SELECT t1_id, t1_name, t2_name FROM t1 RIGHT JOIN t2 ON t1_id = t2_id AND t2_id >= 22 ORDER BY t2_name";
+ let res = ctx.create_logical_plan(sql);
+ assert!(res.is_ok());
+ let actual = execute_to_batches(&ctx, sql).await;
+ let expected = vec![
+ "+-------+---------+---------+",
+ "| t1_id | t1_name | t2_name |",
+ "+-------+---------+---------+",
+ "| | | w |",
+ "| 44 | d | x |",
+ "| 22 | b | y |",
+ "| | | z |",
+ "+-------+---------+---------+",
+ ];
+ assert_batches_eq!(expected, &actual);
+ Ok(())
+}
+
+#[tokio::test]
+async fn equijoin_right_and_condition_from_both() -> Result<()> {
+ let ctx = create_join_context("t1_id", "t2_id")?;
+ let sql =
+ "SELECT t1_int, t2_int, t2_id FROM t1 RIGHT JOIN t2 ON t1_id = t2_id AND t2_int <= t1_int ORDER BY t2_id";
+ let res = ctx.create_logical_plan(sql);
+ assert!(res.is_ok());
+ let actual = execute_to_batches(&ctx, sql).await;
+ let expected = vec![
+ "+--------+--------+-------+",
+ "| t1_int | t2_int | t2_id |",
+ "+--------+--------+-------+",
+ "| | 3 | 11 |",
+ "| 2 | 1 | 22 |",
+ "| 4 | 3 | 44 |",
+ "| | 3 | 55 |",
+ "+--------+--------+-------+",
+ ];
+ assert_batches_eq!(expected, &actual);
Ok(())
}
diff --git a/datafusion/core/tests/sql/mod.rs b/datafusion/core/tests/sql/mod.rs
index 566baefab7..a13f2ebffe 100644
--- a/datafusion/core/tests/sql/mod.rs
+++ b/datafusion/core/tests/sql/mod.rs
@@ -180,6 +180,7 @@ fn create_join_context(column_left: &str, column_right: &str) -> Result<SessionC
let t1_schema = Arc::new(Schema::new(vec![
Field::new(column_left, DataType::UInt32, true),
Field::new("t1_name", DataType::Utf8, true),
+ Field::new("t1_int", DataType::UInt32, true),
]));
let t1_data = RecordBatch::try_new(
t1_schema.clone(),
@@ -191,6 +192,7 @@ fn create_join_context(column_left: &str, column_right: &str) -> Result<SessionC
Some("c"),
Some("d"),
])),
+ Arc::new(UInt32Array::from_slice(&[1, 2, 3, 4])),
],
)?;
let t1_table = MemTable::try_new(t1_schema, vec![vec![t1_data]])?;
@@ -199,6 +201,7 @@ fn create_join_context(column_left: &str, column_right: &str) -> Result<SessionC
let t2_schema = Arc::new(Schema::new(vec![
Field::new(column_right, DataType::UInt32, true),
Field::new("t2_name", DataType::Utf8, true),
+ Field::new("t2_int", DataType::UInt32, true),
]));
let t2_data = RecordBatch::try_new(
t2_schema.clone(),
@@ -210,6 +213,7 @@ fn create_join_context(column_left: &str, column_right: &str) -> Result<SessionC
Some("x"),
Some("w"),
])),
+ Arc::new(UInt32Array::from_slice(&[3, 1, 3, 3])),
],
)?;
let t2_table = MemTable::try_new(t2_schema, vec![vec![t2_data]])?;
diff --git a/datafusion/core/tests/sql/wildcard.rs b/datafusion/core/tests/sql/wildcard.rs
index 106f47a457..d78d0456d3 100644
--- a/datafusion/core/tests/sql/wildcard.rs
+++ b/datafusion/core/tests/sql/wildcard.rs
@@ -93,13 +93,13 @@ async fn select_qualified_wildcard_join() -> Result<()> {
let sql =
"SELECT tb1.*, tb2.* FROM t1 tb1 JOIN t2 tb2 ON t2_id = t1_id ORDER BY t1_id";
let expected = vec![
- "+-------+---------+-------+---------+",
- "| t1_id | t1_name | t2_id | t2_name |",
- "+-------+---------+-------+---------+",
- "| 11 | a | 11 | z |",
- "| 22 | b | 22 | y |",
- "| 44 | d | 44 | x |",
- "+-------+---------+-------+---------+",
+ "+-------+---------+--------+-------+---------+--------+",
+ "| t1_id | t1_name | t1_int | t2_id | t2_name | t2_int |",
+ "+-------+---------+--------+-------+---------+--------+",
+ "| 11 | a | 1 | 11 | z | 3 |",
+ "| 22 | b | 2 | 22 | y | 1 |",
+ "| 44 | d | 4 | 44 | x | 3 |",
+ "+-------+---------+--------+-------+---------+--------+",
];
let results = execute_to_batches(&ctx, sql).await;
@@ -114,13 +114,13 @@ async fn select_non_alias_qualified_wildcard_join() -> Result<()> {
let ctx = create_join_context("t1_id", "t2_id")?;
let sql = "SELECT t1.*, tb2.* FROM t1 JOIN t2 tb2 ON t2_id = t1_id ORDER BY t1_id";
let expected = vec![
- "+-------+---------+-------+---------+",
- "| t1_id | t1_name | t2_id | t2_name |",
- "+-------+---------+-------+---------+",
- "| 11 | a | 11 | z |",
- "| 22 | b | 22 | y |",
- "| 44 | d | 44 | x |",
- "+-------+---------+-------+---------+",
+ "+-------+---------+--------+-------+---------+--------+",
+ "| t1_id | t1_name | t1_int | t2_id | t2_name | t2_int |",
+ "+-------+---------+--------+-------+---------+--------+",
+ "| 11 | a | 1 | 11 | z | 3 |",
+ "| 22 | b | 2 | 22 | y | 1 |",
+ "| 44 | d | 4 | 44 | x | 3 |",
+ "+-------+---------+--------+-------+---------+--------+",
];
let results = execute_to_batches(&ctx, sql).await;
diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs
index a20208c7de..b40109ebb6 100644
--- a/datafusion/expr/src/logical_plan/builder.rs
+++ b/datafusion/expr/src/logical_plan/builder.rs
@@ -448,14 +448,19 @@ impl LogicalPlanBuilder {
Self::from(plan).project(vec![Expr::Wildcard])
}
- /// Apply a join with on constraint
+ /// Apply a join with on constraint.
+ ///
+ /// Filter expression expected to contain non-equality predicates that can not be pushed
+ /// down to any of join inputs.
+ /// In case of outer join, filter applied to only matched rows.
pub fn join(
&self,
right: &LogicalPlan,
join_type: JoinType,
join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
+ filter: Option<Expr>,
) -> Result<Self> {
- self.join_detailed(right, join_type, join_keys, false)
+ self.join_detailed(right, join_type, join_keys, filter, false)
}
fn normalize(
@@ -476,6 +481,7 @@ impl LogicalPlanBuilder {
right: &LogicalPlan,
join_type: JoinType,
join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
+ filter: Option<Expr>,
null_equals_null: bool,
) -> Result<Self> {
if join_keys.0.len() != join_keys.1.len() {
@@ -571,6 +577,7 @@ impl LogicalPlanBuilder {
left: Arc::new(self.plan.clone()),
right: Arc::new(right.clone()),
on,
+ filter,
join_type,
join_constraint: JoinConstraint::On,
schema: DFSchemaRef::new(join_schema),
@@ -603,6 +610,7 @@ impl LogicalPlanBuilder {
left: Arc::new(self.plan.clone()),
right: Arc::new(right.clone()),
on,
+ filter: None,
join_type,
join_constraint: JoinConstraint::Using,
schema: DFSchemaRef::new(join_schema),
@@ -750,12 +758,12 @@ impl LogicalPlanBuilder {
.unzip();
if is_all {
LogicalPlanBuilder::from(left_plan)
- .join_detailed(&right_plan, join_type, join_keys, true)?
+ .join_detailed(&right_plan, join_type, join_keys, None, true)?
.build()
} else {
LogicalPlanBuilder::from(left_plan)
.distinct()?
- .join_detailed(&right_plan, join_type, join_keys, true)?
+ .join_detailed(&right_plan, join_type, join_keys, None, true)?
.build()
}
}
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs
index 05c8a22e7d..acdb909206 100644
--- a/datafusion/expr/src/logical_plan/plan.rs
+++ b/datafusion/expr/src/logical_plan/plan.rs
@@ -743,22 +743,34 @@ impl LogicalPlan {
}
LogicalPlan::Join(Join {
on: ref keys,
+ filter,
join_constraint,
join_type,
..
}) => {
let join_expr: Vec<String> =
keys.iter().map(|(l, r)| format!("{} = {}", l, r)).collect();
+ let filter_expr = filter
+ .as_ref()
+ .map(|expr| format!(" Filter: {}", expr))
+ .unwrap_or_else(|| "".to_string());
match join_constraint {
JoinConstraint::On => {
- write!(f, "{} Join: {}", join_type, join_expr.join(", "))
+ write!(
+ f,
+ "{} Join: {}{}",
+ join_type,
+ join_expr.join(", "),
+ filter_expr
+ )
}
JoinConstraint::Using => {
write!(
f,
- "{} Join: Using {}",
+ "{} Join: Using {}{}",
join_type,
- join_expr.join(", ")
+ join_expr.join(", "),
+ filter_expr,
)
}
}
@@ -1181,6 +1193,8 @@ pub struct Join {
pub right: Arc<LogicalPlan>,
/// Equijoin clause expressed as pairs of (left, right) join columns
pub on: Vec<(Column, Column)>,
+ /// Filters applied during join (non-equi conditions)
+ pub filter: Option<Expr>,
/// Join type
pub join_type: JoinType,
/// Join constraint
diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs
index a7aed1799d..bb81d6776f 100644
--- a/datafusion/expr/src/utils.rs
+++ b/datafusion/expr/src/utils.rs
@@ -378,6 +378,7 @@ pub fn from_plan(
join_type,
join_constraint,
on,
+ filter,
null_equals_null,
..
}) => {
@@ -389,6 +390,7 @@ pub fn from_plan(
join_type: *join_type,
join_constraint: *join_constraint,
on: on.clone(),
+ filter: filter.clone(),
schema: DFSchemaRef::new(schema),
null_equals_null: *null_equals_null,
}))
diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rs
index ba05a22452..3556b02035 100644
--- a/datafusion/sql/src/planner.rs
+++ b/datafusion/sql/src/planner.rs
@@ -29,7 +29,7 @@ use datafusion_expr::logical_plan::{
ToStringifiedPlan,
};
use datafusion_expr::utils::{
- expand_qualified_wildcard, expand_wildcard, expr_as_column_expr, exprlist_to_columns,
+ expand_qualified_wildcard, expand_wildcard, expr_as_column_expr, expr_to_columns,
find_aggregate_exprs, find_column_exprs, find_window_exprs,
};
use datafusion_expr::{
@@ -572,95 +572,113 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
// extract join keys
extract_join_keys(expr, &mut keys, &mut filter);
- let mut cols = HashSet::new();
- exprlist_to_columns(&filter, &mut cols)?;
-
let (left_keys, right_keys): (Vec<Column>, Vec<Column>) =
keys.into_iter().unzip();
- // return the logical plan representing the join
+ let normalized_filters = filter
+ .into_iter()
+ .map(|expr| {
+ let mut using_columns = HashSet::new();
+ expr_to_columns(&expr, &mut using_columns)?;
+
+ normalize_col_with_schemas(
+ expr,
+ &[left.schema(), right.schema()],
+ &[using_columns],
+ )
+ })
+ .collect::<Result<Vec<_>>>()?;
+
if left_keys.is_empty() {
// When we don't have join keys, use cross join
let join = LogicalPlanBuilder::from(left).cross_join(&right)?;
-
- join.filter(filter.into_iter().reduce(Expr::and).unwrap())?
+ normalized_filters
+ .into_iter()
+ .reduce(Expr::and)
+ .map(|filter| join.filter(filter))
+ .unwrap_or(Ok(join))?
.build()
- } else if filter.is_empty() {
+ } else if join_type == JoinType::Inner && !normalized_filters.is_empty() {
let join = LogicalPlanBuilder::from(left).join(
&right,
join_type,
(left_keys, right_keys),
+ None,
)?;
- join.build()
- } else if join_type == JoinType::Inner {
+ join.filter(
+ normalized_filters.into_iter().reduce(Expr::and).unwrap(),
+ )?
+ .build()
+ } else if join_type == JoinType::Left {
+ // Inner filters - predicates based only on right input columns
+ // Outer filters - predicates using left input columns
+ //
+ // Inner filters are safe to push to right input and exclude from ON
+ let (inner_filters, outer_filters): (Vec<_>, Vec<_>) =
+ normalized_filters.into_iter().partition(|e| {
+ find_column_exprs(&[e.clone()])
+ .iter()
+ .filter_map(|e| match e {
+ Expr::Column(column) => Some(column),
+ _ => None,
+ })
+ .all(|c| right.schema().index_of_column(c).is_ok())
+ });
+
+ let right_input = if inner_filters.is_empty() {
+ right
+ } else {
+ LogicalPlanBuilder::from(right)
+ .filter(inner_filters.into_iter().reduce(Expr::and).unwrap())?
+ .build()?
+ };
+
let join = LogicalPlanBuilder::from(left).join(
+ &right_input,
+ join_type,
+ (left_keys, right_keys),
+ outer_filters.into_iter().reduce(Expr::and),
+ )?;
+ join.build()
+ } else if join_type == JoinType::Right && !normalized_filters.is_empty() {
+ // Inner filters - predicates based only on left input columns
+ // Outer filters - predicates using right input columns
+ //
+ // Inner filters are safe to push to left input and exclude from ON
+ let (inner_filters, outer_filters): (Vec<_>, Vec<_>) =
+ normalized_filters.into_iter().partition(|e| {
+ find_column_exprs(&[e.clone()])
+ .iter()
+ .filter_map(|e| match e {
+ Expr::Column(column) => Some(column),
+ _ => None,
+ })
+ .all(|c| left.schema().index_of_column(c).is_ok())
+ });
+
+ let left_input = if inner_filters.is_empty() {
+ left
+ } else {
+ LogicalPlanBuilder::from(left)
+ .filter(inner_filters.into_iter().reduce(Expr::and).unwrap())?
+ .build()?
+ };
+
+ let join = LogicalPlanBuilder::from(left_input).join(
&right,
join_type,
(left_keys, right_keys),
+ outer_filters.into_iter().reduce(Expr::and),
)?;
- join.filter(filter.into_iter().reduce(Expr::and).unwrap())?
- .build()
- }
- // Left join with all non-equijoin expressions from the right
- // l left join r
- // on l1=r1 and r2 > [..]
- else if join_type == JoinType::Left
- && cols.iter().all(
- |Column {
- relation: qualifier,
- name,
- }| {
- right
- .schema()
- .field_with_name(qualifier.as_deref(), name)
- .is_ok()
- },
- )
- {
- let join_filter_init = filter.remove(0);
- LogicalPlanBuilder::from(left)
- .join(
- &LogicalPlanBuilder::from(right)
- .filter(
- filter
- .into_iter()
- .fold(join_filter_init, |acc, e| acc.and(e)),
- )?
- .build()?,
- join_type,
- (left_keys, right_keys),
- )?
- .build()
- }
- // Right join with all non-equijoin expressions from the left
- // l right join r
- // on l1=r1 and l2 > [..]
- else if join_type == JoinType::Right
- && cols.iter().all(
- |Column {
- relation: qualifier,
- name,
- }| {
- left.schema()
- .field_with_name(qualifier.as_deref(), name)
- .is_ok()
- },
- )
- {
- let join_filter_init = filter.remove(0);
- LogicalPlanBuilder::from(left)
- .filter(
- filter
- .into_iter()
- .fold(join_filter_init, |acc, e| acc.and(e)),
- )?
- .join(&right, join_type, (left_keys, right_keys))?
- .build()
+ join.build()
} else {
- Err(DataFusionError::NotImplemented(format!(
- "Unsupported expressions in {:?} JOIN: {:?}",
- join_type, filter
- )))
+ let join = LogicalPlanBuilder::from(left).join(
+ &right,
+ join_type,
+ (left_keys, right_keys),
+ normalized_filters.into_iter().reduce(Expr::and),
+ )?;
+ join.build()
}
}
JoinConstraint::Using(idents) => {
@@ -683,7 +701,6 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
)),
}
}
-
fn create_relation(
&self,
relation: TableFactor,
@@ -892,7 +909,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
join_keys.iter().map(|(_, r)| r.clone()).collect();
let builder = LogicalPlanBuilder::from(left);
left = builder
- .join(&plan, JoinType::Inner, (left_keys, right_keys))?
+ .join(&plan, JoinType::Inner, (left_keys, right_keys), None)?
.build()?;
}
@@ -3798,7 +3815,7 @@ mod tests {
}
#[test]
- fn equijoin_unsupported_expression() {
+ fn equijoin_with_condition() {
let sql = "SELECT id, order_id \
FROM person \
JOIN orders \
@@ -3812,13 +3829,13 @@ mod tests {
}
#[test]
- fn left_equijoin_unsupported_expression() {
+ fn left_equijoin_with_conditions() {
let sql = "SELECT id, order_id \
FROM person \
LEFT JOIN orders \
- ON id = customer_id AND order_id > 1";
+ ON id = customer_id AND order_id > 1 AND age < 30";
let expected = "Projection: #person.id, #orders.order_id\
- \n Left Join: #person.id = #orders.customer_id\
+ \n Left Join: #person.id = #orders.customer_id Filter: #person.age < Int64(30)\
\n TableScan: person projection=None\
\n Filter: #orders.order_id > Int64(1)\
\n TableScan: orders projection=None";
@@ -3826,19 +3843,32 @@ mod tests {
}
#[test]
- fn right_equijoin_unsupported_expression() {
+ fn right_equijoin_with_conditions() {
let sql = "SELECT id, order_id \
FROM person \
RIGHT JOIN orders \
- ON id = customer_id AND id > 1";
+ ON id = customer_id AND id > 1 AND order_id < 100";
let expected = "Projection: #person.id, #orders.order_id\
- \n Right Join: #person.id = #orders.customer_id\
+ \n Right Join: #person.id = #orders.customer_id Filter: #orders.order_id < Int64(100)\
\n Filter: #person.id > Int64(1)\
\n TableScan: person projection=None\
\n TableScan: orders projection=None";
quick_test(sql, expected);
}
+ #[test]
+ fn full_equijoin_with_conditions() {
+ let sql = "SELECT id, order_id \
+ FROM person \
+ FULL JOIN orders \
+ ON id = customer_id AND id > 1 AND order_id < 100";
+ let expected = "Projection: #person.id, #orders.order_id\
+ \n Full Join: #person.id = #orders.customer_id Filter: #person.id > Int64(1) AND #orders.order_id < Int64(100)\
+ \n TableScan: person projection=None\
+ \n TableScan: orders projection=None";
+ quick_test(sql, expected);
+ }
+
#[test]
fn join_with_table_name() {
let sql = "SELECT id, order_id \
diff --git a/dev/build-arrow-ballista.sh b/dev/build-arrow-ballista.sh
index 0c39226273..47dbed1a38 100755
--- a/dev/build-arrow-ballista.sh
+++ b/dev/build-arrow-ballista.sh
@@ -24,7 +24,7 @@ rm -rf arrow-ballista 2>/dev/null
# clone the repo
# TODO make repo/branch configurable
-git clone https://github.com/apache/arrow-ballista
+git clone --branch join_filter https://github.com/korowa/arrow-ballista
# update dependencies to local crates
python ./dev/make-ballista-deps-local.py