You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "JasonLi-cn (via GitHub)" <gi...@apache.org> on 2024/07/15 04:13:49 UTC

[PR] feat: support group by unnest [datafusion]

JasonLi-cn opened a new pull request, #11469:
URL: https://github.com/apache/datafusion/pull/11469

   ## 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 #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   ## Rationale for this change
   
   support SQLs like:
   ```
   SELECT unnest(list_type_col) c0, count(1) FROM tab GROUP BY c0;
   SELECT unnest(unnest(recursive_list_type_col)) c0, count(1) FROM tab GROUP BY c0;
   ```
   
   ## What changes are included in this PR?
   
   <!--
   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.
   -->
   
   ## Are these changes tested?
   
   Yes. Has added some test cases into `unnest.slt`.
   
   ## Are there any user-facing changes?
   
   Simplified SQL syntax, eg:
   
   ```
   SELECT t0.c0, count(1) FROM (SELECT unnest(list_col) c0 FROM tal) t0 GROUP BY t0.c0;
   ```
   can replace by
   ```
   SELECT unnest(list_col) c0, count(1) FROM tal GROUP BY c0;
   ```
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2227809461

   Thank you for the new feature, I have some thoughts for an alternative design:
   
   Recursive aggregate functions are generally unsupported: e.g. `select sum(sum(v1)) from t1` is not supported in DataFusion/Postgres/DuckDB.
   For this `unnest()` case, a recursive call is required, DuckDB uses: https://duckdb.org/docs/sql/query_syntax/unnest.html#recursive-unnest
   
   What do you think about implementing DuckDB syntax, I think it's better for:
   1. Keep the SQL syntax consistent and avoid nested aggregate function
   2. Avoid changing planner code (which might be error-prone), and keep the unnest logic within the aggregate function body


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2227760383

   I wonder why we need to specialize group by expression for unnest, does that mean we need to specialize unnest with filter by too? 🤔 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "JasonLi-cn (via GitHub)" <gi...@apache.org>.
JasonLi-cn commented on code in PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#discussion_r1679085120


##########
datafusion/sql/src/select.rs:
##########
@@ -297,6 +298,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         input: LogicalPlan,
         select_exprs: Vec<Expr>,
     ) -> Result<LogicalPlan> {
+        // Try process group by unnest
+        let input = self.try_process_aggregate_unnest(input)?;

Review Comment:
   I agree with you. We need to verify this logic in the future



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2227896445

   > > Thank you for the new feature, I have some thoughts for an alternative design:
   > > Recursive aggregate functions are generally unsupported: e.g. `select sum(sum(v1)) from t1` is not supported in DataFusion/Postgres/DuckDB. For this `unnest()` case, a recursive call is required, DuckDB uses: https://duckdb.org/docs/sql/query_syntax/unnest.html#recursive-unnest
   > > What do you think about implementing DuckDB syntax, I think it's better for:
   > > 
   > > 1. Keep the SQL syntax consistent and avoid nested aggregate function
   > > 2. Avoid changing planner code (which might be error-prone), and keep the recursive unnest logic within the aggregate function body
   > 
   > Thank you for your reply.
   > 
   > 1 If "keep the recursive unnest logic within the aggregate function body" is implemented, at least the following work needs to be done: (1) Improve the logic of `Expr::Unnest` processing in `TypeCoercionRewriter`; (2) Implement `create_physical_expr` function to support `Expr::Unnest`; (3) Maybe there are other tasks... Also, I would like to check whether you are talking about `aggregate function` or `AggregateExec` here. Because pg currently does not support aggregation functions that include `unnest`. (Of course, it is not appropriate to illustrate this issue only by pg here)
   > 
   > 2 If 'Recursive Unnest' is handled like DuckDB, how do we implement the unnest(unnest(list_column)) syntax when the user needs it? By optimization rules?
   
   @JasonLi-cn I mistakenly thought `unnest` was some aggregate function... please ignore my previous reply, and also sorry for the confusion.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "JasonLi-cn (via GitHub)" <gi...@apache.org>.
JasonLi-cn commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2227877569

   > Thank you for the new feature, I have some thoughts for an alternative design:
   > 
   > Recursive aggregate functions are generally unsupported: e.g. `select sum(sum(v1)) from t1` is not supported in DataFusion/Postgres/DuckDB. For this `unnest()` case, a recursive call is required, DuckDB uses: https://duckdb.org/docs/sql/query_syntax/unnest.html#recursive-unnest
   > 
   > What do you think about implementing DuckDB syntax, I think it's better for:
   > 
   > 1. Keep the SQL syntax consistent and avoid nested aggregate function
   > 2. Avoid changing planner code (which might be error-prone), and keep the recursive unnest logic within the aggregate function body
   
   Thank you for your reply.
   
   1 If "keep the recursive unnest logic within the aggregate function body" is implemented, at least the following work needs to be done:
   (1) Improve the logic of `Expr::Unnest` processing in `TypeCoercionRewriter`;
   (2) Implement `create_physical_expr` function to support `Expr::Unnest`;
   (3) Maybe there are other tasks...
   Also, I would like to check whether you are talking about `aggregate function` or `AggregateExec` here. Because pg currently does not support aggregation functions that include `unnest`. (Of course, it is not appropriate to illustrate this issue only by pg here)
   
   2 If 'Recursive Unnest' is handled like DuckDB, how do we implement the unnest(unnest(list_column)) syntax when the user needs it? By optimization rules?
    


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#discussion_r1678290570


##########
datafusion/sqllogictest/test_files/unnest.slt:
##########
@@ -556,4 +554,126 @@ physical_plan
 05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
 06)----------UnnestExec
 07)------------ProjectionExec: expr=[column3@0 as unnest(recursive_unnest_table.column3), column3@0 as column3]
-08)--------------MemoryExec: partitions=1, partition_sizes=[1]
\ No newline at end of file
+08)--------------MemoryExec: partitions=1, partition_sizes=[1]
+
+
+## group by unnest
+
+### without agg exprs
+query I
+select unnest(column1) c1 from unnest_table group by c1 order by c1;
+----
+1
+2
+3
+4
+5
+6
+12
+
+query II
+select unnest(column1) c1, unnest(column2) c2 from unnest_table group by c1, c2 order by c1, c2;

Review Comment:
   Could you also please add a test with grouping directly in the group by list (not a reference to the select list)
   
   Like
   
   ```suggestion
   select unnest(column1), count(*) from unnest_table group by unnest(column1);
   ```



##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,102 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    fn try_process_group_by_unnest(
+        &self,
+        agg: &Aggregate,
+    ) -> Result<(LogicalPlan, Vec<Expr>)> {
+        let mut aggr_expr_using_columns: Option<HashSet<Expr>> = None;
+
+        let input = agg.input.as_ref();
+        let group_by_exprs = &agg.group_expr;
+        let aggr_exprs = &agg.aggr_expr;
+
+        // rewrite group_by_exprs
+        let mut intermediate_plan = input.clone();
+        let mut intermediate_select_exprs = group_by_exprs.to_vec();
+
+        loop {
+            let mut unnest_columns = vec![];
+            let mut inner_projection_exprs = vec![];
+
+            let outer_projection_exprs: Vec<Expr> = intermediate_select_exprs
+                .iter()
+                .map(|expr| {
+                    transform_bottom_unnest(
+                        &intermediate_plan,
+                        &mut unnest_columns,
+                        &mut inner_projection_exprs,
+                        expr,
+                    )
+                })
+                .collect::<Result<Vec<_>>>()?
+                .into_iter()
+                .flatten()
+                .collect();
+
+            if unnest_columns.is_empty() {
+                break;
+            } else {
+                let columns = unnest_columns.into_iter().map(|col| col.into()).collect();
+                let unnest_options = UnnestOptions::new().with_preserve_nulls(false);
+
+                let mut projection_exprs = match &aggr_expr_using_columns {
+                    Some(exprs) => (*exprs).clone(),
+                    None => {
+                        let mut columns = HashSet::new();
+                        for expr in aggr_exprs {
+                            expr.apply(|expr| {
+                                if let Expr::Column(c) = expr {
+                                    columns.insert(Expr::Column(c.clone()));
+                                }
+                                Ok(TreeNodeRecursion::Continue)
+                            })
+                            // As the closure always returns Ok, this "can't" error
+                            .expect("Unexpected error");
+                        }
+                        aggr_expr_using_columns = Some(columns.clone());
+                        columns
+                    }
+                };
+                projection_exprs.extend(inner_projection_exprs);
+
+                let plan = LogicalPlanBuilder::from(intermediate_plan.clone())

Review Comment:
   maybe you could avoid the clone with something like
   
   ```suggestion
                   let intermediate_plan = LogicalPlanBuilder::from(intermediate_plan,
   ```



##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,102 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    fn try_process_group_by_unnest(
+        &self,
+        agg: &Aggregate,
+    ) -> Result<(LogicalPlan, Vec<Expr>)> {
+        let mut aggr_expr_using_columns: Option<HashSet<Expr>> = None;
+
+        let input = agg.input.as_ref();
+        let group_by_exprs = &agg.group_expr;
+        let aggr_exprs = &agg.aggr_expr;
+
+        // rewrite group_by_exprs

Review Comment:
   I wonder if you could add some documentation comments to this function that explains what it does
   
   Ideally such documentation could include an example showing what it is necessary to handle group by specially



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support `unnest` in GROUP BY clause [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2231854255

   I merged up to resolve a conflict as well


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "JasonLi-cn (via GitHub)" <gi...@apache.org>.
JasonLi-cn commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2229933369

   > Thank you @JasonLi-cn -- I think this PR looks good to me. Thank you for the contribution
   > 
   > I think adding some comments about what `try_process_group_by_unnest` is doing and why would help improve this code but I don't think it is required prior to merge
   > 
   > c @jonahgao
   
   Thank you @alamb for your review. I have completed the code modification according to your modification suggestions.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support `unnest` in GROUP BY clause [datafusion]

Posted by "jonahgao (via GitHub)" <gi...@apache.org>.
jonahgao merged PR #11469:
URL: https://github.com/apache/datafusion/pull/11469


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support `unnest` in GROUP BY clause [datafusion]

Posted by "jonahgao (via GitHub)" <gi...@apache.org>.
jonahgao commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2232144289

   Thanks @JasonLi-cn @alamb 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#discussion_r1680028460


##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,118 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    /// Try converting Unnest(Expr) of group by to Unnest/Projection
+    /// Return the new input and group_by_exprs of Aggregate.
+    fn try_process_group_by_unnest(
+        &self,
+        agg: &Aggregate,
+    ) -> Result<(LogicalPlan, Vec<Expr>)> {
+        let mut aggr_expr_using_columns: Option<HashSet<Expr>> = None;
+
+        let input = agg.input.as_ref();
+        let group_by_exprs = &agg.group_expr;
+        let aggr_exprs = &agg.aggr_expr;
+
+        // process unnest of group_by_exprs, and input of agg will be rewritten
+        // for example:
+        //
+        // ```
+        // Aggregate: groupBy=[[UNNEST(Column(Column { relation: Some(Bare { table: "tab" }), name: "array_col" }))]], aggr=[[]]
+        //   TableScan: tab
+        // ```
+        //
+        // will be transformed into
+        //
+        // ```
+        // Aggregate: groupBy=[[unnest(tab.array_col)]], aggr=[[]]
+        //   Unnest: lists[unnest(tab.array_col)] structs[]
+        //     Projection: tab.array_col AS unnest(tab.array_col)
+        //       TableScan: tab
+        // ```
+        let mut intermediate_plan = input.clone();

Review Comment:
   I pushed 810ca8b80 which avoids the cloning in this function



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#discussion_r1680032211


##########
datafusion/sql/src/select.rs:
##########
@@ -297,6 +298,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         input: LogicalPlan,
         select_exprs: Vec<Expr>,
     ) -> Result<LogicalPlan> {
+        // Try process group by unnest
+        let input = self.try_process_aggregate_unnest(input)?;

Review Comment:
   Tracked in https://github.com/apache/datafusion/issues/11498



##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,118 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    /// Try converting Unnest(Expr) of group by to Unnest/Projection
+    /// Return the new input and group_by_exprs of Aggregate.
+    fn try_process_group_by_unnest(

Review Comment:
   Tracked in https://github.com/apache/datafusion/issues/11498



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "JasonLi-cn (via GitHub)" <gi...@apache.org>.
JasonLi-cn commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2227811590

   > I wonder why we need to specialize group by expression for unnest, does that mean we need to specialize unnest with filter by too? 🤔
   
   - Pg supports group by `unnest` expression;
   - Our user needs this syntax support. 
   
   So, I tried to implement it in the community version.
   
   As far as I know, pg does not currently support unnest in filter, so I'm not sure it needs to be implemented.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "jonahgao (via GitHub)" <gi...@apache.org>.
jonahgao commented on code in PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#discussion_r1678992594


##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,118 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    /// Try converting Unnest(Expr) of group by to Unnest/Projection
+    /// Return the new input and group_by_exprs of Aggregate.
+    fn try_process_group_by_unnest(

Review Comment:
   This function seems to have some code repetition with function [try_process_unnest](https://github.com/apache/datafusion/blob/f204869ff55bb3e39cf23fc0a34ebd5021e6773f/datafusion/sql/src/select.rs#L295). 
   
   I wonder if there's a better way to handle this, such as planning unnest before aggregation, and then reusing the current group-by planning logic. This seems more intuitive to me. But I'm not sure about it.
   



##########
datafusion/sql/src/select.rs:
##########
@@ -297,6 +298,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
         input: LogicalPlan,
         select_exprs: Vec<Expr>,
     ) -> Result<LogicalPlan> {
+        // Try process group by unnest
+        let input = self.try_process_aggregate_unnest(input)?;

Review Comment:
   If unnest has already been processed by `try_process_aggregate_unnest`, does the following logic for handling `unnest` become redundant?



##########
datafusion/sql/src/select.rs:
##########
@@ -354,6 +358,118 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
             .build()
     }
 
+    fn try_process_aggregate_unnest(&self, input: LogicalPlan) -> Result<LogicalPlan> {
+        match &input {
+            LogicalPlan::Aggregate(agg) => {
+                let (new_input, new_group_by_exprs) =
+                    self.try_process_group_by_unnest(agg)?;
+                LogicalPlanBuilder::from(new_input)
+                    .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                    .build()
+            }
+            LogicalPlan::Filter(filter) => match filter.input.as_ref() {
+                LogicalPlan::Aggregate(agg) => {
+                    let (new_input, new_group_by_exprs) =
+                        self.try_process_group_by_unnest(agg)?;
+                    LogicalPlanBuilder::from(new_input)
+                        .aggregate(new_group_by_exprs, agg.aggr_expr.clone())?
+                        .filter(filter.predicate.clone())?
+                        .build()
+                }
+                _ => Ok(input),
+            },
+            _ => Ok(input),
+        }
+    }
+
+    /// Try converting Unnest(Expr) of group by to Unnest/Projection
+    /// Return the new input and group_by_exprs of Aggregate.
+    fn try_process_group_by_unnest(
+        &self,
+        agg: &Aggregate,
+    ) -> Result<(LogicalPlan, Vec<Expr>)> {
+        let mut aggr_expr_using_columns: Option<HashSet<Expr>> = None;
+
+        let input = agg.input.as_ref();
+        let group_by_exprs = &agg.group_expr;
+        let aggr_exprs = &agg.aggr_expr;
+
+        // process unnest of group_by_exprs, and input of agg will be rewritten
+        // for example:
+        //
+        // ```
+        // Aggregate: groupBy=[[UNNEST(Column(Column { relation: Some(Bare { table: "tab" }), name: "array_col" }))]], aggr=[[]]
+        //   TableScan: tab
+        // ```
+        //
+        // will be transformed into
+        //
+        // ```
+        // Aggregate: groupBy=[[unnest(tab.array_col)]], aggr=[[]]
+        //   Unnest: lists[unnest(tab.array_col)] structs[]
+        //     Projection: tab.array_col AS unnest(tab.array_col)
+        //       TableScan: tab
+        // ```
+        let mut intermediate_plan = input.clone();

Review Comment:
   Is it possible to avoid this clone?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support `unnest` in GROUP BY clause [datafusion]

Posted by "JasonLi-cn (via GitHub)" <gi...@apache.org>.
JasonLi-cn commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2231980745

   > I merged up to resolve a conflict as well
   
   Thank you @alamb for your help to modify the code, I learned a lot from it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat: support group by unnest [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #11469:
URL: https://github.com/apache/datafusion/pull/11469#issuecomment-2228367521

   @JasonLi-cn Is it better to move the logic into `try_process_unnest`?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org