Skip to content

DataFrame API: allow aggregate functions in select() (#17874) - #21021

Closed
cj-zhukov wants to merge 12 commits into
apache:mainfrom
cj-zhukov:cj-zhukov/DataFrame-API-allow-aggregate-functions-in-select
Closed

cj-zhukov wants to merge 12 commits into
apache:mainfrom
cj-zhukov:cj-zhukov/DataFrame-API-allow-aggregate-functions-in-select

Conversation

@cj-zhukov

@cj-zhukov cj-zhukov commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

DataFrame::select currently does not support aggregate expressions directly.
Users must explicitly call DataFrame::aggregate. This PR improves ergonomics by allowing aggregate expressions inside select, while preserving existing behavior and validation rules.

What changes are included in this PR?

  • Added support for using aggregate functions directly in DataFrame::select
  • Updated snapshot tests to reflect the new logical plan datafusion-cli/tests/snapshots/cli_explain_environment_overrides@explain_plan_environment_overrides.snap

Are these changes tested?

  • Existing tests continue to pass
  • Added new test for this new use case test_dataframe_api_aggregate_fn_in_select

Are there any user-facing changes?

Yes (behavioral improvement, no API changes).
Users can now use aggregate functions directly in select() without explicitly calling aggregate().

ctx.table("aggregate_test_100")
    .await?
    .select(vec![
        approx_distinct(col("c9")).alias("count_c9"),
        approx_distinct(cast(col("c9"), arrow_schema::DataType::Utf8View))
            .alias("count_c9_str"),
    ])?
    .show()
    .await?;

Previously, this required:

ctx.table("aggregate_test_100")
    .await?
    .aggregate(
        vec![],
        vec![
            approx_distinct(col("c9")).alias("count_c9"),
            approx_distinct(cast(col("c9"), arrow_schema::DataType::Utf8View))
                .alias("count_c9_str"),
        ],
    )?
    .show()
    .await?;

Both syntaxes are now valid and can be used interchangeably.

There are no breaking changes to the public API.

@github-actions github-actions Bot added the core Core DataFusion crate label Mar 18, 2026
@martin-g

Copy link
Copy Markdown
Member

You need to update the Insta snapshot for the datafusion-cli crate

Comment thread datafusion/core/src/dataframe/mod.rs Resolved
Comment thread datafusion/core/src/dataframe/mod.rs Resolved
Comment thread datafusion/core/tests/dataframe/mod.rs Resolved
Comment thread datafusion/core/src/dataframe/mod.rs Resolved
@cj-zhukov

Copy link
Copy Markdown
Contributor Author

I've fixed the previously found bugs and added the requested tests. There's still some work in progress on generating truly unique aggregate aliases - for now, we’re using __df_agg_{i}.

@cj-zhukov

Copy link
Copy Markdown
Contributor Author

Updated the alias generation to use expression-based names (name_for_alias) with deduplication to avoid collisions. I'm happy to iterate further or make additional improvements if needed.

@cj-zhukov

Copy link
Copy Markdown
Contributor Author

@martin-g I've updated the code with improved aggregate alias generation and all tests are passing. Could you please take another look when you have a chance?

Comment thread datafusion/core/src/dataframe/mod.rs Resolved
Comment thread datafusion/core/src/dataframe/mod.rs Resolved
Comment thread datafusion/core/src/dataframe/mod.rs Resolved
Comment thread datafusion/core/tests/dataframe/mod.rs Resolved
Comment thread datafusion/core/tests/dataframe/mod.rs Resolved
Comment thread datafusion/core/tests/dataframe/mod.rs Resolved
Comment thread datafusion/core/src/dataframe/mod.rs Resolved
@github-actions github-actions Bot added the proto Related to proto crate label Apr 1, 2026
@cj-zhukov

Copy link
Copy Markdown
Contributor Author

I’ve pushed updates addressing the previous review comments:

  • Fixed unique alias generation
  • Added new tests to improve coverage
  • Added an example with aggregates in the select doc comment
  • Added new aggregation examples in datafusion-examples that may be useful for new users
  • Updated existing tests to align with the new logic: test_aggregate_subexpr and test_aggregate_with_union

Note on roundtrip_expr_api:
I updated the test to follow the new approach, but there is still one unresolved issue with:
grouping(lit(1))
This currently fails with:
Error: Context("resolve_grouping_function", Plan("Argument Int32(1) to grouping function is not in grouping columns "))
For now, I’ve commented it out and left a TODO to revisit.

@martin-g I’ve addressed all the points from the previous review. The PR should now be ready for the next round of review.

Comment thread datafusion/core/src/dataframe/mod.rs Resolved
@cj-zhukov

Copy link
Copy Markdown
Contributor Author

Adjusted the roundtrip_expr_api test by handling grouping(lit(1)) separately.
It can’t be included in the main expr_list because it requires a grouping column. Testing it in its own branch ensures the roundtrip serialization/deserialization still passes.

@cj-zhukov

Copy link
Copy Markdown
Contributor Author

@Jefffrey Since you opened the original issue, could you take a look at this PR when you get a chance?

@Jefffrey Jefffrey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies it took me a while to get around to reviewing this

// SELECT `c1` , min(c2) as `result`
.select(vec![col("c1"), min(col("c2")).alias("result")])?;
// GROUP BY c1, compute min(c2) as result
.aggregate(vec![col("c1")], vec![min(col("c2")).alias("result")])?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these existing tests need to be changed because the new functionality interferes with them? Ideally we don't want any regression for this new (somewhat niche?) feature

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising this. The changes are not introducing a regression in existing behavior, but they do affect how certain edge cases are handled due to the new aggregate rewriting logic.

I tried to keep the impact minimal and avoid breaking existing functionality, but some adjustments in tests were needed to align with the updated behavior.

The test_aggregate_with_union case should still behave correctly, but let me know if you see a specific scenario where the behavior deviates from expectations.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand how these aren't considered regressions if we needed to fix existing test cases because of this new functionality 🤔

});
}

// Unique name generator

@Jefffrey Jefffrey Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 * on top? Or does this miss an edge case?

For example:

df.select(count(1))

Project *
  Aggregate count(1)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, your understanding is correct - the implementation introduces an Aggregate node with uniquely aliased expressions, followed by a Projection that rewrites the original select expressions to reference those aggregates.

I also considered simplifying this to “Aggregate + Project *”, but that only works for very simple cases like select(count(1)).

As soon as the select contains expressions on top of aggregates (e.g. count(1) + 1), aliases, or repeated aggregates, we need the rewrite step to correctly reference the computed aggregate outputs.

The mapping + projection ensures that:

  • aggregates are computed exactly once
  • expressions on top of aggregates are preserved
  • aliases are stable and deterministic

So while the current approach is a bit more involved, it aligns with how logical plans typically separate aggregation from final projection.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 select while preserving the existing API behavior required more complexity than I originally expected.

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.

Comment on lines +464 to +467
if matches!(plan, LogicalPlan::Aggregate(_))
|| has_non_aggregate_expr
|| aggr_exprs.is_empty()
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 has_non_aggregate_expr matter here when all we really care about is the presence of aggregate expressions (aggr_exprs.is_empty() here)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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.

// SELECT `c1` , min(c2) as `result`
.select(vec![col("c1"), min(col("c2")).alias("result")])?;
// GROUP BY c1, compute min(c2) as result
.aggregate(vec![col("c1")], vec![min(col("c2")).alias("result")])?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand how these aren't considered regressions if we needed to fix existing test cases because of this new functionality 🤔

/// # Executing subqueries
/// # Querying data
///
/// * [aggregate_global_and_grouped]: global vs grouped aggregation (`select` vs `aggregate`)

Copy link
Copy Markdown
Contributor

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?

Copy link
Copy Markdown
Contributor Author

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:

  • a minimal, easy-to-follow aggregation example
  • a side-by-side illustration of using the aggregate API vs aggregates inside select

This should help users better understand the different approaches and choose the one that fits their use case.

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

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.

});
}

// Unique name generator

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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.

@alamb

alamb commented May 26, 2026

Copy link
Copy Markdown
Contributor

What is the plan for this PR?

I am trying to clear out the approved PR queue and this one seems to have gotten stuck. Do we want to merge this? It seems to me this might be a non trivial API change for not much benefit downstream

https://datafusion.apache.org/contributor-guide/api-health.html#when-to-make-breaking-api-changes

@cj-zhukov

Copy link
Copy Markdown
Contributor Author

What is the plan for this PR?

I am trying to clear out the approved PR queue and this one seems to have gotten stuck. Do we want to merge this? It seems to me this might be a non trivial API change for not much benefit downstream

https://datafusion.apache.org/contributor-guide/api-health.html#when-to-make-breaking-api-changes

I’m totally fine with not merging this PR in its current form if we conclude that the added complexity is not justified by the downstream benefit. While working on it, it became clear that the scope and implementation complexity were larger than I initially expected.

I’m still happy to continue working on the original task if we think the functionality is valuable, but I agree it would probably make sense to narrow the scope and better define the expected behavior before moving forward further.

At the very least, this PR can still serve as a draft/prototype for future work around aggregate support in the DataFrame API and help clarify some of the edge cases and tradeoffs involved.

@Jefffrey

Copy link
Copy Markdown
Contributor

Apologies I wasn't able to get around to reviewing it, in its current state I probably won't be able to fully review it again 😅

I agree in that the current state is adding a bit too much complexity relative to the feature benefit; I only raised the original issue since I was playing around in PySpark to test some other compatibility and noted they allowed this easier to use way of specifying aggregations; so it is not really a high priority feature.

@alamb

alamb commented May 27, 2026

Copy link
Copy Markdown
Contributor

Thank you @Jefffrey and @cj-zhukov -- while it pains me to close this PR it does seem like that is the best strategy at this point. I appreciate all the efforts so far

@alamb alamb closed this May 27, 2026
zhuqi-lucas pushed a commit to raams95/datafusion that referenced this pull request Oct 22, 2026
…apache#25482)

## Which issue does this PR close?

<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax. For example
`Closes apache#123` indicates that this PR will close issue apache#123.
-->

- Closes apache#17874.

## Rationale for this change
`DataFrame::select` currently does not support aggregate expressions
directly. Users must explicitly call `DataFrame::aggregate`. This PR
improves ergonomics by allowing aggregate expressions inside `select`,
while preserving existing behavior and validation rules.

<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.

Please explain the problem you are trying to solve in terms of the
user-visible
behavior, rather than the implementation.

For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of
the
implementation. "COUNT(DISTINCT) returns wrong results when the column
contains
nulls" is the user-visible problem.
-->

## What changes are included in this PR?
- `DataFrame::select` lifts a global Aggregate when every expression is
an aggregate or a scalar over aggregates (and literals).
- Existing tests were not rewritten. 
- Examples are left for a follow-up.
<!--
There is no need to duplicate the description in the issue here, but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->

## What is the testing strategy for this PR?
- Existing `DataFrame` select/aggregate tests continue to pass without
edits.
- Added `test_dataframe_api_select_semantics` (from apache#21021, plus two
cases for this design).
- `roundtrip_expr_api` was not changed and still passes (mixed aggregate
+ scalar lists stay a `Projection`).
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code

Briefly describe how this PR is tested, and point to the specific tests
you added. For example: 'This new feature is covered by the
`sqllogictest` cases added in `foo.slt`'.

If this PR does not add tests, explain why. For example, if the change
is already covered by existing tests, please mention it.

You should also check the `codecov` bot reply on this PR to confirm the
changed code is exercised.
-->

## Are there any user-facing changes?
Yes — additive behavior only. The public `select()` signature is
unchanged. There are no breaking API changes.

Users can write a global aggregation with `select()`:
```rust
ctx.table("aggregate_test_100")
    .await?
    .select(vec![
        approx_distinct(col("c9")).alias("count_c9"),
        approx_distinct(cast(col("c9"), DataType::Utf8View))
            .alias("count_c9_str"),
    ])?
    .show()
    .await?;
```
Previously this required:
```rust

ctx.table("aggregate_test_100")
    .await?
    .aggregate(
        vec![],
        vec![
            approx_distinct(col("c9")).alias("count_c9"),
            approx_distinct(cast(col("c9"), DataType::Utf8View))
                .alias("count_c9_str"),
        ],
    )?
    .show()
    .await?;
```
Both remain valid. Grouped aggregation is still aggregate(group, aggs).
<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.

If there are any breaking changes to public APIs, please add the `api
change` label.
-->

---------

Co-authored-by: kosiew <kosiew@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate proto Related to proto crate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DataFrame API: allow aggregate functions in select()

4 participants