Intermediatecoding Verified ~8 min
In PySpark, find the top N most frequent words in a large text file using the DataFrame API.
Source: Spark cluster mode overview
Quick answer
Read lines with spark.read.text, lowercase and split on r"\W+", explode into words, filter out empty strings, groupBy("word").count(), then orderBy(desc("count"), "word").limit(n). The groupBy is the only shuffle, and the top-N is merged without collecting all words to the driver.
Solution
main.py
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("top-words").getOrCreate()
def top_words(path: str, n: int = 10):
lines = spark.read.text(path) # one column: value
words = (lines
.select(F.explode(F.split(F.lower(F.col("value")), r"\W+")).alias("word"))
.filter(F.col("word") != "")) # split can yield empty strings
return (words.groupBy("word").count()
.orderBy(F.desc("count"), F.col("word")) # ties broken alphabetically
.limit(n))
top_words("/data/books/*.txt", 5).show()
Notes on each step:
r"\W+"is a raw string, so Python does not treat\Was an escape. It splits on any run of non-word characters (punctuation, spaces). A line that starts or ends with punctuation produces an empty string, hence the filter.- Spark uses Java regex, where
\Wmeans "not[a-zA-Z_0-9]". Underscores and digits count as word characters, but accented or non-English letters would be treated as separators. Use a different pattern such as[^\p{L}\p{N}']+if you need Unicode letters or want to keep apostrophes. explodeturns each array element into its own row.
How Spark executes it
Rendering diagram…
- Narrow stage: read, lower, split, explode, filter, and a partial aggregate (map-side) per partition.
- One shuffle by
wordfor the final counts. orderBy(...).limit(n)is planned as aTakeOrderedAndProject: each partition keeps its topn, and only those small candidate lists are merged. Spark does not sort the full word list and does notcollect()all words to the driver.
Complexity
- Time: O(W) to scan W words, plus sorting only distinct-word candidates per partition.
- Shuffle size: proportional to distinct words per partition, not total words (thanks to the partial aggregate).
- Memory: hash aggregate per task; the driver only holds
nrows.
Edge cases
- Ties at position
n: the second sort keywordmakes the result deterministic. - Case and punctuation: lowercasing merges "The" and "the".
- For stop words, filter with
isinor an anti-join before counting.
Animated explanation
- 1read.textone row per line
- 2split + explodeone row per word
- 3filterdrop empty strings
- 4groupBy + countthe only shuffle
- 5orderBy + limit(n)top N per partition, then merged
See the concept: Spark shufflegroupBy moves every record to the partition that owns its key
Spark shuffle: groupBy(key)
key A key B key C
Input partition 0
ACBA
Input partition 1
BBCA
Input partition 2
CABC
Stage 1: narrow transformations run in place
Key points
explode(split(lower(value), r"\W+"))turns lines into one row per word.- Filter out empty strings produced by leading or trailing separators.
groupBy("word").count()is the only shuffle, with a map-side partial aggregate.orderBy(desc("count"), "word").limit(n)gets the top N deterministically with a per-partition top-N merge.- Never
collect()all words to the driver.
Common mistakes
- Using a non-raw string "\W+", which is an invalid or fragile escape in Python.
- Forgetting to filter empty strings, so "" appears as a word.
- Not lowercasing, so "Spark" and "spark" are counted separately.
- Ordering only by count, leaving ties in random order.
- Collecting all words to the driver and counting in Python.
Prerequisites
- DataFrame basics
- Spark functions
explodeandsplit - Shuffle and aggregation
Best practices
- Include a second sort key for deterministic results.
- Check
explain()for one Exchange and a TakeOrderedAndProject. - Remove stop words and normalise Unicode if the text is multilingual.
- Use
spark.read.textrather than RDDs so Catalyst optimises the plan.
Likely follow-ups
- How would you write the same solution with the RDD API and reduceByKey?
- What is the difference between
orderBy().limit(n)andsortfollowed bycollect()? - How would you remove stop words efficiently?
- How does Spark avoid sorting all words for a top-N query?
- How would you count words in a streaming source?