You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "simicd (via GitHub)" <gi...@apache.org> on 2023/03/04 21:04:13 UTC

[GitHub] [arrow-datafusion-python] simicd opened a new pull request, #258: docs: Example of calling Python UDF & UDAF in SQL

simicd opened a new pull request, #258:
URL: https://github.com/apache/arrow-datafusion-python/pull/258

   # Which issue does this PR close?
   
   Closes #138
   
    # Rationale for this change
   Document how to utilize Python UDFs & UDAFs in SQL
   
   # What changes are included in this PR?
   Document examples & link in README.md
   
   # Are there any user-facing changes?
   Additional examples/documentation


-- 
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@arrow.apache.org

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


[GitHub] [arrow-datafusion-python] andygrove merged pull request #258: docs: Example of calling Python UDF & UDAF in SQL

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove merged PR #258:
URL: https://github.com/apache/arrow-datafusion-python/pull/258


-- 
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@arrow.apache.org

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


[GitHub] [arrow-datafusion-python] simicd commented on a diff in pull request #258: docs: Example of calling Python UDF & UDAF in SQL

Posted by "simicd (via GitHub)" <gi...@apache.org>.
simicd commented on code in PR #258:
URL: https://github.com/apache/arrow-datafusion-python/pull/258#discussion_r1125560690


##########
datafusion/__init__.py:
##########
@@ -190,7 +190,7 @@ def udaf(accum, input_type, return_type, state_type, volatility, name=None):
             "`accum` must implement the abstract base class Accumulator"
         )
     if name is None:
-        name = accum.__qualname__
+        name = accum.__qualname__.lower()

Review Comment:
   Previously calling the UDAF in SQL would fail if `name` is not specified (i.e. both `MyAccumulator(b)` and `myaccumulator(b)` would fail in the example below if `name` is not specified). With this change both the uppercase & lowercase will work.



-- 
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@arrow.apache.org

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


[GitHub] [arrow-datafusion-python] simicd commented on a diff in pull request #258: docs: Example of calling Python UDF & UDAF in SQL

Posted by "simicd (via GitHub)" <gi...@apache.org>.
simicd commented on code in PR #258:
URL: https://github.com/apache/arrow-datafusion-python/pull/258#discussion_r1125562637


##########
examples/sql-using-python-udaf.py:
##########
@@ -0,0 +1,91 @@
+# 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.
+
+from datafusion import udaf, SessionContext, Accumulator
+import pyarrow as pa
+
+
+# Define a user-defined aggregation function (UDAF)
+class MyAccumulator(Accumulator):
+    """
+    Interface of a user-defined accumulation.
+    """
+
+    def __init__(self):
+        self._sum = pa.scalar(0.0)
+
+    def update(self, values: pa.Array) -> None:
+        # not nice since pyarrow scalars can't be summed yet. This breaks on `None`
+        self._sum = pa.scalar(
+            self._sum.as_py() + pa.compute.sum(values).as_py()
+        )
+
+    def merge(self, states: pa.Array) -> None:
+        # not nice since pyarrow scalars can't be summed yet. This breaks on `None`
+        self._sum = pa.scalar(
+            self._sum.as_py() + pa.compute.sum(states).as_py()
+        )
+
+    def state(self) -> pa.Array:
+        return pa.array([self._sum.as_py()])
+
+    def evaluate(self) -> pa.Scalar:
+        return self._sum
+
+
+my_udaf = udaf(
+    MyAccumulator,
+    pa.float64(),
+    pa.float64(),
+    [pa.float64()],
+    "stable",
+    # This will be the name of the UDAF in SQL
+    # If not specified it will by default the same as accumulator class name
+    # name="my_accumulator",
+)
+
+# Create a context
+ctx = SessionContext()
+
+# Create a datafusion DataFrame from a Python dictionary
+source_df = ctx.from_pydict({"a": [1, 1, 3], "b": [4, 5, 6]})
+# Dataframe:
+# +---+---+
+# | a | b |
+# +---+---+
+# | 1 | 4 |
+# | 1 | 5 |
+# | 3 | 6 |
+# +---+---+
+
+# Register UDF for use in SQL
+ctx.register_udaf(my_udaf)
+
+# Query the DataFrame using SQL
+table_name = ctx.catalog().database().names().pop()
+result_df = ctx.sql(
+    f"select a, my_accumulator(b) as b_aggregated from {table_name} group by a order by a"
+)

Review Comment:
   Here it would be nice if the table name can be set in the `from...` context functions so table_name is known, have created ticket #259 as follow-up task 



-- 
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@arrow.apache.org

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


[GitHub] [arrow-datafusion-python] simicd commented on a diff in pull request #258: docs: Example of calling Python UDF & UDAF in SQL

Posted by "simicd (via GitHub)" <gi...@apache.org>.
simicd commented on code in PR #258:
URL: https://github.com/apache/arrow-datafusion-python/pull/258#discussion_r1125560690


##########
datafusion/__init__.py:
##########
@@ -190,7 +190,7 @@ def udaf(accum, input_type, return_type, state_type, volatility, name=None):
             "`accum` must implement the abstract base class Accumulator"
         )
     if name is None:
-        name = accum.__qualname__
+        name = accum.__qualname__.lower()

Review Comment:
   Previously calling the UDAF in SQL would fail if `name` is not specified (i.e. both `MyAccumulator(b)` and `myaccumulator(b)` would fail when running e.g. `result_df = ctx.sql(f"select a, myaccumulator(b) as b_aggregated from {table_name}")` ). With this change both the uppercase & lowercase variant will work.



-- 
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@arrow.apache.org

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