You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "itholic (via GitHub)" <gi...@apache.org> on 2023/08/01 17:54:21 UTC

[GitHub] [spark] itholic commented on a diff in pull request #42272: [SPARK-44508][PYTHON][DOCS] Add user guide for Python user-defined table functions

itholic commented on code in PR #42272:
URL: https://github.com/apache/spark/pull/42272#discussion_r1280957265


##########
examples/src/main/python/sql/udtf.py:
##########
@@ -0,0 +1,169 @@
+#
+# 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.
+#
+
+"""
+A simple example demonstrating Python UDTFs in Spark
+Run with:
+  ./bin/spark-submit examples/src/main/python/sql/udtf.py
+"""
+
+# NOTE that this file is imported in user guide in PySpark documentation.
+# The codes are referred via line numbers. See also `literalinclude` directive in Sphinx.
+import pandas as pd
+from typing import Iterator, Any
+
+from pyspark.sql import SparkSession
+from pyspark.sql.pandas.utils import require_minimum_pandas_version, require_minimum_pyarrow_version
+
+# Python UDTFs use Arrow by default.
+require_minimum_pandas_version()
+require_minimum_pyarrow_version()
+
+
+def python_udtf_simple_example(spark: SparkSession):
+
+    from pyspark.sql.functions import lit, udtf
+
+    class SimpleUDTF:
+        def eval(self, x: int, y: int):
+            yield x + y, x - y
+
+    # Now, create a Python UDTF using the defined class and specify a return type
+    func = udtf(SimpleUDTF, returnType="c1: int, c2: int")
+
+    func(lit(1), lit(2)).show()
+    # +---+---+
+    # | c1| c2|
+    # +---+---+
+    # |  3| -1|
+    # +---+---+
+
+
+def python_udtf_registration(spark: SparkSession):
+
+    from pyspark.sql.functions import udtf
+
+    # Use the decorator to define the UDTF.
+    @udtf(returnType="c1: int, c2: int")
+    class PlusOne:
+        def eval(self, x: int):
+            yield x, x + 1
+
+    # Register the UDTF
+    spark.udtf.register("plus_one", PlusOne)
+    
+    # Use the UDTF in SQL
+    spark.sql("SELECT * FROM plus_one(1)").show()
+    # +---+---+
+    # | c1| c2|
+    # +---+---+
+    # |  1|  2|
+    # +---+---+
+
+    # Use the UDTF in SQL with lateral join
+    spark.sql("SELECT * FROM VALUES (0, 1), (1, 2) t(x, y), LATERAL plus_one(x)").show()
+    # +---+---+---+---+
+    # |  x|  y| c1| c2|
+    # +---+---+---+---+
+    # |  0|  1|  0|  1|
+    # |  1|  2|  1|  2|
+    # +---+---+---+---+
+
+
+def python_udtf_terminate_example(spark: SparkSession):
+
+    from pyspark.sql.functions import udtf
+
+    @udtf(returnType="cnt: int")
+    class CountUDTF:
+        def __init__(self):
+            self.count = 0
+
+        def eval(self, x):
+            self.count += 1
+    
+        def terminate(self):
+            yield self.count,

Review Comment:
   qq: should we always yield the data as `tuple` for UDTF?



##########
python/docs/source/user_guide/sql/python_udtf.rst:
##########
@@ -0,0 +1,140 @@
+..  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.
+
+===========================================
+Python User-defined Table Functions (UDTFs)
+===========================================
+
+Spark 3.5 introduces a new type of user-defined fucntion: Python user-defined table functions (UDTFs),

Review Comment:
   typo: "fucntion" -> "function"



##########
python/docs/source/user_guide/sql/python_udtf.rst:
##########
@@ -0,0 +1,140 @@
+..  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.
+
+===========================================
+Python User-defined Table Functions (UDTFs)
+===========================================
+
+Spark 3.5 introduces a new type of user-defined fucntion: Python user-defined table functions (UDTFs),
+which take zero or more arguments and return a set of rows.
+
+Implementing a Python UDTF
+--------------------------
+
+.. currentmodule:: pyspark.sql.functions
+
+To implement a Python UDTF, you can implement this class:
+
+.. code-block:: python
+
+    class PythonUDTF:
+
+        def __init__(self) -> None:
+            """
+            Initialize the user-defined table function (UDTF).
+
+            This method is optional to implement and is called once when the UDTF is
+            instantiated. Use it to perform any initialization required for the UDTF.
+            """
+            ...
+
+        def eval(self, *args: Any) -> Iterator[Any]:
+            """"
+            Evaluate the function using the given input arguments.
+
+            This method is required to implement.
+
+            Args:
+                *args: Arbitrary positional arguments representing the input
+                       to the UDTF.
+
+            Yields:
+                tuple: A tuple representing a single row in the UDTF result relation.
+                       Yield thisas many times as needed to produce multiple rows.

Review Comment:
   typo?: "thisas" -> "this as"



##########
examples/src/main/python/sql/udtf.py:
##########
@@ -0,0 +1,169 @@
+#
+# 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.
+#
+
+"""
+A simple example demonstrating Python UDTFs in Spark
+Run with:
+  ./bin/spark-submit examples/src/main/python/sql/udtf.py
+"""
+
+# NOTE that this file is imported in user guide in PySpark documentation.

Review Comment:
   nit: "user guide" -> "User Guides" to follow official documentation name?
   
   Also maybe adding a doc link(https://spark.apache.org/docs/latest/api/python/user_guide/index.html) would helpful?



##########
python/docs/source/user_guide/sql/python_udtf.rst:
##########
@@ -0,0 +1,140 @@
+..  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.
+
+===========================================
+Python User-defined Table Functions (UDTFs)
+===========================================
+
+Spark 3.5 introduces a new type of user-defined fucntion: Python user-defined table functions (UDTFs),
+which take zero or more arguments and return a set of rows.
+
+Implementing a Python UDTF
+--------------------------
+
+.. currentmodule:: pyspark.sql.functions
+
+To implement a Python UDTF, you can implement this class:
+
+.. code-block:: python
+
+    class PythonUDTF:
+
+        def __init__(self) -> None:
+            """
+            Initialize the user-defined table function (UDTF).
+
+            This method is optional to implement and is called once when the UDTF is
+            instantiated. Use it to perform any initialization required for the UDTF.
+            """
+            ...
+
+        def eval(self, *args: Any) -> Iterator[Any]:
+            """"
+            Evaluate the function using the given input arguments.
+
+            This method is required to implement.
+
+            Args:

Review Comment:
   I'm not pretty sure if we should follow [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html#sections) style here since we're following them in overall PySpark code base. WDYT @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