Repository navigation
Conversation
|
You need to update the Insta snapshot for the datafusion-cli crate |
|
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 |
|
Updated the alias generation to use expression-based names ( |
|
@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? |
|
I’ve pushed updates addressing the previous review comments:
Note on @martin-g I’ve addressed all the points from the previous review. The PR should now be ready for the next round of review. |
|
Adjusted the |
|
@Jefffrey Since you opened the original issue, could you take a look at this PR when you get a chance? |
Jefffrey
left a comment
There was a problem hiding this comment.
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")])? |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I agree this seems like much more logic is added here than justified by the feature being added. Something doesn't add up 🤔
There was a problem hiding this comment.
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.
| if matches!(plan, LogicalPlan::Aggregate(_)) | ||
| || has_non_aggregate_expr | ||
| || aggr_exprs.is_empty() | ||
| { |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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")])? |
There was a problem hiding this comment.
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`) |
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
maybe we can add them as a separate PR -- this PR is already pretty big
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
|
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. |
|
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. |
|
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 |
…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>
Which issue does this PR close?
select()#17874.Rationale for this change
DataFrame::selectcurrently does not support aggregate expressions directly.Users must explicitly call
DataFrame::aggregate. This PR improves ergonomics by allowing aggregate expressions insideselect, while preserving existing behavior and validation rules.What changes are included in this PR?
DataFrame::selectdatafusion-cli/tests/snapshots/cli_explain_environment_overrides@explain_plan_environment_overrides.snapAre these changes tested?
test_dataframe_api_aggregate_fn_in_selectAre there any user-facing changes?
Yes (behavioral improvement, no API changes).
Users can now use aggregate functions directly in
select()without explicitly callingaggregate().Previously, this required:
Both syntaxes are now valid and can be used interchangeably.
There are no breaking changes to the public API.