Skip to main content
Jack_sparrow
Silver ⭐️⭐️
Sep 8, 2025 12:04 PM UTC
Solved

How to run spark df.write inside UDF called in rdd.foreach or rdd.foreachpartition

How to run spark df.write inside UDF called in rdd.foreach or rdd.foreachpartition

I.e. spark session object inside executor.

vafs
vafsAnswer
Gold ⭐️⭐️⭐️
Sep 8, 2025 8:12 PM UTC

Hello @Jack_sparrow, 

Glad to see you on the Community. 

As far as I know, df.write is not possible to be used on an rdd.foreach or rdd.foreachpartition. 
The reason is because df.write is a driver-side action, it triggers a Spark job.
rdd.foreach or rdd.foreachpartition are executors, and executors cannot trigger jobs.

Check these references: 
https://stackoverflow.com/questions/46964250/nullpointerexception-creating-dataset-dataframe-inside-foreachpartition-foreach
https://stackoverflow.com/questions/46964250/nullpointerexception-creating-dataset-dataframe-inside-foreachpartition-foreach
https://sparkbyexamples.com/spark/spark-foreachpartition-vs-foreach-explained

The option that looks like it works for you is this: 

df.write.partitionBy

Something like this: 

df.write.partitionBy("someColumn").parquet("/path/out")

 

3 replies

VidyaSargur
Community Manager
Community Manager
Sep 8, 2025 3:32 PM UTC

@Jack_sparrow, Welcome to our community! To help you get the best possible answer, I have tagged in our Spark experts @haridjh and @vafs, who may be able to assist you further.

Please feel free to provide any additional information or details about your query. We hope that you will find a satisfactory solution to your question.

Translate
Regards, Vidya Sargur Madabhushi| Senior Community Manager | Was your question answered? Make sure to mark the answer as the Best Answer. If you find a reply useful, say thanks by clicking on the thumbs up button.
vafs
Gold ⭐️⭐️⭐️
vafsAnswer
Gold ⭐️⭐️⭐️
Sep 8, 2025 8:12 PM UTC

Hello @Jack_sparrow, 

Glad to see you on the Community. 

As far as I know, df.write is not possible to be used on an rdd.foreach or rdd.foreachpartition. 
The reason is because df.write is a driver-side action, it triggers a Spark job.
rdd.foreach or rdd.foreachpartition are executors, and executors cannot trigger jobs.

Check these references: 
https://stackoverflow.com/questions/46964250/nullpointerexception-creating-dataset-dataframe-inside-foreachpartition-foreach
https://stackoverflow.com/questions/46964250/nullpointerexception-creating-dataset-dataframe-inside-foreachpartition-foreach
https://sparkbyexamples.com/spark/spark-foreachpartition-vs-foreach-explained

The option that looks like it works for you is this: 

df.write.partitionBy

Something like this: 

df.write.partitionBy("someColumn").parquet("/path/out")

 

Translate
Jack_sparrow
Silver ⭐️⭐️
Sep 9, 2025 4:01 AM UTC

Thank you for the response.

Translate