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

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
""")

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()
sales
sale_idstore_idqtyrevenue
1101220
21021296
3101115
41031080
5102327
610315105
7101436
810219

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()

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.