Reviewed by Aditya Kumar · Last reviewed 2026-03-24
To count word occurrences in a text file using Spark, the standard approach leverages the PySpark DataFrame API to read the file, tokenize lines into words, and then aggregate these words. This method…
This medium-level Spark/Big Data question appears frequently in data engineering interviews at companies like Altimetrik, Infosys. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, python, spark) will help you answer variations of this question confidently.
Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.
To count word occurrences in a text file using Spark, the standard approach leverages the PySpark DataFrame API to read the file, tokenize lines into words, and then aggregate these words. This method is efficient and scalable for large datasets.
The process begins by reading the text file, where each line becomes a single row in a DataFrame. The F.split(F.col("value"), "\\s+") function then transforms each line into an array of words, using whitespace as a delimiter. Crucially, F.explode() flattens this array, creating a new row for each word, which is essential for subsequent aggregation. Finally, groupBy("word").count() groups all identical words together and counts their occurrences. This sequence of transformations is optimized by Spark's Catalyst optimizer, which builds an efficient execution plan (DAG) to distribute the work across the cluster.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# Initialize Spark Session
spark = SparkSession.builder.appName("WordCount").getOrCreate()
# Read the text file into a DataFrame
df = spark.read.text("path/to/file.txt")
# Split lines into words, explode the array, and count
word_counts = df.select(F.explode(F.split(F.col("value"), "\\s+")).alias("word")) \
.groupBy("word") \
.count()
# Show results (or write to storage)
word_counts.show()
# Stop Spark Session
spark.stop()
For large files, Spark partitions are critical for parallelism; spark.read.text typically creates partitions based on HDFS block sizes. The groupBy operation is a wide transformation that triggers a shuffle, moving data across the network to group identical keys. This is the most expensive part of the operation. To mitigate performance issues:
* Data Skew: If certain words (e.g., "the", "a") are extremely common, they can lead to data skew, causing a few tasks to process disproportionately more data and become bottlenecks. Repartitioning by key or using salting techniques can help.
* Shuffle Optimization: While the DataFrame API often optimizes shuffles, understanding the underlying reduceByKey semantics (available in RDDs) reveals how partial aggregation (combiner pattern) can reduce the amount of data shuffled. Spark's optimizer often applies similar techniques implicitly.
* Resource Tuning: Adjust spark.sql.shuffle.partitions and executor memory settings to match cluster resources and data volume.
In the interview, also mention the importance of monitoring Spark UI to identify shuffle bottlenecks and data skew, and how this fundamental problem illustrates core distributed computing concepts.
Red Flag: Using split(" ") and forgetting empty strings or multiple spaces. Pro-Move: 'I use regex split for whitespace, filter out empty strings, and repartition before groupBy when word distribution is skewed.'
Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.
According to DataEngPrep.tech, this is one of the most frequently asked Spark/Big Data interview questions, reported at 2 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.