Using UDFs (User Defined Functions) in Apache Spark
📖 Scenario: You work at a retail company. You have sales data with product names and prices. You want to add a new column that shows the price category: 'Cheap' if price is less than 20, 'Moderate' if price is between 20 and 50, and 'Expensive' if price is above 50.
🎯 Goal: Create a Spark DataFrame with product data, define a User Defined Function (UDF) to categorize prices, apply it to add a new column, and display the result.
📋 What You'll Learn
Create a Spark DataFrame with exact product and price data
Define a UDF named price_category that categorizes prices
Use the UDF to add a new column category to the DataFrame
Show the final DataFrame with the new column
💡 Why This Matters
🌍 Real World
In real companies, UDFs help add custom logic to big data processing pipelines when built-in functions are not enough.
💼 Career
Knowing how to write and use UDFs is important for data engineers and data scientists working with Apache Spark to transform and analyze large datasets.
Progress0 / 4 steps
1
Create the initial Spark DataFrame
Create a Spark DataFrame called df with these exact rows: ("Pen", 10), ("Notebook", 25), ("Backpack", 60). Use columns named product and price.
Apache Spark
Hint
Use spark.createDataFrame with a list of tuples and specify column names.
2
Define the UDF function
Define a Python function called price_category that takes a single argument price and returns the string 'Cheap' if price is less than 20, 'Moderate' if price is between 20 and 50 (inclusive), and 'Expensive' if price is greater than 50.
Apache Spark
Hint
Use simple if-elif-else statements to return the correct category string.
3
Register the UDF and apply it to the DataFrame
Import udf and StringType from pyspark.sql.functions and pyspark.sql.types. Register the price_category function as a UDF named price_category_udf with return type StringType(). Use withColumn on df to add a new column called category by applying price_category_udf to the price column. Save the result back to df.
Apache Spark
Hint
Use udf(function, returnType) to register, then withColumn to add the new column.
4
Show the final DataFrame
Use print to display the result of df.show().
Apache Spark
Hint
Use df.show() inside a print statement to display the table.
Practice
(1/5)
1. What is the main purpose of a User Defined Function (UDF) in Apache Spark?
easy
A. To create new Spark sessions
B. To manage cluster resources
C. To optimize Spark SQL queries automatically
D. To apply custom logic to each row of a DataFrame
Solution
Step 1: Understand UDF role in Spark
A UDF lets you add your own logic to process each row in a DataFrame, beyond built-in functions.
Step 2: Compare options
The other options relate to Spark setup or optimization, not custom row logic.
Final Answer:
To apply custom logic to each row of a DataFrame -> Option D
Quick Check:
UDF = custom row logic [OK]
Hint: UDFs add your own row-wise logic in Spark [OK]
Common Mistakes:
Confusing UDFs with Spark session management
Thinking UDFs optimize queries automatically
Assuming UDFs manage cluster resources
2. Which of the following is the correct way to register a UDF in PySpark with a return type of IntegerType?
easy
A. spark.udf.register('my_udf', func, 'IntegerType')
B. spark.udf.register('my_udf', func)
C. spark.udf.register('my_udf', func, IntegerType())
D. spark.udf.create('my_udf', func, IntegerType())
Solution
Step 1: Recall UDF registration syntax
The correct method is spark.udf.register with function name, function, and return type as a DataType object.
Step 2: Evaluate options
spark.udf.register('my_udf', func, IntegerType()) uses IntegerType() correctly. spark.udf.register('my_udf', func) misses return type. spark.udf.create('my_udf', func, IntegerType()) uses a non-existent method. spark.udf.register('my_udf', func, 'int') uses a string instead of IntegerType().
Final Answer:
spark.udf.register('my_udf', func, IntegerType()) -> Option C
Quick Check:
Register UDF with return type object [OK]
Hint: Always specify return type as DataType object when registering UDF [OK]
Common Mistakes:
Omitting the return type parameter
Using incorrect method names like create
Passing return type as string instead of DataType
3. Given the following PySpark code, what will be the output of df.select('name', 'age_plus_one').show()?
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType
def add_one(age):
return age + 1
add_one_udf = udf(add_one, IntegerType())
df = spark.createDataFrame([('Alice', 30), ('Bob', 25)], ['name', 'age'])
df = df.withColumn('age_plus_one', add_one_udf('age'))
medium
A. [[Alice, 31], [Bob, 26]]
B. [[Alice, 30], [Bob, 25]]
C. Error: UDF missing return type
D. [[Alice, 1], [Bob, 1]]
Solution
Step 1: Understand UDF logic
The UDF adds 1 to the 'age' column values: 30 + 1 = 31, 25 + 1 = 26.
Step 2: Check DataFrame transformation
The new column 'age_plus_one' will have values 31 and 26 for Alice and Bob respectively.
Final Answer:
[[Alice, 31], [Bob, 26]] -> Option A
Quick Check:
age + 1 = 31, 26 [OK]
Hint: UDF applies function row-wise, transforming each value [OK]
Common Mistakes:
Forgetting to specify return type causing errors
Assuming original age remains unchanged
Confusing UDF output with input data
4. Identify the error in the following PySpark UDF code snippet:
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
def greet(name):
return 'Hello ' + name
greet_udf = udf(greet)
df = spark.createDataFrame([('John',), ('Jane',)], ['name'])
df = df.withColumn('greeting', greet_udf('name'))
df.show()
medium
A. UDF missing return type specification
B. Function greet has wrong parameter type
C. DataFrame creation syntax is incorrect
D. withColumn method is used incorrectly
Solution
Step 1: Check UDF registration
The UDF is created without specifying the return type, which is required.
Step 2: Verify other code parts
Function parameter and DataFrame creation are correct. withColumn usage is proper.
Final Answer:
UDF missing return type specification -> Option A
Quick Check:
Always specify return type when creating UDF [OK]
Hint: Always specify return type when defining UDF [OK]
Common Mistakes:
Omitting return type causes runtime errors
Assuming return type is optional
Misunderstanding function parameter types
5. You want to create a UDF that returns the length of a string column but safely handles null values by returning 0 instead of failing. Which of the following UDF definitions correctly implements this behavior?
hard
A. def safe_length(s):
return len(s)
safe_length_udf = udf(safe_length, IntegerType())
B. def safe_length(s):
if s is None:
return 0
else:
return len(s)
safe_length_udf = udf(safe_length, IntegerType())
C. def safe_length(s):
if s == '':
return 0
return len(s)
safe_length_udf = udf(safe_length, StringType())
D. def safe_length(s):
return s.length()
safe_length_udf = udf(safe_length, IntegerType())
Solution
Step 1: Handle null values safely
def safe_length(s):
if s is None:
return 0
else:
return len(s)
safe_length_udf = udf(safe_length, IntegerType()) checks if input is None and returns 0, preventing errors.
Step 2: Check return type and logic
def safe_length(s):
if s is None:
return 0
else:
return len(s)
safe_length_udf = udf(safe_length, IntegerType()) returns IntegerType and uses len(s) correctly. Others either miss null check or use wrong return type or method.
Final Answer:
def safe_length(s):
if s is None:
return 0
else:
return len(s)
safe_length_udf = udf(safe_length, IntegerType()) -> Option B
Quick Check:
Check nulls first, then return length [OK]
Hint: Check for None before calling len() in UDF [OK]
Common Mistakes:
Not handling None causing runtime errors
Returning wrong data type from UDF
Using string methods incorrectly in Python
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.