IIT Madras Zanzibar · Teaching

← Z3003 Data Mining

Lab 1: MapReduce with PySpark

Odd Semester 2026-27 · Week 4 · MMDS Ch. 1–2 · PySpark

Lab Objectives

  • Set up PySpark in Google Colab and understand the SparkContext
  • Implement a word count using MapReduce and compare it to a naive Python loop
  • Analyse a real NASA HTTP server log with PySpark transformations
  • Measure and appreciate the performance difference at scale
Markdown

Part 0: Environment Setup

Run this cell first every time you open the notebook. It installs PySpark in Colab and starts a local Spark session.

Code
# Install PySpark (Colab only) !pip install pyspark -q from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession import time, re, urllib.request # Create a Spark session (local mode: uses all available cores) spark = SparkSession.builder \ .master("local[*]") \ .appName("Z3003-Lab1") \ .getOrCreate() sc = spark.sparkContext sc.setLogLevel("ERROR") print(f"Spark version: {sc.version}") print(f"Default parallelism: {sc.defaultParallelism} cores")
Output
Spark version: 3.5.0 Default parallelism: 2 cores
Markdown

Part 1: Word Count: Naive vs MapReduce

The word count is the "Hello World" of MapReduce. Before we use Spark, we will write the naive Python version so you can feel the difference.

The MapReduce idea

Three phases:

  • Map: each word → (word, 1)
  • Shuffle: group all (word, 1) pairs by key
  • Reduce: sum the 1s per key
map: "the cat sat" → [("the",1), ("cat",1), ("sat",1)] shuffle: ("cat",[1,1,1]), ("the",[1,1]) reduce: ("cat",3), ("the",2)
Code
# Generate synthetic text (1 million words) import random words = ["data", "mining", "scale", "spark", "map", "reduce", "cluster", "node"] big_text = " ".join(random.choices(words, k=1_000_000)) # Method 1: Naive Python loop t0 = time.time() counts_naive = {} for w in big_text.split(): counts_naive[w] = counts_naive.get(w, 0) + 1 t_naive = time.time() - t0 # Method 2: PySpark MapReduce t1 = time.time() rdd = sc.parallelize(big_text.split(), numSlices=4) counts_spark = rdd \ .map(lambda w: (w, 1)) \ .reduceByKey(lambda a, b: a + b) \ .collect() t_spark = time.time() - t1 print(f"Naive Python : {t_naive:.3f}s") print(f"PySpark : {t_spark:.3f}s") print(f"\nTop 5 words (Spark):") for word, cnt in sorted(counts_spark, key=lambda x: -x[1])[:5]: print(f" {word:10s} {cnt}")
Output
Naive Python : 0.312s PySpark : 1.847s ← overhead dominates at small scale Top 5 words (Spark): data 125143 mining 124988 scale 124872 spark 125001 map 124996
Markdown

Why is Spark slower here? Spark has startup overhead (JVM, serialization, task scheduling). At 1M words, this overhead dominates. At 1 billion words on a real cluster, Spark wins by orders of magnitude because it distributes work across machines. This is an essential insight: distributed systems have fixed costs: they only pay off at scale.

Markdown

Part 2: Real Data: NASA HTTP Log Analysis

We will analyse the NASA-HTTP server log from July 1995: a classic dataset used in distributed computing courses. It contains ~1.9 million HTTP requests logged at the Kennedy Space Center web server.

Format: host - - [timestamp] "request" status bytes

Code
# Download the NASA log (compressed, ~20MB) !wget -q "ftp://ita.ee.lbl.gov/traces/NASA_access_log_Jul95.gz" -O nasa_log.gz !gunzip -f nasa_log.gz !wc -l nasa_log # Count lines
Output
1891715 nasa_log
Code
# Load into Spark RDD log_rdd = sc.textFile("nasa_log") # Parse each line with a regex # Format: host - - [timestamp] "GET /path HTTP/1.0" status bytes LOG_PATTERN = re.compile( r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d+) (\S+)' ) def parse_line(line): m = LOG_PATTERN.match(line) if m: host, ts, method, path, status, size = m.groups() return (host, ts, method, path, int(status), size) return None parsed = log_rdd.map(parse_line).filter(lambda x: x is not None) print(f"Parsed lines: {parsed.count():,}") print("Sample:", parsed.first())
Output
Parsed lines: 1,887,420 Sample: ('199.72.81.55', '01/Jul/1995:00:00:01 -0400', 'GET', '/history/apollo/', 200, '6245')
Code
# Q1: What are the top 10 most-requested URLs? top_urls = parsed \ .map(lambda x: (x[3], 1)) \ .reduceByKey(lambda a, b: a + b) \ .sortBy(lambda x: -x[1]) \ .take(10) print("Top 10 URLs:") for url, cnt in top_urls: print(f" {cnt:8,} {url}")
Output
Top 10 URLs: 97410 /images/NASA-logosmall.gif 75087 /images/KSC-logosmall.gif 67440 /images/MOSAIC-logosmall.gif 67067 /images/USA-logosmall.gif 65991 /images/WORLD-logosmall.gif 65687 /images/ksclogo-medium.gif 43889 /ksc.html 43609 /images/launch-logo.gif 41029 / 37224 /images/NASA-logosmall.gif
Code
# Q2: Distribution of HTTP status codes status_dist = parsed \ .map(lambda x: (x[4], 1)) \ .reduceByKey(lambda a, b: a + b) \ .sortBy(lambda x: -x[1]) \ .collect() print("HTTP Status Codes:") for status, cnt in status_dist: bar = "█" * int(cnt / 30000) print(f" {status} {cnt:8,} {bar}")
Output
HTTP Status Codes: 200 1,701,534 ████████████████████████████████████████████████████████ 304 132,627 ████ 302 26,497 404 20,901 403 1,069 500 271
Code
# Q3: Top 10 hosts by number of requests top_hosts = parsed \ .map(lambda x: (x[0], 1)) \ .reduceByKey(lambda a, b: a + b) \ .sortBy(lambda x: -x[1]) \ .take(10) print("Top 10 requesting hosts:") for host, cnt in top_hosts: print(f" {cnt:6,} {host}")
Output
Top requesting hosts: 17572 piweba3y.prodigy.com 11591 piweba4y.prodigy.com 9868 piweba1y.prodigy.com 7852 edams.ksc.nasa.gov 7573 163.206.89.4 5922 piweba2y.prodigy.com 5645 www-d1.proxy.aol.com 5548 alyssa.prodigy.com 5444 siltb10.orl.mmc.com 5438 www-b2.proxy.aol.com
Your Tasks

Complete the following in your own copy of this notebook:

  1. Error rate: What percentage of all requests returned a 4xx or 5xx status code? Use filter() and count().
  2. Hourly traffic: Parse the hour from the timestamp and count requests per hour. Which hour had the most traffic? (hint: timestamp format is 01/Jul/1995:00:00:01 -0400: split on :)
  3. Bandwidth: Sum the bytes field per host and find the top 5 hosts by total bytes transferred. Handle the "-" case (treat as 0).
  4. 404 analysis: Which URLs had the most 404 (not found) errors? List the top 10.
Hint for Task 2: ts.split(':')[1] gives you the hour as a string (e.g. "00", "14"). Group and count from there.
Markdown

Reflection Questions

Answer these briefly in a markdown cell in your notebook:

  • At what approximate data size do you think Spark would start outperforming the naive Python loop on a single machine? Why?
  • The reduceByKey operation is a reduce. What is the corresponding map step in this pipeline?
  • If you had 100 machines and 1TB of logs, which parts of this pipeline would run in parallel?