How can you trigger an action operation in PySpark?
Instruction: Explain what an action operation is in PySpark and provide examples of how to trigger one.
Updated
An action asks Spark to produce a result or write output from a lazy transformation plan. Examples include count(), collect(), take(n), show() and a DataFrame writer's save operation.
For an existing SparkSession named spark:
from pyspark.sql import functions as F
logs = spark.createDataFrame([
(1, "INFO", "started"), (2, "ERROR", "timeout"),
(3, "ERROR", "unavailable"),
], "id int, level string, message string")
errors = logs.filter(F.col("level") == "ERROR")
assert errors.count() == 2
assert errors.orderBy("id").take(1)[0].message == "timeout"
filter describes the selected rows; the two actions request a count and a preview. They may execute work separately. Persist only if measured reuse justifies it; adding actions everywhere can repeatedly scan and shuffle the data.
collect() returns all result rows to the driver, so reserve it for bounded results. take(n) bounds the number of returned rows, not their byte size or necessarily the amount of upstream work. A global aggregate or sort may still process substantial data before returning a small result. A preview is not a representative random sample and does not validate all rows.
Writes execute work too, but destination commit, retry and idempotency behavior depends on the sink. Laziness does not make external side effects exactly once. RDD actions, DataFrame take