You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "allisonwang-db (via GitHub)" <gi...@apache.org> on 2023/07/13 19:09:07 UTC
[GitHub] [spark] allisonwang-db opened a new pull request, #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
allisonwang-db opened a new pull request, #41989:
URL: https://github.com/apache/spark/pull/41989
<!--
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 supports creating and registering Python UDTFs in Spark Connect.
### 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.
-->
To make Python UDTF work with Spark Connect.
### 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'.
-->
Yes. After this PR, users can use Python UDTFs in Spark Connect.
### 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.
-->
New unit tests
--
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 #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1263186508
##########
python/pyspark/sql/connect/udtf.py:
##########
@@ -0,0 +1,206 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+User-defined table function related classes and functions
+"""
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import warnings
+from typing import Type, TYPE_CHECKING, Optional, Union
+
+from pyspark.rdd import PythonEvalType
+from pyspark.sql.connect.column import Column
+from pyspark.sql.connect.expressions import ColumnReference
+from pyspark.sql.connect.plan import (
+ CommonInlineUserDefinedTableFunction,
+ PythonUDTF,
+)
+from pyspark.sql.connect.types import UnparsedDataType
+from pyspark.sql.connect.utils import get_python_ver
+from pyspark.sql.udtf import UDTFRegistration as PySparkUDTFRegistration
+from pyspark.sql.udtf import _validate_udtf
+from pyspark.sql.types import DataType, StructType
+from pyspark.errors import PySparkRuntimeError, PySparkTypeError
+
+
+if TYPE_CHECKING:
+ from pyspark.sql.connect._typing import ColumnOrName
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import SparkSession
+
+
+def _create_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+) -> "UserDefinedTableFunction":
+ udtf_obj = UserDefinedTableFunction(
+ cls, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic
+ )
+ return udtf_obj
+
+
+def _create_py_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ deterministic: bool = True,
+ useArrow: Optional[bool] = None,
+) -> "UserDefinedTableFunction":
+ if useArrow is not None:
+ arrow_enabled = useArrow
+ else:
+ from pyspark.sql.connect.session import _active_spark_session
+
+ arrow_enabled = (
+ _active_spark_session.conf.get("spark.sql.execution.pythonUDTF.arrow.enabled") == "true"
+ if _active_spark_session is not None
+ else True
+ )
+
+ # Create a regular Python UDTF and check for invalid handler class.
+ regular_udtf = _create_udtf(cls, returnType, name, PythonEvalType.SQL_TABLE_UDF, deterministic)
+
+ if not arrow_enabled:
+ return regular_udtf
+
+ from pyspark.sql.pandas.utils import (
+ require_minimum_pandas_version,
+ require_minimum_pyarrow_version,
+ )
+
+ try:
+ require_minimum_pandas_version()
+ require_minimum_pyarrow_version()
+ except ImportError as e:
+ warnings.warn(
+ f"Arrow optimization for Python UDTFs cannot be enabled: {str(e)}. "
+ f"Falling back to using regular Python UDTFs.",
+ UserWarning,
+ )
+ return regular_udtf
+
+ from pyspark.sql.udtf import _vectorize_udtf
+
+ vectorized_udtf = _vectorize_udtf(cls)
+ return _create_udtf(
+ vectorized_udtf, returnType, name, PythonEvalType.SQL_ARROW_TABLE_UDF, deterministic
+ )
+
+
+class UserDefinedTableFunction:
+ """
+ User defined function in Python
+
+ Notes
+ -----
+ The constructor of this class is not supposed to be directly called.
+ Use :meth:`pyspark.sql.functions.udtf` to create this instance.
+ """
+
+ def __init__(
+ self,
+ func: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+ ) -> None:
+ self.func = func
+ self.returnType: DataType = (
+ UnparsedDataType(returnType) if isinstance(returnType, str) else returnType
+ )
+ self._name = name or func.__name__
+ self.evalType = evalType
+ self.deterministic = deterministic
+
+ _validate_udtf(self)
+
+ def _build_common_inline_user_defined_table_function(
+ self, *cols: "ColumnOrName"
+ ) -> CommonInlineUserDefinedTableFunction:
+ arg_cols = [
+ col if isinstance(col, Column) else Column(ColumnReference(col)) for col in cols
+ ]
+ arg_exprs = [col._expr for col in arg_cols]
+
+ udtf = PythonUDTF(
+ func=self.func,
+ return_type=self.returnType,
+ eval_type=self.evalType,
+ python_ver=get_python_ver(),
+ )
+ return CommonInlineUserDefinedTableFunction(
+ function_name=self._name,
+ function=udtf,
+ deterministic=self.deterministic,
+ arguments=arg_exprs,
+ )
+
+ def __call__(self, *cols: "ColumnOrName") -> "DataFrame":
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import _active_spark_session
+
+ if _active_spark_session is None:
+ # TODO: can we create a Spark session here?
+ raise PySparkRuntimeError(
+ "An active SparkSession is required for "
+ "executing a Python user-defined table function."
+ )
Review Comment:
oh, we don't have `getActiveSessionOrCreate` now
--
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 closed pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon closed pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
URL: https://github.com/apache/spark/pull/41989
--
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 #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1263186508
##########
python/pyspark/sql/connect/udtf.py:
##########
@@ -0,0 +1,206 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+User-defined table function related classes and functions
+"""
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import warnings
+from typing import Type, TYPE_CHECKING, Optional, Union
+
+from pyspark.rdd import PythonEvalType
+from pyspark.sql.connect.column import Column
+from pyspark.sql.connect.expressions import ColumnReference
+from pyspark.sql.connect.plan import (
+ CommonInlineUserDefinedTableFunction,
+ PythonUDTF,
+)
+from pyspark.sql.connect.types import UnparsedDataType
+from pyspark.sql.connect.utils import get_python_ver
+from pyspark.sql.udtf import UDTFRegistration as PySparkUDTFRegistration
+from pyspark.sql.udtf import _validate_udtf
+from pyspark.sql.types import DataType, StructType
+from pyspark.errors import PySparkRuntimeError, PySparkTypeError
+
+
+if TYPE_CHECKING:
+ from pyspark.sql.connect._typing import ColumnOrName
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import SparkSession
+
+
+def _create_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+) -> "UserDefinedTableFunction":
+ udtf_obj = UserDefinedTableFunction(
+ cls, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic
+ )
+ return udtf_obj
+
+
+def _create_py_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ deterministic: bool = True,
+ useArrow: Optional[bool] = None,
+) -> "UserDefinedTableFunction":
+ if useArrow is not None:
+ arrow_enabled = useArrow
+ else:
+ from pyspark.sql.connect.session import _active_spark_session
+
+ arrow_enabled = (
+ _active_spark_session.conf.get("spark.sql.execution.pythonUDTF.arrow.enabled") == "true"
+ if _active_spark_session is not None
+ else True
+ )
+
+ # Create a regular Python UDTF and check for invalid handler class.
+ regular_udtf = _create_udtf(cls, returnType, name, PythonEvalType.SQL_TABLE_UDF, deterministic)
+
+ if not arrow_enabled:
+ return regular_udtf
+
+ from pyspark.sql.pandas.utils import (
+ require_minimum_pandas_version,
+ require_minimum_pyarrow_version,
+ )
+
+ try:
+ require_minimum_pandas_version()
+ require_minimum_pyarrow_version()
+ except ImportError as e:
+ warnings.warn(
+ f"Arrow optimization for Python UDTFs cannot be enabled: {str(e)}. "
+ f"Falling back to using regular Python UDTFs.",
+ UserWarning,
+ )
+ return regular_udtf
+
+ from pyspark.sql.udtf import _vectorize_udtf
+
+ vectorized_udtf = _vectorize_udtf(cls)
+ return _create_udtf(
+ vectorized_udtf, returnType, name, PythonEvalType.SQL_ARROW_TABLE_UDF, deterministic
+ )
+
+
+class UserDefinedTableFunction:
+ """
+ User defined function in Python
+
+ Notes
+ -----
+ The constructor of this class is not supposed to be directly called.
+ Use :meth:`pyspark.sql.functions.udtf` to create this instance.
+ """
+
+ def __init__(
+ self,
+ func: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+ ) -> None:
+ self.func = func
+ self.returnType: DataType = (
+ UnparsedDataType(returnType) if isinstance(returnType, str) else returnType
+ )
+ self._name = name or func.__name__
+ self.evalType = evalType
+ self.deterministic = deterministic
+
+ _validate_udtf(self)
+
+ def _build_common_inline_user_defined_table_function(
+ self, *cols: "ColumnOrName"
+ ) -> CommonInlineUserDefinedTableFunction:
+ arg_cols = [
+ col if isinstance(col, Column) else Column(ColumnReference(col)) for col in cols
+ ]
+ arg_exprs = [col._expr for col in arg_cols]
+
+ udtf = PythonUDTF(
+ func=self.func,
+ return_type=self.returnType,
+ eval_type=self.evalType,
+ python_ver=get_python_ver(),
+ )
+ return CommonInlineUserDefinedTableFunction(
+ function_name=self._name,
+ function=udtf,
+ deterministic=self.deterministic,
+ arguments=arg_exprs,
+ )
+
+ def __call__(self, *cols: "ColumnOrName") -> "DataFrame":
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import _active_spark_session
+
+ if _active_spark_session is None:
+ # TODO: can we create a Spark session here?
+ raise PySparkRuntimeError(
+ "An active SparkSession is required for "
+ "executing a Python user-defined table function."
+ )
Review Comment:
we don't still have `getActiveSessionOrCreate` now, so I think the only workaround is using the `_active_spark_session`
--
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] ueshin commented on a diff in pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "ueshin (via GitHub)" <gi...@apache.org>.
ueshin commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1264258450
##########
python/pyspark/sql/connect/plan.py:
##########
@@ -2173,6 +2175,107 @@ def plan(self, session: "SparkConnectClient") -> proto.Relation:
return plan
+class PythonUDTF:
+ """Represents a Python user-defined table function."""
+
+ def __init__(
+ self,
+ func: Type,
+ return_type: Union[DataType, str],
+ eval_type: int,
+ python_ver: str,
+ ) -> None:
+ self._func = func
+ self._name = func.__name__
+ self._return_type: DataType = (
+ UnparsedDataType(return_type) if isinstance(return_type, str) else return_type
+ )
+ self._eval_type = eval_type
+ self._python_ver = python_ver
+
+ def _parse_return_type(self, session: "SparkConnectClient") -> StructType:
+ if isinstance(self._return_type, UnparsedDataType):
+ parsed = session._analyze(
+ method="ddl_parse", ddl_string=self._return_type.data_type_string
+ ).parsed
+ else:
+ parsed = self._return_type
+
+ if not isinstance(parsed, StructType):
+ raise PySparkTypeError(
+ error_class="INVALID_UDTF_RETURN_TYPE",
+ message_parameters={"name": self._name, "return_type": f"{parsed}"},
+ )
Review Comment:
As this check is done in the server side, we don't need to check this in client side, then we can reduce one round-trip to parse the schema. `UnparsedDataType` will be handled in `SparkConnectPlanner.transformDataType`.
--
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] xinrong-meng commented on a diff in pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "xinrong-meng (via GitHub)" <gi...@apache.org>.
xinrong-meng commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1264023458
##########
connector/connect/common/src/main/protobuf/spark/connect/relations.proto:
##########
@@ -941,6 +942,36 @@ message ApplyInPandasWithState {
string timeout_conf = 7;
}
+message CommonInlineUserDefinedTableFunction {
+ // (Required) Name of the user-defined table function.
+ string function_name = 1;
+
+ // (Optional) Whether the user-defined table function is deterministic.
+ bool deterministic = 2;
+
+ // (Optional) Function input arguments. Empty arguments are allowed.
+ repeated Expression arguments = 3;
+
+ // (Required) Type of the user-defined table function.
+ oneof function {
+ PythonUDTF python_udtf = 4;
Review Comment:
Out of curiosity will there be UDTFs in other languages?
--
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 #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on PR #41989:
URL: https://github.com/apache/spark/pull/41989#issuecomment-1637004340
Merged to 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] allisonwang-db commented on a diff in pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1263171467
##########
python/pyspark/sql/connect/udtf.py:
##########
@@ -0,0 +1,206 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+User-defined table function related classes and functions
+"""
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import warnings
+from typing import Type, TYPE_CHECKING, Optional, Union
+
+from pyspark.rdd import PythonEvalType
+from pyspark.sql.connect.column import Column
+from pyspark.sql.connect.expressions import ColumnReference
+from pyspark.sql.connect.plan import (
+ CommonInlineUserDefinedTableFunction,
+ PythonUDTF,
+)
+from pyspark.sql.connect.types import UnparsedDataType
+from pyspark.sql.connect.utils import get_python_ver
+from pyspark.sql.udtf import UDTFRegistration as PySparkUDTFRegistration
+from pyspark.sql.udtf import _validate_udtf
+from pyspark.sql.types import DataType, StructType
+from pyspark.errors import PySparkRuntimeError, PySparkTypeError
+
+
+if TYPE_CHECKING:
+ from pyspark.sql.connect._typing import ColumnOrName
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import SparkSession
+
+
+def _create_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+) -> "UserDefinedTableFunction":
+ udtf_obj = UserDefinedTableFunction(
+ cls, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic
+ )
+ return udtf_obj
+
+
+def _create_py_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ deterministic: bool = True,
+ useArrow: Optional[bool] = None,
+) -> "UserDefinedTableFunction":
+ if useArrow is not None:
+ arrow_enabled = useArrow
+ else:
+ from pyspark.sql.connect.session import _active_spark_session
+
+ arrow_enabled = (
+ _active_spark_session.conf.get("spark.sql.execution.pythonUDTF.arrow.enabled") == "true"
+ if _active_spark_session is not None
+ else True
+ )
+
+ # Create a regular Python UDTF and check for invalid handler class.
+ regular_udtf = _create_udtf(cls, returnType, name, PythonEvalType.SQL_TABLE_UDF, deterministic)
+
+ if not arrow_enabled:
+ return regular_udtf
+
+ from pyspark.sql.pandas.utils import (
+ require_minimum_pandas_version,
+ require_minimum_pyarrow_version,
+ )
+
+ try:
+ require_minimum_pandas_version()
+ require_minimum_pyarrow_version()
+ except ImportError as e:
+ warnings.warn(
+ f"Arrow optimization for Python UDTFs cannot be enabled: {str(e)}. "
+ f"Falling back to using regular Python UDTFs.",
+ UserWarning,
+ )
+ return regular_udtf
+
+ from pyspark.sql.udtf import _vectorize_udtf
+
+ vectorized_udtf = _vectorize_udtf(cls)
+ return _create_udtf(
+ vectorized_udtf, returnType, name, PythonEvalType.SQL_ARROW_TABLE_UDF, deterministic
+ )
+
+
+class UserDefinedTableFunction:
+ """
+ User defined function in Python
+
+ Notes
+ -----
+ The constructor of this class is not supposed to be directly called.
+ Use :meth:`pyspark.sql.functions.udtf` to create this instance.
+ """
+
+ def __init__(
+ self,
+ func: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+ ) -> None:
+ self.func = func
+ self.returnType: DataType = (
+ UnparsedDataType(returnType) if isinstance(returnType, str) else returnType
+ )
+ self._name = name or func.__name__
+ self.evalType = evalType
+ self.deterministic = deterministic
+
+ _validate_udtf(self)
+
+ def _build_common_inline_user_defined_table_function(
+ self, *cols: "ColumnOrName"
+ ) -> CommonInlineUserDefinedTableFunction:
+ arg_cols = [
+ col if isinstance(col, Column) else Column(ColumnReference(col)) for col in cols
+ ]
+ arg_exprs = [col._expr for col in arg_cols]
+
+ udtf = PythonUDTF(
+ func=self.func,
+ return_type=self.returnType,
+ eval_type=self.evalType,
+ python_ver=get_python_ver(),
+ )
+ return CommonInlineUserDefinedTableFunction(
+ function_name=self._name,
+ function=udtf,
+ deterministic=self.deterministic,
+ arguments=arg_exprs,
+ )
+
+ def __call__(self, *cols: "ColumnOrName") -> "DataFrame":
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import _active_spark_session
+
+ if _active_spark_session is None:
+ # TODO: can we create a Spark session here?
+ raise PySparkRuntimeError(
+ "An active SparkSession is required for "
+ "executing a Python user-defined table function."
+ )
Review Comment:
@HyukjinKwon @zhengruifeng Given that we don't have `SparkSession._getActiveSessionOrCreate()` in Spark Connect, what's the best approach to creating a Spark Connect session when the active Spark session is None? Or, should we not recommend this and instead throw an exception when the Spark Connect session is None?
--
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 #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1263180196
##########
python/pyspark/sql/connect/udtf.py:
##########
@@ -0,0 +1,206 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+User-defined table function related classes and functions
+"""
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import warnings
+from typing import Type, TYPE_CHECKING, Optional, Union
+
+from pyspark.rdd import PythonEvalType
+from pyspark.sql.connect.column import Column
+from pyspark.sql.connect.expressions import ColumnReference
+from pyspark.sql.connect.plan import (
+ CommonInlineUserDefinedTableFunction,
+ PythonUDTF,
+)
+from pyspark.sql.connect.types import UnparsedDataType
+from pyspark.sql.connect.utils import get_python_ver
+from pyspark.sql.udtf import UDTFRegistration as PySparkUDTFRegistration
+from pyspark.sql.udtf import _validate_udtf
+from pyspark.sql.types import DataType, StructType
+from pyspark.errors import PySparkRuntimeError, PySparkTypeError
+
+
+if TYPE_CHECKING:
+ from pyspark.sql.connect._typing import ColumnOrName
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import SparkSession
+
+
+def _create_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+) -> "UserDefinedTableFunction":
+ udtf_obj = UserDefinedTableFunction(
+ cls, returnType=returnType, name=name, evalType=evalType, deterministic=deterministic
+ )
+ return udtf_obj
+
+
+def _create_py_udtf(
+ cls: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ deterministic: bool = True,
+ useArrow: Optional[bool] = None,
+) -> "UserDefinedTableFunction":
+ if useArrow is not None:
+ arrow_enabled = useArrow
+ else:
+ from pyspark.sql.connect.session import _active_spark_session
+
+ arrow_enabled = (
+ _active_spark_session.conf.get("spark.sql.execution.pythonUDTF.arrow.enabled") == "true"
+ if _active_spark_session is not None
+ else True
+ )
+
+ # Create a regular Python UDTF and check for invalid handler class.
+ regular_udtf = _create_udtf(cls, returnType, name, PythonEvalType.SQL_TABLE_UDF, deterministic)
+
+ if not arrow_enabled:
+ return regular_udtf
+
+ from pyspark.sql.pandas.utils import (
+ require_minimum_pandas_version,
+ require_minimum_pyarrow_version,
+ )
+
+ try:
+ require_minimum_pandas_version()
+ require_minimum_pyarrow_version()
+ except ImportError as e:
+ warnings.warn(
+ f"Arrow optimization for Python UDTFs cannot be enabled: {str(e)}. "
+ f"Falling back to using regular Python UDTFs.",
+ UserWarning,
+ )
+ return regular_udtf
+
+ from pyspark.sql.udtf import _vectorize_udtf
+
+ vectorized_udtf = _vectorize_udtf(cls)
+ return _create_udtf(
+ vectorized_udtf, returnType, name, PythonEvalType.SQL_ARROW_TABLE_UDF, deterministic
+ )
+
+
+class UserDefinedTableFunction:
+ """
+ User defined function in Python
+
+ Notes
+ -----
+ The constructor of this class is not supposed to be directly called.
+ Use :meth:`pyspark.sql.functions.udtf` to create this instance.
+ """
+
+ def __init__(
+ self,
+ func: Type,
+ returnType: Union[StructType, str],
+ name: Optional[str] = None,
+ evalType: int = PythonEvalType.SQL_TABLE_UDF,
+ deterministic: bool = True,
+ ) -> None:
+ self.func = func
+ self.returnType: DataType = (
+ UnparsedDataType(returnType) if isinstance(returnType, str) else returnType
+ )
+ self._name = name or func.__name__
+ self.evalType = evalType
+ self.deterministic = deterministic
+
+ _validate_udtf(self)
+
+ def _build_common_inline_user_defined_table_function(
+ self, *cols: "ColumnOrName"
+ ) -> CommonInlineUserDefinedTableFunction:
+ arg_cols = [
+ col if isinstance(col, Column) else Column(ColumnReference(col)) for col in cols
+ ]
+ arg_exprs = [col._expr for col in arg_cols]
+
+ udtf = PythonUDTF(
+ func=self.func,
+ return_type=self.returnType,
+ eval_type=self.evalType,
+ python_ver=get_python_ver(),
+ )
+ return CommonInlineUserDefinedTableFunction(
+ function_name=self._name,
+ function=udtf,
+ deterministic=self.deterministic,
+ arguments=arg_exprs,
+ )
+
+ def __call__(self, *cols: "ColumnOrName") -> "DataFrame":
+ from pyspark.sql.connect.dataframe import DataFrame
+ from pyspark.sql.connect.session import _active_spark_session
+
+ if _active_spark_session is None:
+ # TODO: can we create a Spark session here?
+ raise PySparkRuntimeError(
+ "An active SparkSession is required for "
+ "executing a Python user-defined table function."
+ )
Review Comment:
currently, we use `pyspark.sql.connect.session._active_spark_session` in ml and pandas
https://github.com/apache/spark/blob/10751dc285c5c639e3343a8abc26857407522822/python/pyspark/ml/util.py#L756-L758
https://github.com/apache/spark/blob/b97ce8b9a99c570fc57dec967e7e9db3d115c1db/python/pyspark/pandas/utils.py#L484-L486
--
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] allisonwang-db commented on pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on PR #41989:
URL: https://github.com/apache/spark/pull/41989#issuecomment-1635104349
cc @HyukjinKwon @zhengruifeng @xinrong-meng
--
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] allisonwang-db commented on a diff in pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1264194640
##########
connector/connect/common/src/main/protobuf/spark/connect/relations.proto:
##########
@@ -941,6 +942,36 @@ message ApplyInPandasWithState {
string timeout_conf = 7;
}
+message CommonInlineUserDefinedTableFunction {
+ // (Required) Name of the user-defined table function.
+ string function_name = 1;
+
+ // (Optional) Whether the user-defined table function is deterministic.
+ bool deterministic = 2;
+
+ // (Optional) Function input arguments. Empty arguments are allowed.
+ repeated Expression arguments = 3;
+
+ // (Required) Type of the user-defined table function.
+ oneof function {
+ PythonUDTF python_udtf = 4;
Review Comment:
Currently only Python but more UDTFs might be supported 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: 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 #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on PR #41989:
URL: https://github.com/apache/spark/pull/41989#issuecomment-1636956966
@allisonwang-db the test failures are related
--
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] xinrong-meng commented on a diff in pull request #41989: [SPARK-43965][PYTHON][CONNECT] Support Python UDTF in Spark Connect
Posted by "xinrong-meng (via GitHub)" <gi...@apache.org>.
xinrong-meng commented on code in PR #41989:
URL: https://github.com/apache/spark/pull/41989#discussion_r1264028428
##########
python/pyspark/sql/connect/functions.py:
##########
@@ -3891,6 +3894,21 @@ def udf(
udf.__doc__ = pysparkfuncs.udf.__doc__
+def udtf(
+ cls: Optional[Type] = None,
+ *,
+ returnType: Union[StructType, str],
+ useArrow: Optional[bool] = None,
+) -> Union["UserDefinedTableFunction", functools.partial]:
Review Comment:
We typically do not use `functools.partial` as a type hint in Python. Shall we use `Callable` following the `udf` return type hints?
--
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