Chapter 10 - Beyond MapReduce - Pig, Hive & ZooKeeper
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
| Problem | Explanation |
|---|---|
| Low-level abstraction | Developers write Java code that's hard to maintain and reuse |
| Isolated jobs | Intermediate processes can't talk to each other |
| Heavy shuffling | Not dynamic enough for data that needs lots of network transfers |
| Not for streaming | MR is best for batch processing on data you already have |
| Not for OLTP | Not suited for large numbers of short online transactions |
| Overkill for small data | A 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
| Type | Has Schema? | Examples |
|---|---|---|
| Structured | ✅ Yes | RDBMS tables (rows + columns with defined types) |
| Unstructured | ❌ No | Log 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?
| Problem | Detail |
|---|---|
| Small unstructured data | grep, sed, awk work fine — but only on a single machine |
| Big unstructured data | Web crawls, log files, click streams — terabytes! |
| SQL is too strict | Not suited for scripting-centric workflows |
| MapReduce is tedious | Rigid 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 Case | Why Pig? |
|---|---|
| Ad-hoc analysis of unstructured data | Web crawls, log files, click streams |
| ETL tool | Extract → Transform → Load before data warehouse ingestion |
| Rapid prototyping for analytics | Experiment with large datasets before writing custom apps |
6. Data Storage Hierarchy
| Level | Description |
|---|---|
| File | Raw files on disk |
| Database (DB) | Structured, queryable |
| Data Warehouse (DW) | Historical, analytics-oriented |
| Data Lake (DL) | Raw, unprocessed, multi-format |
| Big Data | Distributed, 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
| Goal | Meaning |
|---|---|
| Dataflow Language | Operations expressed as sequential steps; each step = one high-level transformation |
| Quick Start | Load flat files fast; schemas are optional — refer to fields by position ($0, $1) |
| Fully Nested Data Model | A field can encapsulate any other data type |
| UDFs as First-Class Citizens | Functions can take and return any data type (unlike SQL) |
Schemas are optional = Pig supports both structured and unstructured data!
8. Pig Latin — Data Types
| Type | Description | Example |
|---|---|---|
| Atom | Simple atomic value | 'alice' |
| Tuple | Sequence of fields (any types) | ('alice', 'lakers') |
| Bag | Collection of tuples | {('alice','lakers'), ('alice',('iPod','apple'))} |
| Map | Key-value pairs (key = atom) | ['fan of' → {'lakers','iPod'}, 'age' → 20] |
9. Pig Latin — Expressions ⭐
Given tuple: with fields f1, f2, f3
| Expression Type | Example | Value for |
|---|---|---|
| Constant | 'bob' | Always 'bob' |
| Field by position | $0 | 'alice' |
| Field by name | f3 | ['age' → 20] |
| Projection | f2.$0 | {('lakers'), ('iPod')} |
| Map Lookup | f3#'age' | 20 |
| Function Evaluation | SUM(f2.$1) | |
| Conditional | f3#'age'>18? 'adult':'minor' | 'adult' |
| Flattening | FLATTEN(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'COGROUP — Group Related Data from Multiple Relations
grouped_data = COGROUP results BY queryString,
revenue BY queryString;GROUPis 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.,
DUMPorSTORE)
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?
| Problem | Detail |
|---|---|
| SQL users don't know Java | Business analysts can't write MapReduce programs |
| RDBMS is maxed out | Storage and compute limits of a single server |
| Need SQL at TB/PB scale | Traditional 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
| Component | Role |
|---|---|
| CLI / WebUI / JDBC / ODBC | External interfaces for users |
| Thrift Server | Cross-language framework (Java, C++, PHP, Perl, Python) |
| Metastore | System catalog — stores table schemas, SerDes, partition info. Stored in RDBMS (HDFS too slow for random access) |
| Driver | Maintains lifecycle of a HiveQL statement |
| Query Compiler | Compiles HiveQL → DAG of MapReduce tasks |
| Executor | Runs the plan in correct dependency order |
Hive Driver = Brain of Hive! Its output is a MapReduce job.
16. Hive Data Model
Tables → Partitions → Buckets
| Level | What It Is | HDFS Location |
|---|---|---|
| Table | Like an RDBMS table | /wh/t |
| Partition | Sub-directory of the table, organized by column value | /wh/t/2 |
| Bucket | File within a partition (hash-based) | /wh/t/2/part-0000.part |
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
| Operation | Direction |
|---|---|
| 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
| Format | Type | Best For |
|---|---|---|
| Parquet | Columnar | Fast analytical reads (reads only needed columns) |
| Avro | Row-based | Streaming data pipelines, schema evolution |
| ORC | Optimized Row Columnar | Hive-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
| Optimization | What It Does | Benefit |
|---|---|---|
| Predicate Pushdown | Filter data before join/scan | Less data read |
| Column Pruning | Read only columns you need | Faster I/O |
| Partition Pruning | Read only relevant partitions | Huge speedup |
| Map Join (Broadcast) | Broadcast small table to all nodes | Avoids costly shuffle |
| Job Reduction | Combine multiple joins into fewer MR jobs | Lower 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:
- Partition Pruning — Read only
sale_date = '2026-01-01'partition - Predicate Pushdown — Filter
country = 'TH'before joining customers - Column Pruning — Read only needed columns from each table
- Map Join — Broadcast small
customerstable to all nodes - Join Re-ordering — (filtered customers) JOIN sales → JOIN products
- 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)
| Type | Description | Example |
|---|---|---|
| UDF | Operates on individual data elements | Substr, Trim |
| UDAF | Aggregation on columns | Sum, Avg, Max, Min |
| UDTF | Outputs a new table | Explode (like FLATTEN() in Pig) |
| Custom MR Scripts | Read/write from standard I/O | Custom Java/Python scripts |
23. Hive Pros & Cons
| ✅ Pros | ❌ Cons |
|---|---|
| Familiar SQL for analysts | No UPDATE/DELETE support (limited DML) |
| Easy learning curve | Multi-query optimization is weak |
| Transparent to MapReduce | Independent jobs not parallelized in DAG |
| Partitions = huge speedup | Debug support in shell is poor |
| Flexible data loading |
PART 3: Hive vs. Pig
24. Comparison
| Dimension | Pig | Hive |
|---|---|---|
| Language Style | Procedural — specify steps (A = load; dump A) | Declarative — say what you want (SELECT * FROM A) |
| Work Type | Ad-hoc analysis (click streams, search logs) | Reporting tool (weekly BI reports) |
| Target Users | Researchers, programmers, ML pipelines | Business analysts |
| Data Types | Structured + semi-structured + unstructured | Structured only |
| Integration | No Thrift server | Thrift server (JDBC, ODBC) |
| Abstraction | Higher-level scripting | Higher-level SQL |
Declarative = say what you want (SQL). Procedural = say how to get it (C, Pig Latin).
25. MapReduce vs. Hive vs. Pig
| Feature | MapReduce | Hive | Pig |
|---|---|---|---|
| Language | Compiled Java | SQL-like (HiveQL) | Scripting (Pig Latin) |
| Code Complexity | Long, complex | Short, familiar | Moderate |
| Data Types | All | Structured only | All |
| Abstraction Level | Lowest | Highest | High |
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:
| Feature | What It Solves |
|---|---|
| Naming | Centralized naming of distributed nodes |
| Configuration | Shared dynamic config across all nodes |
| Synchronization | Barriers, locks, semaphores |
| Organization | Membership lists |
| Heartbeat | Detect node failures |
| Leader Election | Elect 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
| Type | Description |
|---|---|
| Ephemeral | Exists only as long as the creating client's session; no children |
| Persistent | Survives client disconnection |
| Sequential | Persistent + sequence number appended (e.g., /zoo/goat2) |
30. ZooKeeper API
| Operation | Description |
|---|---|
create | Creates a znode |
delete | Deletes a znode (must have no children) |
exists | Tests if znode exists + retrieves metadata |
getACL / setACL | Gets/sets access control list |
getChildren | Gets list of children |
getData / setData | Gets/sets data for a znode |
sync | Synchronizes 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
- All nodes create a sequential, ephemeral znode under
/app/leader_election/guid_ - ZooKeeper appends a 10-digit sequence →
guid_0000000001,guid_0000000002, etc. - Node with the smallest number becomes Leader; all others = Followers
- Each follower watches the znode with the next smallest number (e.g.,
guid_8watchesguid_7) - If leader goes down → its znode is deleted
- Next-in-line follower gets watch notification about leader removal
- Next-in-line checks: any smaller znodes exist? → If none, it becomes Leader
- 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
| Guarantee | Description |
|---|---|
| Replicated | Every modification replicated to a majority of ensemble |
| Fault Tolerant | Works as long as majority of nodes are active |
| Sequential Consistency | Every update is sequentially consistent |
| Atomic | All updates to znode state are atomic |
| Single System Image | Every client sees one consistent view |
| Durable | Updates persist despite server failures |
| Timely | Client's view is not stale |