Reduce and aggregate actions help you combine many data points into a single summary value. This makes it easier to understand big data by getting totals, averages, or other summaries.
Reduce and aggregate actions in Apache Spark
rdd.reduce(func) rdd.aggregate(zeroValue, seqOp, combOp)
reduce combines all elements using a function that takes two inputs and returns one output.
aggregate is more flexible: it uses a starting value, a function to combine data within partitions, and another to combine results across partitions.
reduce.numbers = sc.parallelize([1, 2, 3, 4]) sum = numbers.reduce(lambda a, b: a + b)
aggregate with a zero start and two functions.numbers = sc.parallelize([1, 2, 3, 4]) zero = 0 seqOp = (lambda acc, x: acc + x) combOp = (lambda acc1, acc2: acc1 + acc2) sum = numbers.aggregate(zero, seqOp, combOp)
aggregateByKey after mapping to (word, 1) pairs.words = sc.parallelize(['apple', 'banana', 'apple']) word_pairs = words.map(lambda w: (w, 1)) count = word_pairs.aggregateByKey(0, lambda acc, v: acc + v, lambda acc1, acc2: acc1 + acc2).collect()
This program creates a list of numbers as an RDD. It then finds the sum of all numbers using both reduce and aggregate. Both methods give the same result.
from pyspark.sql import SparkSession spark = SparkSession.builder.master('local[*]').appName('ReduceAggregateExample').getOrCreate() sc = spark.sparkContext # Create an RDD of numbers numbers = sc.parallelize([10, 20, 30, 40, 50]) # Use reduce to find the sum sum_reduce = numbers.reduce(lambda a, b: a + b) # Use aggregate to find the sum with zero start zero = 0 seqOp = lambda acc, x: acc + x combOp = lambda acc1, acc2: acc1 + acc2 sum_aggregate = numbers.aggregate(zero, seqOp, combOp) print(f"Sum using reduce: {sum_reduce}") print(f"Sum using aggregate: {sum_aggregate}") spark.stop()
reduce requires a function that combines two elements into one.
aggregate is useful when you want to start from a specific value or do more complex combining.
Both actions trigger computation in Spark and return results to the driver program.
Reduce and aggregate actions combine many data points into one summary value.
Use reduce for simple combining with one function.
Use aggregate for more control with a starting value and two functions.
Practice
What does the reduce action do in Apache Spark?
Solution
Step 1: Understand the purpose of reduce
Thereduceaction combines all elements of an RDD by applying a function that takes two elements and returns one, repeating until one result remains.Step 2: Compare with other actions
Filtering selects elements, mapping transforms elements, and sorting orders elements, none of which combine all elements into one.Final Answer:
It combines all elements of an RDD using a specified function to produce a single result. -> Option CQuick Check:
Reduce = combine all elements [OK]
- Confusing reduce with filter or map actions
- Thinking reduce sorts data
- Assuming reduce returns an RDD instead of a single value
Which of the following is the correct syntax to use reduce on an RDD named rdd to sum all elements?
rdd.reduce(_____)
Solution
Step 1: Identify the function signature for reduce
The function passed toreducemust take two arguments and return one combined result.Step 2: Choose the function that sums two elements
Onlylambda x, y: x + ytakes two arguments and sums them, suitable for summing all elements.Final Answer:
lambda x, y: x + y -> Option BQuick Check:
Reduce needs two-arg function for combining [OK]
- Using single-argument lambda instead of two-argument
- Using multiplication when sum is needed
- Passing a function that does not return a single value
Given the following code, what is the output?
rdd = sc.parallelize([1, 2, 3, 4]) result = rdd.aggregate(0, (lambda acc, x: acc + x), (lambda acc1, acc2: acc1 + acc2)) print(result)
Solution
Step 1: Understand aggregate parameters
The initial value is 0. The first lambda adds each element to the accumulator. The second lambda combines accumulators from partitions by summing.Step 2: Calculate the sum of elements
Sum of [1, 2, 3, 4] is 10. The aggregate returns this sum.Final Answer:
10 -> Option DQuick Check:
Aggregate sums elements starting at 0 [OK]
- Confusing aggregate with reduce output
- Ignoring initial zero value
- Expecting product instead of sum
Identify the error in this Spark code snippet:
rdd = sc.parallelize([1, 2, 3]) result = rdd.reduce(lambda x: x + 1) print(result)
Solution
Step 1: Check lambda function signature for reduce
Thereducefunction requires a function with two parameters to combine elements pairwise.Step 2: Identify the incorrect lambda
The lambdalambda x: x + 1takes only one argument, causing a runtime error.Final Answer:
The lambda function should take two arguments, not one. -> Option AQuick Check:
Reduce needs two-argument function [OK]
- Using single-argument lambda in reduce
- Assuming reduce works on empty RDD without error
- Misreading print syntax in Python 3
You have an RDD of tuples representing (category, value):
data = [("A", 2), ("B", 3), ("A", 5), ("B", 7), ("C", 1)]
rdd = sc.parallelize(data)Which approach correctly uses aggregateByKey to find the sum of values per category?
Solution
Step 1: Understand aggregateByKey usage
aggregateByKeystarts with zero per key, adds values with first lambda, then merges partitions with second lambda.Step 2: Check each option
rdd.aggregateByKey(0, lambda acc, v: acc + v, lambda acc1, acc2: acc1 + acc2).collect() correctly usesaggregateByKeywith zero start and sum functions per key. rdd.reduce(lambda x, y: x + y).collect() is invalid syntax for key-value RDD. rdd.aggregate(0, lambda acc, x: acc + x[1], lambda acc1, acc2: acc1 + acc2).collect() usesaggregateon whole RDD, not per key. rdd.mapValues(lambda v: v).reduceByKey(lambda x, y: x * y).collect() multiplies values, not sums.Final Answer:
rdd.aggregateByKey(0, lambda acc, v: acc + v, lambda acc1, acc2: acc1 + acc2).collect() -> Option AQuick Check:
aggregateByKey sums values per key [OK]
- Using aggregate instead of aggregateByKey for key-value RDD
- Using reduce without key awareness
- Multiplying instead of summing values
Ready to prove it?
Pass the test and this pattern moves unknown
