You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/11/23 07:02:19 UTC

[GitHub] [spark] amaliujia opened a new pull request, #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

amaliujia opened a new pull request, #38768:
URL: https://github.com/apache/spark/pull/38768

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'core/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   This PR proposes that Relations (e.g. Aggregate in this PR) should only deal with  `Expression` than `str`. `str` could be mapped to different expressions (e.g. sql expression, unresolved_attribute, etc.). Relations are not supposed to understand the difference of `str` but DataFrame should understand it.
   
   This PR specifically changes for `Aggregate`.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   Codebase refactoring.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
    No
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   UT


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] grundprinzip commented on a diff in pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
grundprinzip commented on code in PR #38768:
URL: https://github.com/apache/spark/pull/38768#discussion_r1030246542


##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -79,23 +67,23 @@ def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
         )
         return res
 
-    def _map_cols_to_dict(self, fun: str, cols: List[Union[Column, str]]) -> Dict[str, str]:
-        return {x if isinstance(x, str) else x.name(): fun for x in cols}
+    def _map_cols_to_expression(self, fun: str, col: Union[Column, str]) -> Sequence[Expression]:
+        return [ScalarFunctionExpression(fun, Column(col) if isinstance(col, str) else col)]
 
-    def min(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("min", list(cols))
+    def min(self, col: Union[Column, str]) -> "DataFrame":

Review Comment:
   ```suggestion
       def min(self, col: Union[Expression, str]) -> "DataFrame":
   ```



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -79,23 +67,23 @@ def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
         )
         return res
 
-    def _map_cols_to_dict(self, fun: str, cols: List[Union[Column, str]]) -> Dict[str, str]:
-        return {x if isinstance(x, str) else x.name(): fun for x in cols}
+    def _map_cols_to_expression(self, fun: str, col: Union[Column, str]) -> Sequence[Expression]:
+        return [ScalarFunctionExpression(fun, Column(col) if isinstance(col, str) else col)]
 
-    def min(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("min", list(cols))
+    def min(self, col: Union[Column, str]) -> "DataFrame":
+        expr = self._map_cols_to_expression("min", col)
         return self.agg(expr)
 
-    def max(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("max", list(cols))
+    def max(self, col: Union[Column, str]) -> "DataFrame":
+        expr = self._map_cols_to_expression("max", col)
         return self.agg(expr)
 
-    def sum(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("sum", list(cols))
+    def sum(self, col: Union[Column, str]) -> "DataFrame":

Review Comment:
   ```suggestion
       def sum(self, col: Union[Expression, str]) -> "DataFrame":
   ```



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -79,23 +67,23 @@ def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
         )
         return res
 
-    def _map_cols_to_dict(self, fun: str, cols: List[Union[Column, str]]) -> Dict[str, str]:
-        return {x if isinstance(x, str) else x.name(): fun for x in cols}
+    def _map_cols_to_expression(self, fun: str, col: Union[Column, str]) -> Sequence[Expression]:
+        return [ScalarFunctionExpression(fun, Column(col) if isinstance(col, str) else col)]
 
-    def min(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("min", list(cols))
+    def min(self, col: Union[Column, str]) -> "DataFrame":
+        expr = self._map_cols_to_expression("min", col)
         return self.agg(expr)
 
-    def max(self, *cols: Union[Column, str]) -> "DataFrame":
-        expr = self._map_cols_to_dict("max", list(cols))
+    def max(self, col: Union[Column, str]) -> "DataFrame":

Review Comment:
   ```suggestion
       def max(self, col: Union[Expression, str]) -> "DataFrame":
   ```



##########
python/pyspark/sql/connect/plan.py:
##########
@@ -558,29 +557,19 @@ def _repr_html_(self) -> str:
 
 
 class Aggregate(LogicalPlan):
-    MeasureType = Tuple["ExpressionOrString", str]
-    MeasuresType = Sequence[MeasureType]
-    OptMeasuresType = Optional[MeasuresType]
-
     def __init__(
         self,
         child: Optional["LogicalPlan"],
         grouping_cols: List[Column],
-        measures: OptMeasuresType,

Review Comment:
   There is no longer a way to call this with empty measures?



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -164,8 +152,21 @@ def selectExpr(self, *expr: Union[str, List[str]]) -> "DataFrame":
 
         return DataFrame.withPlan(plan.Project(self._plan, *sql_expr), session=self._session)
 
-    def agg(self, exprs: Optional[GroupingFrame.MeasuresType]) -> "DataFrame":
-        return self.groupBy().agg(exprs)
+    def agg(self, *exprs: Union[Expression, Dict[str, str]]) -> "DataFrame":
+        if not exprs:
+            raise ValueError("exprs should not be empty")

Review Comment:
   ```suggestion
               raise ValueError("Argument 'exprs' must not be empty")
   ```



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -79,23 +67,23 @@ def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
         )
         return res
 
-    def _map_cols_to_dict(self, fun: str, cols: List[Union[Column, str]]) -> Dict[str, str]:
-        return {x if isinstance(x, str) else x.name(): fun for x in cols}
+    def _map_cols_to_expression(self, fun: str, col: Union[Column, str]) -> Sequence[Expression]:

Review Comment:
   ```suggestion
       def _map_cols_to_expression(self, fun: str, col: Union[Expression, str]) -> Sequence[Expression]:
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
HyukjinKwon commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1326147457

   Re: https://github.com/apache/spark/pull/38768?notification_referrer_id=NT_kwDOAGLXhbI0OTA0MTUyNTY4OjY0Nzc3MDE&notifications_query=is%3Aunread#issuecomment-1324694898
   
   Yes, please let's refactor as we offline discussed. This refactoring has to be done before starting working on functions cc @xinrong-meng 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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] zhengruifeng closed pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
zhengruifeng closed pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type
URL: https://github.com/apache/spark/pull/38768


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] amaliujia commented on a diff in pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
amaliujia commented on code in PR #38768:
URL: https://github.com/apache/spark/pull/38768#discussion_r1031035663


##########
python/pyspark/sql/connect/plan.py:
##########
@@ -558,29 +557,19 @@ def _repr_html_(self) -> str:
 
 
 class Aggregate(LogicalPlan):
-    MeasureType = Tuple["ExpressionOrString", str]
-    MeasuresType = Sequence[MeasureType]
-    OptMeasuresType = Optional[MeasuresType]
-
     def __init__(
         self,
         child: Optional["LogicalPlan"],
         grouping_cols: List[Column],
-        measures: OptMeasuresType,

Review Comment:
   This is a sequence now and I think it can be len=0 which is empty measures?



-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] amaliujia commented on a diff in pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
amaliujia commented on code in PR #38768:
URL: https://github.com/apache/spark/pull/38768#discussion_r1031750623


##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -51,24 +52,11 @@
 
 
 class GroupingFrame(object):

Review Comment:
   Renamed



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -51,24 +52,11 @@
 
 
 class GroupingFrame(object):
-
-    MeasuresType = Union[Sequence[Tuple["ExpressionOrString", str]], Dict[str, str]]
-    OptMeasuresType = Optional[MeasuresType]
-
     def __init__(self, df: "DataFrame", *grouping_cols: Union[Column, str]) -> None:
         self._df = df
         self._grouping_cols = [x if isinstance(x, Column) else df[x] for x in grouping_cols]
 
-    def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
-
-        # Normalize the dictionary into a list of tuples.
-        if isinstance(exprs, Dict):
-            measures = list(exprs.items())
-        elif isinstance(exprs, List):
-            measures = exprs
-        else:
-            measures = []
-
+    def agg(self, measures: Sequence[Expression]) -> "DataFrame":
         res = DataFrame.withPlan(

Review Comment:
   added.



-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] grundprinzip commented on a diff in pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
grundprinzip commented on code in PR #38768:
URL: https://github.com/apache/spark/pull/38768#discussion_r1031157012


##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -51,24 +52,11 @@
 
 
 class GroupingFrame(object):
-
-    MeasuresType = Union[Sequence[Tuple["ExpressionOrString", str]], Dict[str, str]]
-    OptMeasuresType = Optional[MeasuresType]
-
     def __init__(self, df: "DataFrame", *grouping_cols: Union[Column, str]) -> None:
         self._df = df
         self._grouping_cols = [x if isinstance(x, Column) else df[x] for x in grouping_cols]
 
-    def agg(self, exprs: Optional[MeasuresType] = None) -> "DataFrame":
-
-        # Normalize the dictionary into a list of tuples.
-        if isinstance(exprs, Dict):
-            measures = list(exprs.items())
-        elif isinstance(exprs, List):
-            measures = exprs
-        else:
-            measures = []
-
+    def agg(self, measures: Sequence[Expression]) -> "DataFrame":
         res = DataFrame.withPlan(

Review Comment:
   In OSS we have an assert here
   
   ```
   >>> df.groupBy("state").agg()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "/Users/martin.grund/Development/spark/python/pyspark/sql/group.py", line 162, in agg
       assert exprs, "exprs should not be empty"
   AssertionError: exprs should not be empty
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] zhengruifeng commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
zhengruifeng commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1326936108

   merged into master


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] zhengruifeng commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
zhengruifeng commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1324694898

   I think it is time to refactor `Column` to something like:
   
   ```
   class Column:
   
       def __init__(self, expr: Expression) -> None:
           self.expr = expr
       ...
   ```
   
   we'd better try to match the API shape at first, otherwise it will be hard to do so after we make it more complicated.
   
   cc @HyukjinKwon 


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] amaliujia commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
amaliujia commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1325616449

   @zhengruifeng sure maybe we can do that refactoring in this PR directly.
   
   the plain `str` passing through to relations became a blocker for that refactoring (given there is no place for a plain `str` in expression system, it must be wrapped).


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] amaliujia commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
amaliujia commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1325935616

   @zhengruifeng @grundprinzip can you take another look?


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] zhengruifeng commented on a diff in pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
zhengruifeng commented on code in PR #38768:
URL: https://github.com/apache/spark/pull/38768#discussion_r1031102422


##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -51,24 +52,11 @@
 
 
 class GroupingFrame(object):

Review Comment:
   not related to this PR, but shall we rename it `GroupedData` to be the same with pyspark?



##########
python/pyspark/sql/connect/dataframe.py:
##########
@@ -164,8 +156,20 @@ def selectExpr(self, *expr: Union[str, List[str]]) -> "DataFrame":
 
         return DataFrame.withPlan(plan.Project(self._plan, *sql_expr), session=self._session)
 
-    def agg(self, exprs: Optional[GroupingFrame.MeasuresType]) -> "DataFrame":
-        return self.groupBy().agg(exprs)
+    def agg(self, *exprs: Union[Expression, Dict[str, str]]) -> "DataFrame":
+        if not exprs:
+            raise ValueError("Argument 'exprs' must not be empty")
+
+        if len(exprs) == 1 and isinstance(exprs[0], dict):
+            measures = []
+            for e, fun in exprs[0].items():
+                measures.append(ScalarFunctionExpression(fun, Column(e)))

Review Comment:
   ```suggestion
               measures = [ScalarFunctionExpression(f, Column(e)) for e, f in exprs[0].items()]
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] amaliujia commented on pull request #38768: [SPARK-41230][CONNECT][PYTHON] Remove `str` from Aggregate expression type

Posted by GitBox <gi...@apache.org>.
amaliujia commented on PR #38768:
URL: https://github.com/apache/spark/pull/38768#issuecomment-1326741957

   This PR is a blocker for the refactoring. I will refactor based on the change in this PR, which will further unblocks functions.


-- 
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: reviews-unsubscribe@spark.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org