Built-Ins First

The same bands, without Python

The functions module, imported as F throughout this lesson, holds a few hundred column functions that run inside Spark's engine. The price bands use 2 of them, F.when and F.col. The chain then ends with the .otherwise method.

from pyspark.sql import functions as F

products = spark.table("products")

banded = products.withColumn(
    "band",
    F.when(F.col("price") < 50, "budget")
    .when(F.col("price") < 200, "mid")
    .otherwise("premium"),
)

For every product with a price, band holds the label the UDF produced. The work underneath differs: no Python function is called, and each comparison is an expression Catalyst can read and rewrite.

SQL gets the same rule with no registration step. CASE WHEN is the SQL form of F.when, and the built-ins in this section's table go by the same names in SQL queries.

SELECT
  product_name,
  CASE
    WHEN price < 50 THEN 'budget'
    WHEN price < 200 THEN 'mid'
    ELSE 'premium'
  END AS band
FROM products

Why the built-in wins

Spark keeps rows in memory in its own compact binary format. A built-in expression reads values straight out of that format. A Python UDF cannot. For every row, Spark has to turn the input values into Python objects before it can call your function, and whatever the function returns has to be turned back into the binary format. Turning in-memory values into bytes that another program can rebuild is called serialization, and rebuilding them is deserialization. On 10 rows the round trip is invisible. On 500 million rows it happens 500 million times.

Run 2 jobs that add the same band column to 200 million products. The first calls price_band_udf, and the second uses the F.when chain. The UDF body is 5 lines of comparisons. Why does the F.when job finish first?

Find the built-in before you write the function

Before writing a UDF, search the functions module for the operation you need. The table maps requests that often turn into UDFs onto the built-ins that cover them, using columns from the practice tables.

You want toBuilt-inExample
Lowercase and strip spaces`F.lower`, `F.trim``F.lower(F.trim("product_name"))`
Branch on a condition`F.when`, `.otherwise``F.when(F.col("price") < 50, "budget")`
Replace NULL with a default`F.coalesce``F.coalesce("region", F.lit("unknown"))`
Pull a match out of text`F.regexp_extract``F.regexp_extract("email", "@(.+)", 1)`
Collapse repeated spaces`F.regexp_replace``F.regexp_replace("search_term", " +", " ")`
Parse a date string`F.to_date``F.to_date("signup_date", "yyyy-MM-dd")`
Join strings with a separator`F.concat_ws``F.concat_ws(" ", "first_name", "last_name")`
Split text into an array`F.split``F.split("tags", ",")`

When no row of the table fits

Compose built-ins before giving up on them. F.trim(F.regexp_replace(F.lower("search_term"), " +", " ")) is 3 built-ins deep, and Catalyst reads every layer. Search the API reference by verb: extract and replace are good starts, and so are split and parse. Then search by the type you hold, whether string or date, array or map. A function in Spark's SQL function list with no wrapper in the module still runs as a built-in through F.expr("...").

The cell below cleans each product name and bands its price using built-ins only. Run it, then change the 200 boundary to 100 and run it again to see which products move from mid to premium. Each label matches what price_band returns for the same price.

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.