-
Notifications
You must be signed in to change notification settings - Fork 2k
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
Open
cj-zhukov
wants to merge
5
commits into
apache:main
Choose a base branch
from
cj-zhukov:cj-zhukov/DataFrame-API-allow-aggregate-functions-in-select
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+162
−5
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ff0ada7
DataFrame API: allow aggregate functions in select() (#17874)
cj-zhukov 1659fa7
use count instead of approx_distinct in test
cj-zhukov f9f351e
Update CLI snapshot
cj-zhukov 0262b63
fix found bugs and add tests
cj-zhukov e527e12
better aliases names
cj-zhukov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
|
|
@@ -410,21 +412,102 @@ 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 | ||
| 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()); | ||
|
|
||
| // Check for non-aggregate expressions | ||
| let has_non_aggregate_expr = expressions | ||
| .clone() | ||
| .any(|expr| find_aggregate_exprs(std::iter::once(expr)).is_empty()); | ||
|
Member
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. What about aggregate expr + non-aggregate one ? let res = df.select(vec![
count(col("c9")).alias("count_c9") + lit(1)
])?;I'd expect 101 but it returns 100
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 need to fix it |
||
|
|
||
| // Fallback to projection: | ||
| // - already aggregated | ||
| // - contains non-aggregate expressions | ||
| // - no aggregates | ||
| if matches!(plan, LogicalPlan::Aggregate(_)) | ||
| || has_non_aggregate_expr | ||
| || aggr_exprs.is_empty() | ||
| { | ||
| 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, | ||
| }); | ||
| } | ||
|
|
||
| // Assign aliases to aggregate expressions | ||
| let mut aggr_map: HashMap<Expr, Expr> = HashMap::new(); | ||
| let mut 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 mut name = base_name.clone(); | ||
| let mut counter = 1; | ||
| while used_names.contains(&name) { | ||
| name = format!("{base_name}_{counter}"); | ||
| counter += 1; | ||
| } | ||
| used_names.insert(name.clone()); | ||
| 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 to use aggregate outputs | ||
| 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) | ||
| }; | ||
|
|
||
| let mut rewritten_exprs = Vec::with_capacity(expr_list.len()); | ||
| for select_expr in expr_list.into_iter() { | ||
| match select_expr { | ||
| SelectExpr::Expression(expr) => { | ||
| let rewritten = rewrite_expr(expr.clone(), &aggr_map)?; | ||
| let alias = expr.name_for_alias()?; | ||
| rewritten_exprs.push(SelectExpr::Expression(rewritten.alias(alias))); | ||
| } | ||
| other => rewritten_exprs.push(other), | ||
| } | ||
| } | ||
|
|
||
| // Final projection | ||
| let project_plan = LogicalPlanBuilder::from(plan) | ||
| .project(rewritten_exprs)? | ||
| .build()?; | ||
|
|
||
| Ok(DataFrame { | ||
| session_state: self.session_state, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
find_aggregate_exprs()deduplicates the expressions.Test like:
fails with:
__agg_1is lostThere 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.
I agree - it needs to be fixed