I have two files. functions.py has a function and creates a pyspark udf from that function. main.py attempts to import the udf. However, main.py seems to have trouble accessing the function in functions.py.
functions.py:
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
def do_something(x):
return x + 'hello'
sample_udf = udf(lambda x: do_something(x), StringType())
main.py:
from functions import sample_udf, do_something
df = spark.read.load(file)
df.withColumn("sample",sample_udf(col("text")))
This results in an error:
17/10/03 19:35:29 WARN TaskSetManager: Lost task 0.0 in stage 3.0 (TID 6, ip-10-223-181-5.ec2.internal, executor 3): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/usr/lib/spark/python/pyspark/worker.py", line 164, in main
func, profiler, deserializer, serializer = read_udfs(pickleSer, infile)
File "/usr/lib/spark/python/pyspark/worker.py", line 93, in read_udfs
arg_offsets, udf = read_single_udf(pickleSer, infile)
File "/usr/lib/spark/python/pyspark/worker.py", line 79, in read_single_udf
f, return_type = read_command(pickleSer, infile)
File "/usr/lib/spark/python/pyspark/worker.py", line 55, in read_command
command = serializer._read_with_length(file)
File "/usr/lib/spark/python/pyspark/serializers.py", line 169, in _read_with_length
return self.loads(obj)
File "/usr/lib/spark/python/pyspark/serializers.py", line 454, in loads
return pickle.loads(obj)
AttributeError: 'module' object has no attribute 'do_something'
If I bypass the do_something function and just put it inside the udf, eg: udf(lambda x: x + ' hello', StringType()), the UDF imports fine - but my function is a little longer and it would be nice to have it encapsulated in a separate function. What's the correct way to achieve this?