Skip to main content
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 \W as 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 \W means "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.
  • explode turns each array element into its own row.

How Spark executes it

Rendering diagram…
  1. Narrow stage: read, lower, split, explode, filter, and a partial aggregate (map-side) per partition.
  2. One shuffle by word for the final counts.
  3. orderBy(...).limit(n) is planned as a TakeOrderedAndProject: each partition keeps its top n, and only those small candidate lists are merged. Spark does not sort the full word list and does not collect() 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 n rows.

Edge cases

  • Ties at position n: the second sort key word makes the result deterministic.
  • Case and punctuation: lowercasing merges "The" and "the".
  • For stop words, filter with isin or an anti-join before counting.
Animated explanation
  1. 1read.textone row per line
  2. 2split + explodeone row per word
  3. 3filterdrop empty strings
  4. 4groupBy + countthe only shuffle
  5. 5orderBy + limit(n)top N per partition, then merged
The full word list never goes to the driver.
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

Before: each input partition holds a mix of keys. After the shuffle, all records with the same key live in one partition. That data movement over the network is what makes wide transformations expensive.

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 explode and split
  • 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.text rather 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) and sort followed by collect()?
  • 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?

References

Discussion