A production ETL job is taking too long to run. You must analyze the execution plan, cache intermediate results that are reused multiple times, and partition the output by country to optimize downstream queries.
The processing pipeline will ingest the following local mock file structures (e.g. simulated as `dataset.csv`):
| id | user_id | action | country |
|---|---|---|---|
| 1 | 1001 | click | USA |
| 2 | 1002 | view | CAN |
| 3 | 1001 | purchase | USA |
| 4 | 1003 | click | GER |
| 5 | 1002 | click | CAN |
id,user_id,action,country 1,1001,click,USA 2,1002,view,CAN 3,1001,purchase,USA 4,1003,click,GER 5,1002,click,CAN
Copy this starter template to write the data transformation logic:
# starter.py - Optimize a Slow Spark Job
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
def optimize_pipeline():
spark = SparkSession.builder.appName("OptimizationLab").getOrCreate()
# TODO: Read dataset.csv, filter purchases, cache, partition by country, explain plan
pass
if __name__ == "__main__":
optimize_pipeline().cache() on the intermediate DataFrame. Caching keeps the computed records in executor memory, avoiding rebuilding the execution DAG when counting records and writing to Parquet.
clicks_df.write.mode("overwrite").partitionBy("country").parquet("optimized_output.parquet").
.explain() to display the execution plan in stdout.