Word Count with RDDs
The provided code uses a chain of transformations on an RDD to count the occurrences of every word in the words.txt file located in HDFS.
Step 1: Ingest Data (Action/Creation)
lines_rdd = sc.textFile("words.txt")
Method: sc.textFile() is an action (that initiates the reading) and a method of the SparkContext that creates the initial RDD.
Result: lines_rdd is an RDD wher each element is a single line from the words.txt file. The lines are partitioned across the cluster's worker nodes.
Step 2: Flatten Lines into Words (Transformation)
.flatMap(lambda line: line.split(" "))
Method: flatMap() is a transformation that applies a function to each element of the RDD and then "flattens" the result.
Function: line.split(" ") splits each line into a list of individual words using a space as a delimiter.
Result: The RDD is transformed from a collection of lines into a single, combined RDD of individual words.
Step 3: Map Words to Key-Value Pairs (Transformation)
.map(lambda word: (word, 1))
Method: map() is a simple transformation that applies a function to each element of the RDD, maintaining the one-to-one count.
Function: (word, 1) converts each word into a key-value pair, where the word is the key and 1 is the initial count/value.
Result: The RDD now looks like: [('the', 1), ('quick', 1), ('brown', 1), ('fox', 1), ('the', 1), ...]
Step 4: Aggregate Counts (Wide Transformation)
.reduceByKey(lambda a, b: a + b)
Method: reduceByKey() is a wide transformation (meaning it requires a shuffle of data). It groups all values associated with the same key and applies an aggregation function.
Function: lambda a, b: a + b specifies the aggregation: for any given word, it sums up all the associated 1 values.
Result: This is the core counting step. The RDD now contains the final word counts as key-value pairs: [('the', 2), ('quick', 1), ('brown', 1), ('fox', 1), ...]. This is saved in the counters RDD.
Step 5: Output Result (Action)
counters.collect()
Method: collect() is an action that triggers the entire chain of transformations (from textFile to reduceByKey) and brings the final result from the distributed Executors back to the Driver Program as a local list.
Result: The final output is a Python list containing the complete word counts.