Repository navigation
DataFrame API: allow aggregate functions in select() (#17874) #21021
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
ff0ada7
1659fa7
f9f351e
0262b63
e527e12
072ba48
34127b1
2de353a
9564aba
d9ec8c8
0940936
a43280d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -51,12 +51,14 @@ use arrow::compute::{cast, concat}; | |
| use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; | ||
| use arrow_schema::FieldRef; | ||
| use datafusion_common::config::{CsvOptions, JsonOptions}; | ||
| use datafusion_common::tree_node::{Transformed, TreeNode}; | ||
| use datafusion_common::{ | ||
| Column, DFSchema, DataFusionError, ParamValues, ScalarValue, SchemaError, | ||
| TableReference, UnnestOptions, exec_err, internal_datafusion_err, not_impl_err, | ||
| plan_datafusion_err, plan_err, unqualified_field_not_found, | ||
| }; | ||
| use datafusion_expr::select_expr::SelectExpr; | ||
| use datafusion_expr::utils::find_aggregate_exprs; | ||
| use datafusion_expr::{ | ||
| ExplainOption, SortExpr, TableProviderFilterPushDown, UNNAMED_TABLE, case, | ||
| dml::InsertOp, | ||
|
|
@@ -387,21 +389,35 @@ impl DataFrame { | |
| /// # use datafusion::prelude::*; | ||
| /// # use datafusion::error::Result; | ||
| /// # use datafusion_common::assert_batches_sorted_eq; | ||
| /// # use datafusion_functions_aggregate::expr_fn::{count, sum}; | ||
| /// # #[tokio::main] | ||
| /// # async fn main() -> Result<()> { | ||
| /// let ctx = SessionContext::new(); | ||
| /// let df = ctx | ||
| /// .read_csv("tests/data/example.csv", CsvReadOptions::new()) | ||
| /// .await?; | ||
| /// let df = df.select(vec![col("a"), col("b") * col("c")])?; | ||
| /// | ||
| /// // Expressions are evaluated per row | ||
| /// let res = df.clone().select(vec![col("a"), col("b") * col("c")])?; | ||
| /// let expected = vec![ | ||
| /// "+---+-----------------------+", | ||
| /// "| a | ?table?.b * ?table?.c |", | ||
| /// "+---+-----------------------+", | ||
| /// "| 1 | 6 |", | ||
| /// "+---+-----------------------+", | ||
| /// ]; | ||
| /// # assert_batches_sorted_eq!(expected, &df.collect().await?); | ||
| /// # assert_batches_sorted_eq!(expected, &res.collect().await?); | ||
| /// | ||
| /// // Aggregate expressions are also supported | ||
| /// let res = df.select(vec![count(col("a")), sum(col("b"))])?; | ||
| /// let expected = vec![ | ||
| /// "+----------+--------+", | ||
| /// "| count(a) | sum(b) |", | ||
| /// "+----------+--------+", | ||
| /// "| 1 | 2 |", | ||
| /// "+----------+--------+", | ||
| /// ]; | ||
| /// # assert_batches_sorted_eq!(expected, &res.collect().await?); | ||
| /// # Ok(()) | ||
| /// # } | ||
| /// ``` | ||
|
|
@@ -410,21 +426,128 @@ impl DataFrame { | |
| expr_list: impl IntoIterator<Item = impl Into<SelectExpr>>, | ||
| ) -> Result<DataFrame> { | ||
| let expr_list: Vec<SelectExpr> = | ||
| expr_list.into_iter().map(|e| e.into()).collect::<Vec<_>>(); | ||
| expr_list.into_iter().map(|e| e.into()).collect(); | ||
|
|
||
| // Extract expressions | ||
| let expressions = expr_list.iter().filter_map(|e| match e { | ||
| SelectExpr::Expression(expr) => Some(expr), | ||
| _ => None, | ||
| }); | ||
|
|
||
| let window_func_exprs = find_window_exprs(expressions); | ||
| let plan = if window_func_exprs.is_empty() { | ||
| // Apply window functions first | ||
|
cj-zhukov marked this conversation as resolved.
Resolved
|
||
| let window_func_exprs = find_window_exprs(expressions.clone()); | ||
|
|
||
| let mut plan = if window_func_exprs.is_empty() { | ||
| self.plan | ||
| } else { | ||
| LogicalPlanBuilder::window_plan(self.plan, window_func_exprs)? | ||
| }; | ||
|
|
||
| let project_plan = LogicalPlanBuilder::from(plan).project(expr_list)?.build()?; | ||
| // Collect aggregate expressions | ||
| let aggr_exprs = find_aggregate_exprs(expressions.clone()); | ||
|
martin-g marked this conversation as resolved.
Resolved
|
||
|
|
||
| // Check for non-aggregate expressions | ||
| let has_non_aggregate_expr = expr_list.iter().any(|e| match e { | ||
| SelectExpr::Expression(expr) => { | ||
| find_aggregate_exprs(std::iter::once(expr)).is_empty() | ||
| } | ||
| SelectExpr::Wildcard(_) | SelectExpr::QualifiedWildcard(_, _) => true, | ||
| }); | ||
|
|
||
| if has_non_aggregate_expr && !aggr_exprs.is_empty() { | ||
| return plan_err!( | ||
| "Column in SELECT must be in GROUP BY or an aggregate function" | ||
| ); | ||
| } | ||
|
|
||
| // Fallback to projection | ||
| if matches!(plan, LogicalPlan::Aggregate(_)) | ||
| || has_non_aggregate_expr | ||
| || aggr_exprs.is_empty() | ||
| { | ||
|
Comment on lines
+464
to
+467
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These checks I find a little confusing; what is the significance of the plan already being an aggregate therefore we fallback to projection? And does checking
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good questions - I agree the conditions are not very clear as written. I’ll try simplifying this logic and see if we can reduce it to just checking for aggregate expressions, and only keep additional conditions if they’re strictly necessary. |
||
| let project_plan = | ||
| LogicalPlanBuilder::from(plan).project(expr_list)?.build()?; | ||
|
|
||
| return Ok(DataFrame { | ||
| session_state: self.session_state, | ||
| plan: project_plan, | ||
| projection_requires_validation: false, | ||
| }); | ||
| } | ||
|
|
||
| // Unique name generator | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's quite a bit of logic introduced here, I'm trying to wrap my head around. Is my understanding correct that we're introducing an aggregate node, naming them unique names, then applying a projection on top based on these unique generated names? Is it feasible to simplify this to pass all the aggregate exprs directly into creating an aggregate node, then applying a projection of For example:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, your understanding is correct - the implementation introduces an I also considered simplifying this to “Aggregate + Project *”, but that only works for very simple cases like As soon as the select contains expressions on top of aggregates (e.g. The mapping + projection ensures that:
So while the current approach is a bit more involved, it aligns with how logical plans typically separate aggregation from final projection.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hm that makes sense, though with the amount of logic introduced here it makes me wonder if this feature is worth it. I'll try find some time to carefully look over this.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree this seems like much more logic is added here than justified by the feature being added. Something doesn't add up 🤔
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree that the amount of logic added here is larger than what initially seemed necessary for this feature. When I started working on it, the task looked relatively straightforward, but as I moved forward I realized that supporting aggregates inside That said, I understand the concern about the implementation cost vs feature value. I’m happy to revisit the approach, simplify parts of the logic, or narrow the scope if that would make the feature a better fit for DataFusion. |
||
| let make_unique_name = | ||
| |base: String, used: &mut HashSet<String>, start: usize| { | ||
| let mut name = base.clone(); | ||
| let mut counter = start; | ||
| while used.contains(&name) { | ||
| name = format!("{base}_{counter}"); | ||
| counter += 1; | ||
| } | ||
| used.insert(name.clone()); | ||
|
|
||
| name | ||
| }; | ||
|
|
||
| // Aggregate stage | ||
| let mut aggr_map: HashMap<Expr, Expr> = HashMap::new(); | ||
| let mut aggr_used_names = HashSet::new(); | ||
| let aggr_exprs_with_alias: Vec<Expr> = aggr_exprs | ||
| .into_iter() | ||
| .map(|expr| { | ||
| let base_name = expr.name_for_alias()?; | ||
| let name = make_unique_name(base_name, &mut aggr_used_names, 1); | ||
| let aliased = expr.clone().alias(name.clone()); | ||
| let col = Expr::Column(Column::from_name(name)); | ||
| aggr_map.insert(expr, col); | ||
|
|
||
| Ok(aliased) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
||
| // Build aggregate plan | ||
| plan = LogicalPlanBuilder::from(plan) | ||
| .aggregate(Vec::<Expr>::new(), aggr_exprs_with_alias)? | ||
| .build()?; | ||
|
|
||
| // Rewrite expressions | ||
| let rewrite_expr = |expr: Expr, aggr_map: &HashMap<Expr, Expr>| -> Result<Expr> { | ||
| expr.transform(|e| { | ||
| Ok(match aggr_map.get(&e) { | ||
| Some(replacement) => Transformed::yes(replacement.clone()), | ||
| None => Transformed::no(e), | ||
| }) | ||
| }) | ||
| .map(|t| t.data) | ||
| }; | ||
|
|
||
| // Projection stage | ||
| let mut rewritten_exprs = Vec::with_capacity(expr_list.len()); | ||
| let mut projection_used_names = HashSet::new(); | ||
| for select_expr in expr_list.into_iter() { | ||
| match select_expr { | ||
| SelectExpr::Expression(expr) => { | ||
| let base_alias = expr.name_for_alias()?; | ||
| let rewritten = rewrite_expr(expr, &aggr_map)?; | ||
| let name = | ||
| make_unique_name(base_alias, &mut projection_used_names, 1); | ||
| // Avoid adding a redundant alias if the rewritten expression | ||
| // already has the desired name. | ||
| let final_expr = match rewritten.name_for_alias() { | ||
| Ok(existing) if existing == name => rewritten, | ||
| _ => rewritten.alias(name), | ||
| }; | ||
|
|
||
| rewritten_exprs.push(SelectExpr::Expression(final_expr)); | ||
| } | ||
| other => rewritten_exprs.push(other), | ||
| } | ||
| } | ||
|
|
||
| // Final projection | ||
| let project_plan = LogicalPlanBuilder::from(plan) | ||
| .project(rewritten_exprs)? | ||
| .build()?; | ||
|
|
||
| Ok(DataFrame { | ||
| session_state: self.session_state, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Whats the reasoning behind adding these new examples? Did we not have examples of aggregation before with DataFrame API?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the question. We do have aggregation examples, but I found that there wasn’t a simple, straightforward example demonstrating basic aggregation with the DataFrame API in isolation.
While working on this PR, I actually had to search for such an example myself and even asked in the DataFusion Discord for clarification. That suggested there may be a small gap in discoverability for this common use case.
The goal of adding these examples is to provide:
This should help users better understand the different approaches and choose the one that fits their use case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe we can add them as a separate PR -- this PR is already pretty big
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That makes sense - I totally agree that the examples can be moved into a separate PR, especially since this one has already grown quite a bit.
My motivation for adding them here was to provide some context and usage examples for the new functionality, but I’m happy to split them out to keep this PR more focused.