Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions datafusion/core/src/dataframe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ use datafusion_common::{
};
use datafusion_expr::select_expr::SelectExpr;
use datafusion_expr::{
ExplainOption, ScalarUDF, SortExpr, TableProviderFilterPushDown, UNNAMED_TABLE, case,
dml::InsertOp, is_null, lit, utils::COUNT_STAR_EXPANSION,
AsOfMatch, ExplainOption, ScalarUDF, SortExpr, TableProviderFilterPushDown,
UNNAMED_TABLE, case, dml::InsertOp, is_null, lit, utils::COUNT_STAR_EXPANSION,
};
use datafusion_functions::core::coalesce;
use datafusion_functions::math::nanvl;
Expand Down Expand Up @@ -1380,6 +1380,45 @@ impl DataFrame {
})
}

/// Join this `DataFrame` to the closest eligible row in `right`.
///
/// Every left row is emitted exactly once. `on` contains optional equality
/// expressions and `match_condition` selects the ordered predecessor or
/// successor from the matching right group.
pub fn join_asof(
self,
right: DataFrame,
on: Vec<(Expr, Expr)>,
match_condition: AsOfMatch,
) -> Result<DataFrame> {
let plan = LogicalPlanBuilder::from(self.plan)
.asof_join(right.plan, on, match_condition)?
.build()?;
Ok(DataFrame {
session_state: self.session_state,
plan,
projection_requires_validation: true,
})
}

/// Join this `DataFrame` to the closest eligible row in `right` using
/// same-named equality keys.
pub fn join_asof_using(
self,
right: DataFrame,
using_keys: Vec<Column>,
match_condition: AsOfMatch,
) -> Result<DataFrame> {
let plan = LogicalPlanBuilder::from(self.plan)
.asof_join_using(right.plan, using_keys, match_condition)?
.build()?;
Ok(DataFrame {
session_state: self.session_state,
plan,
projection_requires_validation: true,
})
}

/// Repartition a DataFrame based on a logical partitioning scheme.
///
/// # Example
Expand Down
49 changes: 48 additions & 1 deletion datafusion/core/src/physical_planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ use crate::physical_plan::explain::ExplainExec;
use crate::physical_plan::filter::FilterExecBuilder;
use crate::physical_plan::joins::utils as join_utils;
use crate::physical_plan::joins::{
CrossJoinExec, HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec,
AsOfJoinExec, AsOfMatchExpr, CrossJoinExec, HashJoinExec, NestedLoopJoinExec,
PartitionMode, SortMergeJoinExec,
};
use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
use crate::physical_plan::projection::{ProjectionExec, ProjectionExpr};
Expand Down Expand Up @@ -1790,6 +1791,51 @@ impl DefaultPhysicalPlanner {
join
}
}
LogicalPlan::AsOfJoin(join) => {
let [physical_left, physical_right] = children.two()?;
let join_on = join
.on
.iter()
.map(|(left, right)| {
Ok((
create_physical_expr(
left,
join.left.schema(),
execution_props,
planning_ctx,
)?,
create_physical_expr(
right,
join.right.schema(),
execution_props,
planning_ctx,
)?,
))
})
.collect::<Result<join_utils::JoinOn>>()?;
let match_condition = AsOfMatchExpr::new(
create_physical_expr(
&join.match_condition.left,
join.left.schema(),
execution_props,
planning_ctx,
)?,
join.match_condition.op,
create_physical_expr(
&join.match_condition.right,
join.right.schema(),
execution_props,
planning_ctx,
)?,
);
Arc::new(AsOfJoinExec::try_new(
physical_left,
physical_right,
join_on,
match_condition,
None,
)?)
}
LogicalPlan::RecursiveQuery(RecursiveQuery {
name,
is_distinct,
Expand Down Expand Up @@ -2291,6 +2337,7 @@ fn extract_dml_filters(
| LogicalPlan::Sort(_)
| LogicalPlan::Union(_)
| LogicalPlan::Join(_)
| LogicalPlan::AsOfJoin(_)
| LogicalPlan::Repartition(_)
| LogicalPlan::Aggregate(_)
| LogicalPlan::Window(_)
Expand Down
2 changes: 1 addition & 1 deletion datafusion/core/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub use crate::execution::options::{

pub use datafusion_common::Column;
pub use datafusion_expr::{
Expr,
AsOfMatch, Expr, Operator,
expr_fn::*,
lit, lit_timestamp_nano,
logical_plan::{JoinType, Partitioning},
Expand Down
54 changes: 49 additions & 5 deletions datafusion/core/tests/dataframe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ use datafusion::error::Result;
use datafusion::execution::context::SessionContext;
use datafusion::execution::session_state::SessionStateBuilder;
use datafusion::logical_expr::{ColumnarValue, Volatility};
use datafusion::prelude::{CsvReadOptions, JoinType, ParquetReadOptions};
use datafusion::prelude::{AsOfMatch, CsvReadOptions, JoinType, ParquetReadOptions};
use datafusion::test_util::{
parquet_test_data, populate_csv_partitions, register_aggregate_csv, test_table,
test_table_with_cache_factory, test_table_with_name,
Expand All @@ -78,10 +78,10 @@ use datafusion_expr::expr::{GroupingSet, NullTreatment, Sort, WindowFunction};
use datafusion_expr::var_provider::{VarProvider, VarType};
use datafusion_expr::{
CreateMemoryTable, CreateView, DdlStatement, Expr, ExprFunctionExt, ExprSchemable,
LogicalPlan, LogicalPlanBuilder, ScalarFunctionImplementation, SortExpr, TableType,
WindowFrame, WindowFrameBound, WindowFrameUnits, WindowFunctionDefinition, cast, col,
create_udf, exists, in_subquery, lambda, lambda_var, lit, out_ref_col, placeholder,
scalar_subquery, when, wildcard,
LogicalPlan, LogicalPlanBuilder, Operator, ScalarFunctionImplementation, SortExpr,
TableType, WindowFrame, WindowFrameBound, WindowFrameUnits, WindowFunctionDefinition,
cast, col, create_udf, exists, in_subquery, lambda, lambda_var, lit, out_ref_col,
placeholder, scalar_subquery, when, wildcard,
};
use datafusion_physical_expr::Partitioning;
use datafusion_physical_expr::aggregate::AggregateExprBuilder;
Expand Down Expand Up @@ -1504,6 +1504,50 @@ async fn join() -> Result<()> {
Ok(())
}

#[tokio::test]
async fn join_asof() -> Result<()> {
let ctx = SessionContext::new();
let left = ctx
.read_batch(record_batch!(
("symbol", Utf8, ["A", "A", "B"]),
("ts", Int64, [1, 4, 2]),
("trade_id", Int32, [1, 2, 3])
)?)?
.alias("trades")?;
let right = ctx
.read_batch(record_batch!(
("symbol", Utf8, ["A", "A", "B"]),
("ts", Int64, [2, 4, 1]),
("price", Int32, [20, 40, 101])
)?)?
.alias("prices")?;

let results = left
.join_asof(
right,
vec![(col("symbol"), col("symbol"))],
AsOfMatch::new(col("ts"), Operator::GtEq, col("ts")),
)?
.select(vec![col("trade_id"), col("price")])?
.sort(vec![col("trade_id").sort(true, true)])?
.collect()
.await?;

assert_batches_eq!(
[
"+----------+-------+",
"| trade_id | price |",
"+----------+-------+",
"| 1 | |",
"| 2 | 40 |",
"| 3 | 101 |",
"+----------+-------+",
],
&results
);
Ok(())
}

#[tokio::test]
async fn join_coercion_unnamed() -> Result<()> {
let ctx = SessionContext::new();
Expand Down
78 changes: 74 additions & 4 deletions datafusion/expr/src/logical_plan/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ use crate::expr_rewriter::{
rewrite_sort_cols_by_aggs,
};
use crate::logical_plan::{
Aggregate, Analyze, Distinct, DistinctOn, EmptyRelation, Explain, Filter, Join,
JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning, PlanType, Prepare,
Projection, Repartition, Sort, SubqueryAlias, TableScanBuilder, Union, Unnest,
Values, Window,
Aggregate, Analyze, AsOfJoin, AsOfMatch, Distinct, DistinctOn, EmptyRelation,
Explain, Filter, Join, JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning,
PlanType, Prepare, Projection, Repartition, Sort, SubqueryAlias, TableScanBuilder,
Union, Unnest, Values, Window,
};
use crate::select_expr::SelectExpr;
use crate::utils::{
Expand Down Expand Up @@ -1007,6 +1007,68 @@ impl LogicalPlanBuilder {
)
}

/// Apply a left-preserving ASOF join using equality expressions and one
/// ordered match condition.
pub fn asof_join(
self,
right: LogicalPlan,
on: Vec<(Expr, Expr)>,
match_condition: AsOfMatch,
) -> Result<Self> {
self.asof_join_with_constraint(right, on, match_condition, JoinConstraint::On)
}

/// Apply a left-preserving ASOF join using `USING` equality keys.
pub fn asof_join_using(
self,
right: LogicalPlan,
using_keys: Vec<Column>,
match_condition: AsOfMatch,
) -> Result<Self> {
let on = using_keys
.into_iter()
.map(|key| {
let left = Self::normalize(&self.plan, key.clone())?;
let right = Self::normalize(&right, key)?;
Ok((Expr::Column(left), Expr::Column(right)))
})
.collect::<Result<_>>()?;
self.asof_join_with_constraint(right, on, match_condition, JoinConstraint::Using)
}

fn asof_join_with_constraint(
self,
right: LogicalPlan,
on: Vec<(Expr, Expr)>,
match_condition: AsOfMatch,
join_constraint: JoinConstraint,
) -> Result<Self> {
let normalize = |expr, schema: &DFSchema| {
normalize_col_with_schemas_and_ambiguity_check(expr, &[&[schema]], &[])
};
let on = on
.into_iter()
.map(|(left, right_expr)| {
Ok((
normalize(left, self.plan.schema())?,
normalize(right_expr, right.schema())?,
))
})
.collect::<Result<_>>()?;
let match_condition = AsOfMatch {
left: normalize(match_condition.left, self.plan.schema())?,
op: match_condition.op,
right: normalize(match_condition.right, right.schema())?,
};
Ok(Self::new(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
self.plan,
Arc::new(right),
on,
match_condition,
join_constraint,
)?)))
}

pub(crate) fn normalize(plan: &LogicalPlan, column: Column) -> Result<Column> {
if column.relation.is_some() {
// column is already normalized
Expand Down Expand Up @@ -1776,6 +1838,14 @@ pub fn build_join_schema(
dfschema.with_functional_dependencies(func_dependencies)
}

/// Creates the schema for a left-preserving ASOF join.
///
/// Both `ON` and `USING` preserve all qualified input fields. SQL wildcard
/// expansion handles the unqualified `USING` key as a single column.
pub fn build_asof_join_schema(left: &DFSchema, right: &DFSchema) -> Result<DFSchema> {
build_join_schema(left, right, &JoinType::Left)
}

/// (Re)qualify the sides of a join if needed, i.e. if the columns from one side would otherwise
/// conflict with the columns from the other.
/// This is especially useful for queries that come as Substrait, since Substrait doesn't currently allow specifying
Expand Down
23 changes: 19 additions & 4 deletions datafusion/expr/src/logical_plan/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ use std::collections::HashMap;
use std::fmt;

use crate::{
Aggregate, DescribeTable, Distinct, DistinctOn, DmlStatement, Expr, Filter, Join,
Limit, LogicalPlan, Partitioning, Projection, RecursiveQuery, Repartition, Sort,
Subquery, SubqueryAlias, TableProviderFilterPushDown, TableScan, Unnest, Values,
Window, expr_vec_fmt,
Aggregate, AsOfJoin, DescribeTable, Distinct, DistinctOn, DmlStatement, Expr, Filter,
Join, Limit, LogicalPlan, Partitioning, Projection, RecursiveQuery, Repartition,
Sort, Subquery, SubqueryAlias, TableProviderFilterPushDown, TableScan, Unnest,
Values, Window, expr_vec_fmt,
};

use crate::dml::CopyTo;
Expand Down Expand Up @@ -493,6 +493,21 @@ impl<'a, 'b> PgJsonVisitor<'a, 'b> {
"Filter": format!("{}", filter_expr)
})
}
LogicalPlan::AsOfJoin(AsOfJoin {
on,
match_condition,
join_constraint,
..
}) => {
let join_expr: Vec<String> =
on.iter().map(|(l, r)| format!("{l} = {r}")).collect();
json!({
"Node Type": "AsOf Join",
"Join Constraint": format!("{join_constraint:?}"),
"Join Keys": join_expr.join(", "),
"Match Condition": match_condition.to_string(),
})
}
LogicalPlan::Repartition(Repartition {
partitioning_scheme,
..
Expand Down
16 changes: 8 additions & 8 deletions datafusion/expr/src/logical_plan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ pub mod tree_node;

pub use builder::{
LogicalPlanBuilder, LogicalPlanBuilderOptions, LogicalTableSource, UNNAMED_TABLE,
build_join_schema, requalify_sides_if_needed, table_scan, union,
wrap_projection_for_join_if_necessary,
build_asof_join_schema, build_join_schema, requalify_sides_if_needed, table_scan,
union, wrap_projection_for_join_if_necessary,
};
pub use ddl::{
CreateCatalog, CreateCatalogSchema, CreateExternalTable, CreateFunction,
Expand All @@ -41,12 +41,12 @@ pub use dml::{
WriteOp,
};
pub use plan::{
Aggregate, Analyze, ColumnUnnestList, DescribeTable, Distinct, DistinctOn,
EmptyRelation, Explain, ExplainOption, Extension, FetchType, Filter, Join,
JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning, PlanType, Projection,
RangePartitioning, RecursiveQuery, Repartition, SkipType, Sort, StringifiedPlan,
Subquery, SubqueryAlias, TableScan, TableScanBuilder, ToStringifiedPlan, Union,
Unnest, Values, Window, projection_schema,
Aggregate, Analyze, AsOfJoin, AsOfMatch, ColumnUnnestList, DescribeTable, Distinct,
DistinctOn, EmptyRelation, Explain, ExplainOption, Extension, FetchType, Filter,
Join, JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning, PlanType,
Projection, RangePartitioning, RecursiveQuery, Repartition, SkipType, Sort,
StringifiedPlan, Subquery, SubqueryAlias, TableScan, TableScanBuilder,
ToStringifiedPlan, Union, Unnest, Values, Window, projection_schema,
};
pub use statement::{
Deallocate, Execute, Prepare, ResetVariable, SetVariable, Statement,
Expand Down
Loading