Chapter 10 - Beyond MapReduce - Pig, Hive & ZooKeeper

Chapter 10 - Beyond MapReduce - Pig, Hive & ZooKeeper

Updated 5 Oct 2026

Chapter 10 — Beyond MapReduce: Pig, Hive & ZooKeeper

CSS451 Cloud Computing · Cheat Sheet


🧭 Big Picture First

MapReduce is like a factory assembly line — great for bulk batch processing, but terrible for quick custom orders, live interactions, or anything that needs SQL-style queries. This chapter covers three tools that sit on top of Hadoop to make big data processing easier and more flexible:

  • Pig — scripting language for data pipelines
  • Hive — SQL interface for big data
  • ZooKeeper — coordination service for distributed systems

1. Why Go Beyond MapReduce?

Disadvantages of MapReduce

ProblemExplanation
Low-level abstractionDevelopers write Java code that's hard to maintain and reuse
Isolated jobsIntermediate processes can't talk to each other
Heavy shufflingNot dynamic enough for data that needs lots of network transfers
Not for streamingMR is best for batch processing on data you already have
Not for OLTPNot suited for large numbers of short online transactions
Overkill for small dataA standalone system is less painful to configure

OLTP ≠ OLAP. MapReduce is suited for OLAP (analytical, batch) — not OLTP (transactional, real-time).

What Users Actually Need

  • Interactive processing of large log files
  • SQL syntax instead of Java code
  • Data warehousing with transactions and queries
  • Custom distributed apps without managing synchronization from scratch

2. Structured vs. Unstructured Data

TypeHas Schema?Examples
Structured✅ YesRDBMS tables (rows + columns with defined types)
Unstructured❌ NoLog files, emails, web server logs, pictures, audio, video

Structured = spreadsheet (every column named and typed). Unstructured = pile of sticky notes (no standard format).


3. The Hadoop Ecosystem

         [Pig]    [Hive]
              ↓   ↓
         [MapReduce]
              ↓
            [HDFS]

[ZooKeeper] — standalone coordination service
  • Pig and Hive both run on top of HDFS + MapReduce
  • ZooKeeper is a standalone distributed coordination service

PART 1: Apache Pig 🐷

4. Why Pig?

ProblemDetail
Small unstructured datagrep, sed, awk work fine — but only on a single machine
Big unstructured dataWeb crawls, log files, click streams — terabytes!
SQL is too strictNot suited for scripting-centric workflows
MapReduce is tediousRigid Map/Reduce only; custom joins are painful; hard to reuse

5. What Is Apache Pig?

  • Pig Latin — a high-level language to express operations on data as a query execution plan
  • Apache Pig Framework — interprets and executes Pig Latin programs into MapReduce jobs ⭐ (exam!)
  • Grunt — command line interface (CLI) to Pig
  • Pig Pen — debugging environment

Pig Latin is like a scripting language that automates writing raw MapReduce Java code. You describe what to do step-by-step, and Pig translates it into MapReduce.

Pig Use Cases

Use CaseWhy Pig?
Ad-hoc analysis of unstructured dataWeb crawls, log files, click streams
ETL toolExtract → Transform → Load before data warehouse ingestion
Rapid prototyping for analyticsExperiment with large datasets before writing custom apps

6. Data Storage Hierarchy

LevelDescription
FileRaw files on disk
Database (DB)Structured, queryable
Data Warehouse (DW)Historical, analytics-oriented
Data Lake (DL)Raw, unprocessed, multi-format
Big DataDistributed, massive-scale

ETL Process

[Source DBs] --EXTRACT--> [Staging Area] --TRANSFORM & LOAD--> [Data Warehouse] ---> [Analytics]
  • Extract — Pull data from source systems
  • Transform — Clean, format, restructure
  • Load — Push into target warehouse

Star Schema (Data Warehouse Model)

      [Date Dim]      [Customer Dim]
           \               /
            [SALES FACT TABLE]
           /               \
     [Store Dim]       [Product Dim]
  • Fact Table (center) — measurable quantitative data (e.g., Sales Units)
  • Dimension Tables (surrounding) — descriptive context (Date, Customer, Store, Product)
  • Each dimension has a hierarchy: Year → Quarter → Month → Week → Day → Hour

Star Schema looks like a star — fact table at center, dimensions pointing outward like rays.


7. Pig Latin Design Goals

GoalMeaning
Dataflow LanguageOperations expressed as sequential steps; each step = one high-level transformation
Quick StartLoad flat files fast; schemas are optional — refer to fields by position ($0, $1)
Fully Nested Data ModelA field can encapsulate any other data type
UDFs as First-Class CitizensFunctions can take and return any data type (unlike SQL)

Schemas are optional = Pig supports both structured and unstructured data!


8. Pig Latin — Data Types

TypeDescriptionExample
AtomSimple atomic value'alice'
TupleSequence of fields (any types)('alice', 'lakers')
BagCollection of tuples{('alice','lakers'), ('alice',('iPod','apple'))}
MapKey-value pairs (key = atom)['fan of' → {'lakers','iPod'}, 'age' → 20]

9. Pig Latin — Expressions ⭐

Given tuple: t=(’alice’,(’lakers’,1),(’iPod’,2),[’age’→20])t = (\text{'alice'}, {(\text{'lakers'},1),(\text{'iPod'},2)}, [\text{'age'} \to 20]) with fields f1, f2, f3

Expression TypeExampleValue for tt
Constant'bob'Always 'bob'
Field by position$0'alice'
Field by namef3['age' → 20]
Projectionf2.$0{('lakers'), ('iPod')}
Map Lookupf3#'age'20
Function EvaluationSUM(f2.$1)1+2=31 + 2 = 3
Conditionalf3#'age'>18? 'adult':'minor''adult'
FlatteningFLATTEN(f2)'lakers', 1 / 'iPod', 2 (separate rows)

⭐ Exam: You will be given a tuple and asked to find the value of an expression.


10. Pig Latin — Operators

LOAD — Read Input Data

queries = LOAD 'query_log.txt' USING myLoad()
          AS (userId, queryString, timestamp);
  • myLoad() = user-defined function (UDF)
  • Produces a bag of tuples

FOREACH — Process Each Tuple

expanded_queries = FOREACH queries GENERATE userId,
                   expandQuery(queryString);
  • Applies a function to each tuple in a bag

FLATTEN — Remove Nesting

FLATTEN(expandedQueries);
  • ('alice', {('lakers rumours'), ('lakers news')}) → ('alice','lakers rumours'), ('alice','lakers news')

FILTER — Keep Only Matching Tuples

FILTER expandedQueries BY userId == 'alice'
grouped_data = COGROUP results BY queryString,
                        revenue BY queryString;
  • GROUP is a special case of COGROUP (single relation only)

JOIN — Cross Product of Matching Tuples

join_result = JOIN results BY queryString,
                   revenue BY queryString;
  • JOIN = COGROUP + FLATTEN

STORE — Write Output

STORE join_results INTO 'myoutput' USING myStore();

11. Pig Architecture

[Grunt CLI / PigPen]
        ↓
   [Pig Driver]
        ↓
  [Logical Plan]        ← Parser + Semantic Check + Logical Optimizer
        ↓
  [Physical Plan]       ← Logical → Physical Translator
        ↓
  [MapReduce Plan]      ← Physical → MR Plan Translator
        ↓
  [Execution on Hadoop]

Lazy Compilation ⭐

  • Pig builds the plan as you write commands
  • Execution starts only when output is requested (e.g., DUMP or STORE)

Like a GPS that only calculates the route when you actually start driving — waits until the output is needed.


PART 2: Apache Hive 🐝

12. Why Hive?

ProblemDetail
SQL users don't know JavaBusiness analysts can't write MapReduce programs
RDBMS is maxed outStorage and compute limits of a single server
Need SQL at TB/PB scaleTraditional DBs can't handle this volume

13. What Is Apache Hive?

  • A data warehouse infrastructure built on top of Hadoop
  • Compiles SQL-style queries (HiveQL) into MapReduce jobs ⭐ (exam!)
  • Uses MapReduce for execution and HDFS for storage
  • Supports only structured data (unlike Pig which handles all types)

Hive = putting a SQL interface on top of Hadoop. You think you're querying a database; under the hood, Hive converts your SQL into MapReduce jobs.

Hive Key Principles

  • HiveQL — SQL-like query language
  • Data Warehouse infrastructure on Hadoop
  • Allows plugging in custom mappers and reducers
  • Provides ETL tools

14. Hive Use Cases

  • Predictive modeling & hypothesis testing
  • Customer-facing business intelligence
  • Document indexing
  • Text mining & data analysis

15. Hive Architecture

[Hive Clients]           [Hive Services]              [Storage & Compute]
Thrift App ──────────→  CLI                            Metastore DB
JDBC App   ──────────→  Hive Server → Driver ────────→ FileSystem (HDFS)
ODBC App   ──────────→  Hive Web UI   Execution Engine  Hadoop Cluster

Components

ComponentRole
CLI / WebUI / JDBC / ODBCExternal interfaces for users
Thrift ServerCross-language framework (Java, C++, PHP, Perl, Python)
MetastoreSystem catalog — stores table schemas, SerDes, partition info. Stored in RDBMS (HDFS too slow for random access)
DriverMaintains lifecycle of a HiveQL statement
Query CompilerCompiles HiveQL → DAG of MapReduce tasks
ExecutorRuns the plan in correct dependency order

Hive Driver = Brain of Hive! Its output is a MapReduce job.


16. Hive Data Model

Tables → Partitions → Buckets

LevelWhat It IsHDFS Location
TableLike an RDBMS table/wh/t
PartitionSub-directory of the table, organized by column value/wh/t/2
BucketFile within a partition (hash-based)/wh/t/2/part-0000.part

H(column)mod  NumBuckets=bucket number\boxed{H(\text{column}) \mod \text{NumBuckets} = \text{bucket number}}

Think of a table as a filing cabinet, partitions as drawers (organized by date/country), and buckets as folderswithin each drawer (organized by customer ID hash).

Partition Example

CREATE TABLE Sales (sale_id INT, amount FLOAT)
PARTITIONED BY (country STRING, year INT, month INT)

Creates directory hierarchy:

Sales/country=US/year=2012/month=12/
Sales/country=CANADA/year=2014/month=11/

17. Serialization & SerDe

Serialization

Converting an object/data → stream of bytes to store or transmit it. Reverse = Deserialization

SerDe in Hive

OperationDirection
Write (INSERT)Hive serializes data → stores as files in HDFS
Read (SELECT)Hive deserializes data → converts files → rows/columns

SerDe = the translator between Hive tables and raw data files in HDFS.

Lazy deserialization = deserialize only when actually requested (on demand).

SerDe allows Hive to support multiple file formats: CSV, JSON, ORC, Parquet, Avro

File Formats

FormatTypeBest For
ParquetColumnarFast analytical reads (reads only needed columns)
AvroRow-basedStreaming data pipelines, schema evolution
ORCOptimized Row ColumnarHive-optimized storage

Parquet example — column-based is much faster for selective queries:

Row-based:   Row1: id=1, name=Alice, age=20
Columnar:    id:[1,2], name:[Alice,Bob], age:[20,25]

SELECT age FROM users → reads ONLY the age column

18. HiveQL to MapReduce Flow

Analyst writes: SELECT COUNT(1) FROM Sales;
          ↓
    [Hive Framework]
    CLI / JDBC / ODBC → Driver → Metastore
          ↓
    [MapReduce Job]
    Map: emit (rowcount, 1) per row
    Reduce: sum all values → final count N
          ↓
    Result N returned to analyst

19. Compilation Pipeline

[Parser]           Parse query → parse tree
      ↓
[Semantic Analyzer] Schema check, type checking, column verification
      ↓
[Logical Plan Generator] Internal query representation → logical plan
      ↓
[Optimizer]        Combine joins, reduce MR jobs, prune columns
      ↓
[Physical Plan Generator] Logical plan → DAG of MapReduce jobs
      ↓
[Execution in Hadoop]

20. Optimization Strategies

OptimizationWhat It DoesBenefit
Predicate PushdownFilter data before join/scanLess data read
Column PruningRead only columns you needFaster I/O
Partition PruningRead only relevant partitionsHuge speedup
Map Join (Broadcast)Broadcast small table to all nodesAvoids costly shuffle
Job ReductionCombine multiple joins into fewer MR jobsLower latency

Key rule: FILTER FIRST, THEN JOIN! This alone dramatically reduces data volume.

Example: Full Optimization on a Complex Query

SELECT c.country, p.category, SUM(s.amount)
FROM sales s
JOIN customers c ON s.customer_id = c.id
JOIN products p ON s.product_id = p.id
WHERE s.sale_date = '2026-01-01' AND c.country = 'TH'
GROUP BY c.country, p.category;

Optimized Execution Steps:

  1. Partition Pruning — Read only sale_date = '2026-01-01' partition
  2. Predicate Pushdown — Filter country = 'TH' before joining customers
  3. Column Pruning — Read only needed columns from each table
  4. Map Join — Broadcast small customers table to all nodes
  5. Join Re-ordering — (filtered customers) JOIN sales → JOIN products
  6. Partial Aggregation — Map-side partial SUM, then reduce-side final aggregation

21. HiveQL Reference

DDL

CREATE DATABASE my_db;
CREATE TABLE my_table (...);
ALTER TABLE my_table ...;
SHOW TABLES;
DESCRIBE my_table;

DML

LOAD DATA INPATH '/path/to/file' INTO TABLE my_table;
INSERT INTO my_table SELECT ...;

Query

SELECT col1, col2 FROM table WHERE ...;
SELECT col, COUNT(*) FROM table GROUP BY col;
SELECT * FROM t1 JOIN t2 ON t1.id = t2.id;
 
-- Multi Table Insert (one pass, multiple outputs)
FROM base_table
INSERT INTO table1 SELECT ...
INSERT INTO table2 SELECT ...;

22. User-Defined Functions (UDFs)

TypeDescriptionExample
UDFOperates on individual data elementsSubstr, Trim
UDAFAggregation on columnsSum, Avg, Max, Min
UDTFOutputs a new tableExplode (like FLATTEN() in Pig)
Custom MR ScriptsRead/write from standard I/OCustom Java/Python scripts

23. Hive Pros & Cons

✅ Pros❌ Cons
Familiar SQL for analystsNo UPDATE/DELETE support (limited DML)
Easy learning curveMulti-query optimization is weak
Transparent to MapReduceIndependent jobs not parallelized in DAG
Partitions = huge speedupDebug support in shell is poor
Flexible data loading

PART 3: Hive vs. Pig

24. Comparison

DimensionPigHive
Language StyleProcedural — specify steps (A = load; dump A)Declarative — say what you want (SELECT * FROM A)
Work TypeAd-hoc analysis (click streams, search logs)Reporting tool (weekly BI reports)
Target UsersResearchers, programmers, ML pipelinesBusiness analysts
Data TypesStructured + semi-structured + unstructuredStructured only
IntegrationNo Thrift serverThrift server (JDBC, ODBC)
AbstractionHigher-level scriptingHigher-level SQL

Declarative = say what you want (SQL). Procedural = say how to get it (C, Pig Latin).

25. MapReduce vs. Hive vs. Pig

FeatureMapReduceHivePig
LanguageCompiled JavaSQL-like (HiveQL)Scripting (Pig Latin)
Code ComplexityLong, complexShort, familiarModerate
Data TypesAllStructured onlyAll
Abstraction LevelLowestHighestHigh

PART 4: Apache ZooKeeper 🦁

26. Why ZooKeeper?

Distributed apps need to solve hard coordination problems:

  • Synchronization, naming, consensus, configuration, leader election

Well-known algorithms exist — but every developer has to re-implement them for each new app. ZooKeeper provides these as a ready-to-use service.

The Master-Slave Problem

  • Master-slave architectures are popular but: what happens when the master fails?
  • A single master = performance bottleneck
  • ZooKeeper solves master election and failover automatically

27. What Is ZooKeeper?

  • A distributed coordination service for large-scale distributed systems
  • Provides building blocks for:
FeatureWhat It Solves
NamingCentralized naming of distributed nodes
ConfigurationShared dynamic config across all nodes
SynchronizationBarriers, locks, semaphores
OrganizationMembership lists
HeartbeatDetect node failures
Leader ElectionElect a new master automatically

ZooKeeper is like the conductor of an orchestra — it doesn't play music itself, but coordinates all musicians (distributed nodes) to ensure they're synchronized and in agreement.


28. ZooKeeper Architecture

              [ZooKeeper Ensemble]
    ┌──────────────────────────────────────┐
    │  Server   Server  [Leader]  Server   │
    └──────┬────────┬──────┬─────────┬────┘
           ↑        ↑      ↑         ↑
        Client   Client Client    Client
  • ZooKeeper Ensemble = cluster of ZooKeeper servers
  • One is elected Leader, others are Followers
  • Clients connect to any server; if one fails, connect to the next

Sessions

  • Client connects → creates a session with a configurable timeout
  • Session kept alive via heartbeat
  • On reconnection: failure events handled + watch events delivered automatically

29. ZooKeeper Data Model

  • Hierarchical like a filesystem; each node = znode
  • Znodes store data and have an ACL
  • Size limit: 1 MB per znode
         /
         └── /zoo
               ├── /duck
               ├── /goat
               └── /cow

Types of Znodes

TypeDescription
EphemeralExists only as long as the creating client's session; no children
PersistentSurvives client disconnection
SequentialPersistent + sequence number appended (e.g., /zoo/goat2)

30. ZooKeeper API

OperationDescription
createCreates a znode
deleteDeletes a znode (must have no children)
existsTests if znode exists + retrieves metadata
getACL / setACLGets/sets access control list
getChildrenGets list of children
getData / setDataGets/sets data for a znode
syncSynchronizes client's view with ZooKeeper

31. Reads, Writes & Watches

  • Reads — can be served by any server
  • Writes — always forwarded to the Leader, who commits atomically to a majority
           [Ensemble]
          Leader
  Server ←── Server ──→ Server
read↑   read↑  WRITE↑   read↑
Client  Client  Client  Client
  • Watch — set optionally on a znode after a read; triggered when the znode is deleted or changed

32. ZooKeeper Protocol: Zab

Zab = ZooKeeper Atomic Broadcast — a two-phase protocol:

Phase 1: Leader Election

  • All ensemble members elect a Leader (others = Followers)
  • Election complete when a majority (quorum) of followers sync state with leader

Phase 2: Atomic Broadcast

  • Write requests forwarded to Leader
  • Leader broadcasts update to all Followers
  • Update committed when a quorum of followers persist the change
  • Writes happen atomically via two-phase commit (2PC)

Why odd number of nodes? ZooKeeper needs a majority quorum to commit writes and elect leaders. Odd numbers (3, 5, 7) always allow a clear majority even under failures: 3 nodes tolerate 1 failure, 5 tolerate 2. Even numbers risk split-brain.


33. Leader Election — Step by Step

  1. All nodes create a sequential, ephemeral znode under /app/leader_election/guid_
  2. ZooKeeper appends a 10-digit sequence → guid_0000000001, guid_0000000002, etc.
  3. Node with the smallest number becomes Leader; all others = Followers
  4. Each follower watches the znode with the next smallest number (e.g., guid_8 watches guid_7)
  5. If leader goes down → its znode is deleted
  6. Next-in-line follower gets watch notification about leader removal
  7. Next-in-line checks: any smaller znodes exist? → If none, it becomes Leader
  8. All others re-elect the node with the smallest remaining znode

34. Higher-Level Constructs

Barrier — Synchronize Start/End of Computation

Client calls exists("/b1") with watch=true
  ├── returns true  → wait (barrier still up)
  └── returns false → barrier gone → proceed!

When watch triggers → re-issue exists() and repeat
  • Barrier node = /b1
  • Each process creates /b1/p_i
  • Once enough processes join → computation can begin

Queue

create(/q/i-) → /q/i-1, /q/i-2, /q/i-n
  • Use create() with sequential znodes under /q
  • Process queue items with getChildren() on /q
  • Watch notifies client of new items

35. ZooKeeper Guarantees

GuaranteeDescription
ReplicatedEvery modification replicated to a majority of ensemble
Fault TolerantWorks as long as majority of nodes are active
Sequential ConsistencyEvery update is sequentially consistent
AtomicAll updates to znode state are atomic
Single System ImageEvery client sees one consistent view
DurableUpdates persist despite server failures
TimelyClient's view is not stale