TECHNOLOGIESTieInn Technologies

Transformations, actions, and shuffles

Spark / PySpark · 12 questions

Short notes

Key idea

Transformations (filter, select, groupBy, join) describe new DataFrames lazily. Actions (count, show, collect, write) run them. A shuffle moves data between executors so rows with the same key meet; it's the most expensive part of most jobs.

Syntax

  • Narrow transformations: each output partition needs one input partition (filter, select, withColumn). No shuffle.
  • Wide transformations: need data from many partitions (groupBy, join, distinct, orderBy, repartition). Shuffle, and a new stage.
  • df.explain() prints the plan; Exchange means a shuffle.

Example

df.filter(...).withColumn(...).groupBy("city").sum("amount").show(): the filter and new column run together in stage 1; the groupBy shuffles rows by city into stage 2; show is the action that triggers it all.

Traps

  • Calling several actions on the same DataFrame recomputes it each time; cache it if reused.
  • Unneeded orderBy or distinct add shuffles.
  • Filter and select early so less data is shuffled.
  • count() for "debugging" inside a pipeline triggers extra full jobs.

Want the full lesson with step-by-step examples, a project and a certificate? Spark / PySpark course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Transformations, actions, and shuffles

  1. Question 1easy

    Which transformation causes a shuffle?

  2. Transformations, actions, and shuffles

  3. Question 2easy

    Which of these is an action?

  4. Transformations, actions, and shuffles

  5. Question 3medium

    Ignoring adaptive query execution, how many stages does this job have?

    (orders
        .filter(F.col("amount") > 0)
        .withColumn("year", F.year("order_date"))
        .groupBy("customer_id", "year")
        .agg(F.sum("amount").alias("spend"))
        .write.parquet("gs://out/spend/"))
  6. Transformations, actions, and shuffles

  7. Question 4medium

    In the output of df.explain(), which operator means a shuffle?

  8. Transformations, actions, and shuffles

  9. Question 5medium

    Why put filters before a join or groupBy where possible?

7 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.