Moving Logic to the JVM
Most production UDFs are a few lines: a branch on a number, a string cleanup, a date parse, a lookup in a small dict. Spark has a built-in function for each, and a built-in runs inside the JVM on Spark's own row format, so a rewrite takes the Python workers out of the job and the socket and pickling go with them. These are the patterns you will meet most often.
| Inside the UDF | Built-in replacement |
|---|---|
| `if`/`elif` chain on a value | `F.when(...).when(...).otherwise(...)` |
| `s.strip().lower()` | `F.lower(F.trim(c))` |
| `re.sub(pattern, "", s)` | `F.regexp_replace(c, pattern, "")` |
| `re.search(pattern, s).group(1)` | `F.regexp_extract(c, pattern, 1)` |
| `datetime.strptime(s, "%Y-%m-%d").date()` | `F.to_date(c, "yyyy-MM-dd")` |
| `json.loads(s)["user"]["id"]` | `F.get_json_object(c, "$.user.id")` |
| `LOOKUP.get(code)` on a small dict | A broadcast join to a small lookup DataFrame |
| `[x * 2 for x in xs]` | `F.transform(c, lambda x: x * 2)` |
| `v if v is not None else 0` | `F.coalesce(c, F.lit(0))` |
The lambda passed to F.transform is called once, on the driver, with column placeholders to build an expression. It never runs per row and never crosses the border.
A worked rewrite
This UDF sorts products into price tiers and keeps a missing price missing:
def price_tier(price):
if price is None:
return None
if price < 20:
return "budget"
if price < 100:
return "mid"
return "premium"
tier_udf = F.udf(price_tier, "string")
tiered = products.withColumn("price_tier", tier_udf("price"))The translation is mechanical, with a single trap. F.when treats a comparison against null as false, so a chain ending in .otherwise("premium") would call every unpriced product premium. Spell out the last condition instead and leave otherwise off: a row that matches no branch gets null, which is what price_tier(None) returned.
tier = (
F.when(F.col("price") < 20, "budget")
.when(F.col("price") < 100, "mid")
.when(F.col("price") >= 100, "premium")
)
tiered = products.withColumn("price_tier", tier)Run the built-in version on the practice data. The cell drops unpriced products before grouping, so every group has a tier to show.
The animation plays the same chain over 8 products in 2 partitions. The tier is computed inside each map task, on rows already there, before the shuffle write for the groupBy. The aggregation's shuffle is the only data that moves; with the UDF, every row would also have gone to a Python worker and back inside each map task.
from pyspark.sql import functions as F
tier = (
F.when(F.col("price") < 20, "budget")
.when(F.col("price") < 100, "mid")
.when(F.col("price") >= 100, "premium")
)
products.withColumn("price_tier", tier).groupBy("price_tier").count().collect()| product_id | product_name | price |
|---|---|---|
| 1 | Cable | 9.5 |
| 2 | Mouse | 24 |
| 3 | Keyboard | 79 |
| 4 | Monitor | 219 |
| 5 | Charger | 15 |
| 6 | Headset | 129 |
| 7 | Webcam | 64 |
| 8 | Dock | 189 |
Where a rewrite changes the answer
Python and Spark agree on most operations and disagree on a few that turn up in real UDFs. Check these before shipping a rewrite.
| Case | Python in a UDF | Spark built-in |
|---|---|---|
| Rounding 2.5 | `round(2.5)` gives 2, halves to even | `F.round` gives 3.0, halves up; `F.bround` gives 2.0 |
| Trimming a tab | `"\tsku".strip()` removes the tab | `F.trim` removes spaces only, so the tab stays |
| Title case of `o'neil` | `.title()` gives `O'Neil` | `F.initcap` gives `O'neil` |
| Casting `12a` to an integer | `int("12a")` raises and fails the task | `.cast("int")` gives null when ANSI mode is off, the default before Spark 4.0 |
To prove a rewrite, run both versions on the same sample and compare rows in both directions. exceptAll keeps duplicates, so a row that appears twice on one side and once on the other is caught, and since it reads every column, the UDF cannot be pruned away.
sample = products.sample(fraction=0.01, seed=7)
old = sample.withColumn("price_tier", tier_udf("price"))
new = sample.withColumn("price_tier", tier)
assert old.exceptAll(new).count() == 0
assert new.exceptAll(old).count() == 0A UDF returns round(amount), and finance reconciles against its output. You rewrite it as F.round("amount"), and an exceptAll check finds rows that differ, all with amounts ending in .5. What fixes the rewrite?
- Cast amount to a string before rounding, so both versions see identical digits
- Use F.bround("amount"), which rounds halves to even as Python's round does
- Keep F.round and add .otherwise(0), because the differing rows hold nulls
- Turn off worker reuse, so Python rounds with the same rule the JVM uses
About this lesson
This section is part of the UDFs and Serialization: Intermediate 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.