Registering a UDF
A Python function Spark can call
A user-defined function, or UDF, is a Python function that Spark applies to a column row by row. Spark's built-in column functions cover most transformations, but sometimes the rule you need exists only as Python you wrote yourself. Once you wrap it as a UDF, the function is a column expression, so select and withColumn take it the same way they take a built-in, and so does where.
Every UDF takes 3 steps
- Write a plain Python function that takes column values as arguments and returns 1 value.
- Wrap it with F.udf() and declare the type of the value it returns.
- Call it on columns in a DataFrame expression, or register it by name to call it from SQL.
The running example sorts products into price bands. A price under 50 is budget, a price under 200 is mid, and anything higher is premium.
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
def price_band(price):
if price < 50:
return "budget"
if price < 200:
return "mid"
return "premium"
price_band_udf = F.udf(price_band, StringType())
products = spark.table("products")
banded = products.withColumn("band", price_band_udf(F.col("price")))The second argument to F.udf() is the return type. Spark never looks at what your Python function returns to work out the column's type: the schema of banded lists band as a string because the code declared it. Leave the argument out and Spark assumes StringType. The type can also be a short string like "string" or "double", and "int" works too.
This version fails on a product with no price. The Nulls and Types section shows why and fixes it.
Calling it from SQL
F.udf() returns an object for DataFrame code and nothing more. A SQL query finds functions by name in the session's function registry, and that object was never added there. spark.udf.register() adds the function under a name you choose and also returns a UDF for DataFrame code, so 1 registration serves both.
spark.udf.register("price_band", price_band, StringType())
priced = spark.sql("""
SELECT
product_name,
price,
price_band(price) AS band
FROM products
WHERE price IS NOT NULL
""")- Wrapped with F.udf()
- Returns a UDF for DataFrame expressions
- Invisible to spark.sql()
- Lives in a Python variable
- Registered with spark.udf.register()
- Adds a name to the session's function registry
- Callable from spark.sql() by that name
- Also returns a UDF for DataFrame expressions
- Lasts until the SparkSession stops
A teammate wraps clean_name and then queries it from SQL. What happens when the spark.sql line runs?
clean_name_udf = F.udf(clean_name, "string")
names = spark.sql("""
SELECT
clean_name(product_name) AS name
FROM products
""")- The query runs, because SQL can call any Python function in scope by its def name
- The query is accepted, and the missing function raises an error only when an action runs
- spark.sql() raises an error right away, because no function named clean_name is registered
- The query runs and returns name as a string column, the type declared in F.udf()
Where the function runs
Applying a UDF is a narrow transformation. Each output row depends on 1 input row, so Spark calls the function inside the task that reads the partition, on the executor holding it, and no rows move between executors. The animation labels 8 sales bulk when the quantity is 10 or more and single otherwise, then totals revenue per label.
from pyspark.sql import functions as F
@F.udf(returnType="string")
def size_band(qty):
if qty >= 10:
return "bulk"
return "single"
banded = sales.withColumn("band", size_band(F.col("qty")))
totals = banded.groupBy("band").agg(F.sum("revenue").alias("revenue"))
totals.collect()| sale_id | store_id | qty | revenue |
|---|---|---|---|
| 1 | 101 | 2 | 20 |
| 2 | 102 | 12 | 96 |
| 3 | 101 | 1 | 15 |
| 4 | 103 | 10 | 80 |
| 5 | 102 | 3 | 27 |
| 6 | 103 | 15 | 105 |
| 7 | 101 | 4 | 36 |
| 8 | 102 | 1 | 9 |
The labels appear inside the 2 read tasks, before any row leaves its partition. The only shuffle belongs to groupBy, which brings each label's rows together for the final sum. The driver collects 2 rows: bulk with revenue 281.0 and single with 107.0. A UDF adds work to every task it runs in and adds no shuffle of its own, so you count the shuffles in a UDF job exactly as you would without it.
This job bands every priced product with price_band_udf and counts the products in each band. How many shuffles does Spark run for it?
banded = (
products
.where(F.col("price").isNotNull())
.withColumn("band", price_band_udf(F.col("price")))
)
counts = banded.groupBy("band").count()
counts.collect()- Two shuffles: one for the UDF to gather each price's rows, one for groupBy to gather each band
- No shuffle at all, because the UDF runs on the driver after collect() pulls every product there
- No shuffle, because a UDF and a groupBy both keep each row in the partition it was read from
- One shuffle, for groupBy, while the UDF labels rows inside the tasks that read each partition
About this lesson
This section is part of the UDFs and Serialization: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.