Skip to main content
Big Data Analytics

Pig, Hive, and Data Transformation Frameworks

Published: 2026-08-01
Level: postgraduate
Audience: Postgraduate students in Big Data Analytics

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • The Hadoop Distributed File System (HDFS) and block replication - covered in Lecture 3
  • The MapReduce programming model and execution lifecycle - covered in Lecture 4
  • Apache YARN resource management and scheduling - covered in Lecture 5
  • Apache Sqoop and Apache Flume data ingestion - covered in Lecture 5
  • Apache Hive as a data warehousing layer over Hadoop - covered in Lectures 3 and 5
  • Apache Pig within the Hadoop ecosystem - covered in Lecture 3

# Pig, Hive, and Data Transformation Frameworks

6.1 Lecture Overview, Progress Tracking, and Hadoop Ecosystem Architecture

6.1.1 Hadoop Curriculum Positioning and Core Infrastructure Stack

Why do we need more than just HDFS and MapReduce? If storing petabytes is solved and processing them in parallel is solved, what is still missing? The answer is usability — getting actual business value from the data requires people to write transformation logic, and raw MapReduce in Java is painfully slow to develop.

Enterprise big data architectures rely on a layered stack of storage engines, distributed execution frameworks, multi-tenant schedulers, and data transformation interfaces. In the overall big data ecosystem maturity model, foundational infrastructure comprises two core capabilities:

  • Infinite Distributed Storage: Provided by the Hadoop Distributed File System (HDFS), which splits large datasets into fixed-size blocks (default 128 MB each) and distributes replica copies across a cluster of commodity machines. A master NameNode tracks which blocks live on which DataNodes, while the DataNodes store the actual data and report heartbeats to the master.
  • Infinite Parallel Processing: Provided by the MapReduce (MR) programming paradigm, which executes data-localized map, shuffle, sort, and reduce operations across multi-node clusters. The key insight is data locality — moving computation to where the data resides rather than shipping data across the network to a central processor.

The Hadoop Layer Model (bottom-up):

  1. Storage Layer — HDFS (distributed file system)
  2. Resource Management Layer — YARN (Yet Another Resource Negotiator) — schedules jobs and allocates CPU/memory containers
  3. Processing Layer — MapReduce (batch processing engine), or later Tez/Spark
  4. Abstraction Layer — Pig (data-flow scripting) and Hive (SQL-like querying) — the subject of this lecture
  5. Application Layer — ETL pipelines, analytics dashboards, machine learning workflows

Having established how HDFS manages block storage and how MapReduce parallelizes key-value computations, the current curriculum advances to data flow scripting, data warehousing, and cluster coordination. Specifically, this lecture covers Apache Pig (a high-level data flow scripting language created by Yahoo) and introduces Apache Hive (a data warehousing infrastructure created by Facebook). These components eliminate the need to write raw Java MapReduce programs. Subsequent course modules progress to cluster coordination using Apache Zookeeper, NoSQL database architectures (including Apache HBase and Apache Cassandra), followed by Apache Spark and distributed machine learning after the mid-semester evaluation.

Curriculum roadmap recap: HDFS storage → YARN resource management → MapReduce processing → Pig & Hive (this lecture) → Zookeeper → HBase/Cassandra → Spark → ML. Pig and Hive sit at the abstraction layer, translating high-level scripts into MapReduce jobs automatically.

6.1.2 Recap of Lecture 5: YARN Scheduling, Sqoop Ingestion, and Flume Log Streaming

To contextualize high-level data processing frameworks, consider the core infrastructure components established in previous lectures:

  • YARN (Yet Another Resource Negotiator): Operates as a master-slave architecture decoupling cluster resource management from application execution. The master Node hosts the Resource Manager, which contains two sub-components:
  1. Application Manager: Accepts incoming job submissions, negotiates initial resource containers, and spins off an Application Master instance on a slave node. Think of the Application Manager as a receptionist — it takes your request and assigns you a coordinator.
  2. Scheduler: Allocates cluster memory and CPU containers across competing applications according to configured scheduling policies:
  • FIFO Scheduler — first-in, first-out; simplest but can starve small jobs behind large ones
  • Capacity Scheduler — guarantees a minimum capacity to each queue (used by Yahoo)
  • Fair Scheduler — dynamically balances resources so all applications get roughly equal share (used by Facebook)
  • Slave Nodes: Run NodeManager daemons responsible for monitoring container resource utilization and launching actual map and reduce tasks. Each NodeManager reports available resources to the Resource Manager via periodic heartbeats.
  • Sqoop (SQL-to-Hadoop): A relational data ingestion tool designed to import and export structured datasets bi-directionally between Relational Database Management Systems (RDBMS) such as MySQL, Oracle, or PostgreSQL and HDFS or Hive tables. Sqoop generates MapReduce jobs under the hood to perform the data transfer in parallel, reading from and writing to multiple database partitions simultaneously.
  • Flume: A distributed, reliable event collection service used to stream unstructured log data (such as web server logs or streaming network packets) into HDFS logger sinks. A Flume agent has three components:
  • Source — receives data (e.g., Netcat, Avro, exec, Spooling Directory)
  • Channel — buffers data (memory channel for speed, file channel for durability)
  • Sink — writes data to the destination (HDFS, HBase, Logger)

Scope: YARN, Sqoop, and Flume are background context for this lecture. The exam focuses on Pig and Hive — know what these predecessor components do and where they fit, but deep architecture questions will target the new material.

6.1.3 The MapReduce Usability Gap and Motivation for High-Level Frameworks

The central problem of this lecture: MapReduce is powerful but painful to write. How can we let data analysts — people who know SQL, not Java — work with petabyte-scale data?

Although MapReduce provides massive computational scalability, writing native MapReduce applications in Java presents a steep development barrier. Developers must manually implement low-level Java code comprising three distinct components:

  1. Job Configuration: Writing verbose Java boilerplate to configure input/output formats, key-value serialization classes (Writable), mapper classes, reducer classes, and cluster job parameters.
  2. Mapper Class: Deconstructing business logic into parallel map steps that process raw input key-value pairs and emit intermediate key-value pairs. Each mapper must implement the Mapper<K1, V1, K2, V2> interface and override the map() method.
  3. Reducer Class: Defining shuffle-and-sort aggregation logic to process groups of intermediate values associated with each key. Each reducer must implement the Reducer<K2, V2, K3, V3> and override the reduce() method.

Code comparison — word count (the "Hello World" of MapReduce):

A simple word-count task in Java MapReduce requires roughly 60–100 lines of boilerplate (driver class, mapper class, reducer class, job configuration, Writable key types). The same task in Pig Latin is approximately 5 lines:

lines = LOAD 'input/text.txt' AS (line:chararray);
words = FOREACH lines GENERATE FLATTEN(TOKENIZE(line)) AS word;
grouped = GROUP words BY word;
word_count = FOREACH grouped GENERATE group AS word, COUNT(words) AS count;
DUMP word_count;

In HiveQL, it can be done with a single SQL-style query over a table. This compression ratio (roughly 10:1 to 20:1 in lines of code) is the core motivation for both tools.

Back in 2004, Java and MapReduce were new technologies in the enterprise ecosystem. Engineering teams at major tech companies like Yahoo and Facebook possessed vast datasets and legacy workflows built heavily around SQL and relational databases. Expecting entire organizations of data analysts and DBAs to transition from SQL to writing complex Java MapReduce code created severe operational friction. To bridge this usability gap, Yahoo and Facebook independently developed high-level abstractions on top of MapReduce:

  • Facebook created Apache Hive to provide a familiar SQL-like query interface (HiveQL) over HDFS data — aimed at analysts and BI tools that already spoke SQL.
  • Yahoo created Apache Pig to provide a procedural, data-flow scripting language (Pig Latin) for complex data transformations — aimed at engineers building ETL pipelines.

Declarative vs. Procedural — the key distinction:

  • SQL (and HiveQL) is declarative: you describe what result you want (SELECT ... FROM ... WHERE ...), and the engine figures out how to execute it.
  • Pig Latin is procedural: you describe how to transform the data step by step (LOAD → FILTER → GROUP → FOREACH → STORE), and the engine translates each step into MapReduce jobs.

This distinction matters for debuggability (Pig lets you inspect each intermediate result) and expressiveness (SQL is cleaner for ad-hoc queries, Pig is cleaner for multi-step pipelines).

Pig vs. Hive side-by-side (same task — find maximum temperature by year):

Pig Latin (procedural):

records = LOAD 'weather.txt' AS (year:chararray, temp:int, quality:int);
filtered = FILTER records BY temp != 9999 AND quality IN (0,1,4,5,9);
grouped = GROUP filtered BY year;
max_temp = FOREACH grouped GENERATE group, MAX(filtered.temp);
DUMP max_temp;

HiveQL (declarative):

SELECT year, MAX(temperature) FROM records
WHERE temperature != 9999 AND quality IN (0,1,4,5,9)
GROUP BY year;

Both produce the same result. Pig shows each transformation explicitly; Hive lets you describe the desired outcome.

Real-world: Modern data platforms leverage high-level abstractions like Hive and Pig (and subsequently Spark SQL) to allow data engineers and business analysts to query petabyte-scale data lakes without writing raw Java MapReduce code.

Why Pig and Hive exist: The gap between "data sitting in HDFS" and "useful business answers" was too wide to bridge with raw Java MapReduce alone. Pig (Yahoo, procedural) and Hive (Facebook, declarative) were created to let non-Java developers work with big data. Both compile scripts into MapReduce jobs under the hood.

6.1.4 Student Questions and Answers

Q: Why could enterprise companies in 2004 not rely exclusively on traditional RDBMS setups for their growing data needs?

A: Enterprise companies faced exponential data growth that exceeded the vertical scaling limits of traditional single-node RDBMS systems. Vertical scaling (buying a bigger server) has hard physical and cost ceilings. When Facebook was ingesting hundreds of terabytes of log data per day, no single machine — no matter how powerful — could store or process it. Traditional RDBMS databases could not perform distributed parallel processing across clusters of commodity machines. This horizontal scaling requirement (adding more machines rather than upgrading one) necessitated a migration to architectures like Hadoop, which distributes both storage (HDFS) and computation (MapReduce) across thousands of nodes.

Q: Why was transitioning directly from RDBMS SQL to native Java MapReduce difficult for corporate teams?

A: Data teams were deeply comfortable with declarative SQL syntax — a language optimized for describing what data they wanted. Writing native Java MapReduce required a fundamentally different skill set: learning low-level Java programming, managing verbose job configuration boilerplate, handling custom key-value serialization (Writable interfaces), and manually structuring business logic into parallel mappers and reducers. This steep learning curve drastically slowed down development velocity. A query that took 10 minutes to write in SQL could take days to implement, debug, and deploy in Java MapReduce. The friction was not just technical but organizational — hiring Java developers for what had been an analyst's job was expensive and culturally disruptive.

6.2 Apache Pig Fundamentals, Evolution, and Data Flow Scripting

6.2.1 Origins at Yahoo and Twitter Industry Adoption

Hook: In 2006, Yahoo had petabytes of web crawl data and thousands of engineers — but almost none of them could write Java MapReduce. How do you let data analysts process big data without learning a new programming language?

Apache Pig was originally developed at Yahoo around 2006 to provide an efficient, high-level data flow environment for processing large-scale datasets on Hadoop clusters. The project was led by Yahoo Research and aimed squarely at a practical problem: the vast majority of Yahoo's data engineers and researchers knew SQL and scripting languages, not Java. Writing ETL pipelines in raw MapReduce was blocking productivity.

At Yahoo, engineering teams used Pig to write ETL (Extract, Transform, Load) pipelines, web crawl analysis scripts, and search indexing jobs. Pig became so central to Yahoo's data operations that the company open-sourced it in 2007 under the Apache Software Foundation.

At its peak between 2012 and 2017, Apache Pig achieved massive adoption across the tech industry:

  • Yahoo reported that over 80% of all MapReduce jobs executed across its multi-thousand node Hadoop clusters were generated by Pig Latin scripts.
  • Twitter heavily adopted Apache Pig for log processing, user engagement analytics, and graph mining algorithms.
  • Other major adopters included LinkedIn, Netflix, and Nokia.

Pig's core value proposition: Pig Latin lets you express complex data transformation pipelines in a fraction of the code required by Java MapReduce, while Pig's execution engine handles the translation to optimized MapReduce jobs automatically. The programmer writes what transformations to apply; Pig figures out how to execute them efficiently on the cluster.

6.2.2 Pig Latin Language Design and Productivity Gains over Java MapReduce

Pig Latin is a procedural data-flow language designed specifically for data manipulation. Unlike declarative SQL (which describes what data to retrieve without specifying execution order), Pig Latin allows developers to write an explicit sequence of data transformation steps (how to transform data step by step).

Intuition — Pig Latin is like a recipe, SQL is like a restaurant order: When you write Pig Latin, you are writing a recipe: "Load the data, then filter out bad records, then group by region, then compute the average, then save the result." Each step is explicit. When you write SQL, you are placing a restaurant order: "I want the average revenue per region for good records" — the kitchen (query planner) decides the steps.

Why does this matter? A recipe is easier to debug step by step (you can taste the sauce at each stage). A restaurant order is faster to say but harder to troubleshoot when the dish comes out wrong.

Pig Latin scripts offer massive productivity advantages over raw Java MapReduce:

Metric Java MapReduce Pig Latin Improvement Factor
Lines of code (complex ETL) 100+ lines ~5 lines 20x compression
Development time (typical task) ~16 hours ~1 hour 16x faster
Skills required Java + MR framework SQL-like scripting Lower barrier
Debugging approach Re-compile, re-submit job Inspect each relation with DUMP Interactive

Pitfall — Do not confuse "fewer lines" with "less powerful": Pig Latin compresses code because its operators (FILTER, GROUP, FOREACH GENERATE, JOIN) encapsulate entire MapReduce stages. Each 5-line Pig script can represent multiple MapReduce jobs chained together. The underlying complexity is still there — Pig just hides it.

Pedagogical Analogy: Writing Java MapReduce compared to Pig Latin is like writing low-level C code (where developers manually allocate memory and build data structures from scratch) versus writing modern Python scripts (where high-level built-in data types and operations reduce complex algorithms to concise single-line expressions).

Concrete comparison — Filtering and grouping sales data:

Java MapReduce (~80 lines): Requires a Mapper class extending Mapper<LongWritable, Text, Text, DoubleWritable>, a Reducer class extending Reducer<Text, DoubleWritable, Text, DoubleWritable>, a Driver class with Job configuration, input/output format setup, and explicit key-value type declarations.

Pig Latin (~5 lines):

sales = LOAD 'sales.csv' USING PigStorage(',') AS (region:chararray, revenue:double);
filtered = FILTER sales BY revenue > 50000.0;
grouped = GROUP filtered BY region;
avg_rev = FOREACH grouped GENERATE group AS region, AVG(filtered.revenue) AS avg_revenue;
DUMP avg_rev;

Both accomplish the same task. The Pig version can be typed, tested, and iterated in a fraction of the time.

6.2.3 Ecosystem Transition: Pig Decline and Spark Paradigm Shift

The big data ecosystem evolves rapidly as processing demands change. Between 2012 and 2015, Apache Pig represented the industry standard for Hadoop data processing. However, over time, the popularity of Pig declined due to the emergence of Apache Spark.

Apache Spark introduced in-memory cluster computing and resilient distributed datasets (RDDs), performing data transformations orders of magnitude faster than disk-based MapReduce engines. The key performance difference:

  • Pig (MapReduce-based): Every intermediate result is written to HDFS disk between MapReduce stages. For a multi-step Pig script, this means repeated disk I/O.
  • Spark: Intermediate results can be kept in memory (RAM) across stages, eliminating disk writes for iterative or multi-step computations.

Why Pig declined but Hive survived longer: Both Pig and Hive originally compiled to MapReduce. However, Hive's SQL compatibility meant it could be adopted by existing BI tools (Tableau, PowerBI) with minimal migration effort. Pig's procedural language had no direct equivalent in the SQL ecosystem, so when Spark offered SparkSQL (which was also SQL-compatible), organizations migrated from Pig to Spark more easily than from Hive. Hive also evolved to support Tez and Spark as execution engines, extending its relevance.

While Apache Pig's usage shrank as organizations migrated to Spark, Apache Hive maintained longer longevity due to its direct SQL compatibility with legacy enterprise reporting tools.

6.2.4 Student Questions and Answers

Q: How does Pig Latin differ fundamentally from SQL in terms of programming paradigm?

A: SQL is a declarative query language where the developer specifies what result set is desired, leaving the query engine to choose the execution path. Pig Latin is a procedural data-flow scripting language where the developer explicitly defines a step-by-step pipeline of transformations (load, filter, group, aggregate, store). In SQL you say "give me X"; in Pig Latin you say "do A, then B, then C." This makes Pig scripts easier to debug step by step (you can DUMP any intermediate relation), while SQL is more concise for ad-hoc analytical queries.

Q: Why did Apache Pig's popularity decline despite its massive initial success at Yahoo and Twitter?

A: Apache Pig compiled its scripts into disk-bound Hadoop MapReduce jobs. Every intermediate result was written to HDFS, causing significant I/O overhead for multi-step pipelines. The rise of Apache Spark — which offered in-memory computation, faster execution speeds, and unified APIs in Python, Scala, and SQL — led organizations to migrate away from Pig. Additionally, Spark's SparkSQL module provided SQL compatibility, which attracted both Pig and Hive users.

6.3 Pig Execution Modes, Architecture, and Grunt Shell CLI

6.3.1 Local Mode versus MapReduce Cluster Mode Execution

Hook: You've written a Pig Latin script on your laptop. How do you test it quickly before deploying to a 1,000-node cluster? Pig gives you two execution modes — one for development, one for production.

When launching Apache Pig, developers can choose between two operational execution modes depending on whether they are developing scripts locally or executing production workloads on Hadoop:

Feature Local Mode (pig -x local) MapReduce Cluster Mode (pig)
Target File System Reads and writes files from the local OS filesystem Reads and writes files directly from HDFS
Execution Engine Executes inside a single local JVM process without Hadoop Translates scripts into Java MapReduce JARs submitted to YARN
Primary Use Case Script development, local debugging, fast iteration on small datasets Production data processing on large-scale distributed clusters
Launch Command pig -x local pig (or pig -x mapreduce)
Output Location Local directory on developer workstation HDFS distributed folder directory

Exam note: Be prepared to identify the exact launch flags and filesystem behaviors for local mode (pig -x local) versus MapReduce mode (pig) on examinations. Local mode = local JVM + local disk; MapReduce mode = YARN + HDFS.

Intuition — Local mode is like a test kitchen: Think of local mode as cooking in your home kitchen with a small batch of ingredients. You can quickly try out the recipe (your Pig script), taste it, and adjust. MapReduce mode is like running the same recipe in an industrial kitchen — everything scales up, but the turnaround time for each experiment is much longer. Always develop and debug in local mode first.

6.3.2 Structural Limitations: Absence of Web Server, Storage Engine, and OLTP Capabilities

Scope: Understanding what Pig cannot do is just as important as knowing what it can. Misusing Pig for real-time queries or assuming it stores data will lead to architectural mistakes.

To evaluate where Apache Pig fits into enterprise architectures, it is essential to understand what Pig cannot do:

  1. No Native Storage Engine: Unlike relational databases (such as MySQL or PostgreSQL) which manage dedicated physical storage files on disk, Pig possesses zero native storage capabilities. Pig is purely a client-side execution framework that reads data stored externally in HDFS or local storage. Pig does not "own" any data — it only transforms it.
  1. No Background Daemon or Web Server: Pig does not run a persistent background server daemon or SQL server process. External applications written in C++, Java, or Python cannot connect remotely to Pig via JDBC/ODBC network daemons. Access occurs exclusively through the command-line client.
  1. Not Suitable for Real-Time Processing or OLTP: Pig scripts compile into batch MapReduce jobs. Because Hadoop MapReduce involves YARN container allocation, map-reduce task initialization, and disk I/O serialization, job latency ranges from tens of seconds to hours. Pig cannot be used for Online Transaction Processing (OLTP) or sub-second real-time analytics.
  1. Schema-on-Read / Schema-Less Flexibility: Pig does not enforce rigid schema constraints upon loading. A CSV file can be loaded with or without explicit column names and data types. This is schema-on-read — the schema is applied when the data is read, not when it is written.
  1. Ineffective for Unstructured Data: Pig handles structured and semi-structured datasets (such as CSV, TSV, or JSON) effectively, but is poorly suited for unstructured audio, video, or arbitrary binary blobs.

Pig vs. RDBMS — what Pig is NOT:

Capability RDBMS (MySQL, PostgreSQL) Apache Pig
Storage engine Yes (manages data files on disk) No (reads from HDFS/external)
Background server Yes (JDBC/ODBC daemon) No (client-side CLI only)
Real-time OLTP Yes (sub-second queries) No (batch MapReduce jobs)
Schema enforcement Schema-on-write (strict) Schema-on-read (flexible)
Data modification UPDATE, DELETE supported Bulk read/write only

6.3.3 Grunt Shell CLI and Interactive Script Execution

Apache Pig provides an interactive Command Line Interface (CLI) known as the Grunt Shell. Upon executing the pig command in the terminal, the environment initializes the Grunt prompt:

grunt>

From the Grunt shell, developers can interactively type Pig Latin statements line by line, inspect intermediate relations using DESCRIBE or DUMP, debug transformation logic on sample records, and execute full batch scripts (.pig files).

Grunt shell features for debugging:

  • DESCRIBE relation_name; — shows the schema (field names and types) without scanning data
  • DUMP relation_name; — triggers execution and prints the actual data to the terminal
  • EXPLAIN relation_name; — shows the logical, physical, and MapReduce execution plans
  • ILLUSTRATE relation_name; — generates a small sample dataset and steps through the execution plan

6.3.4 Etymology and Pedagogical Analogy of Apache Pig

The naming of Apache Pig follows a lighthearted animal naming convention common across the Hadoop ecosystem (such as Hadoop's yellow elephant mascot or Mahout's elephant keeper). According to official Apache Pig documentation, the name "Pig" carries three thematic justifications:

  • "Pigs eat anything": Apache Pig can ingest any structured or semi-structured data format regardless of schema (CSV, TSV, JSON, custom formats).
  • "Pigs live anywhere": Pig Latin scripts run anywhere across the Hadoop cluster ecosystem (local mode, pseudo-distributed, fully distributed).
  • "Pigs are domestic and adaptable": Pig provides a flexible, developer-friendly environment for arbitrary data transformation tasks, including User-Defined Functions (UDFs) for custom logic.

Real-world: Pig is classified strictly as an ETL (Extract, Transform, Load) data transformation tool. It is used to ingest raw incoming data, clean corrupted records, join datasets, calculate computed fields, and output refined files ready for data warehouse consumption.

6.3.5 Student Questions and Answers

Q: Can an application connect remotely to Apache Pig via JDBC or ODBC drivers to execute real-time queries?

A: No. Apache Pig lacks a background server daemon or web server architecture. It operates exclusively as a client-side CLI tool (Grunt shell) or batch script interpreter, submitting MapReduce jobs directly to YARN. If you need remote SQL access to big data, use Apache Hive (which supports JDBC/ODBC via HiveServer2).

Q: Why is local mode (pig -x local) recommended during the initial development phase of a Pig Latin script?

A: Local mode runs inside a single local JVM and reads data from the workstation's local disk, eliminating YARN container allocation and HDFS cluster overhead. This allows developers to test and iterate on transformation logic rapidly using sample data before deploying to production clusters. The feedback loop in local mode is seconds; in MapReduce mode it can be minutes to hours per job.

6.4 Pig Data Model and Data Types

6.4.1 Primitive Data Types and Type System

Hook: Every programming language needs types to make sense of raw bytes. Pig Latin defines eight primitive types that map directly to common programming language types — but it also has a special escape hatch type for when you don't know what the data looks like yet.

Apache Pig supports standard primitive data types common across programming languages:

Type Size Description Example Literal
int 32-bit signed Whole numbers 4876
long 64-bit signed Large whole numbers 10000000000L
float 32-bit floating-point Single-precision decimals 97.44f
double 64-bit floating-point Double-precision decimals 152.58
chararray Variable-length UTF-8 Text strings 'Europe'
bytearray Raw bytes Uninterpreted binary data (default when no schema) No literal form
boolean Logical True/false values true, false
datetime Temporal Date and time with timezone 2026-07-30T23:33:57.000+05:30

Pitfall — bytearray is the silent default: When you load data without specifying an AS clause, all fields default to bytearray. This means Pig will not catch type errors at load time — a string 'abc' stored as bytearray will not cause an error until you try to use it in an arithmetic operation, at which point it silently becomes null. Always declare explicit types when loading data.

6.4.2 Complex Data Structures: Tuples, Bags, and Maps

Intuition — Think of these as nested containers: A Tuple is like a single row in a spreadsheet (one record with ordered fields). A Bag is like an entire spreadsheet (a collection of rows). A Map is like a dictionary (key-value lookup). Pig's power comes from nesting these: a GROUP BY creates a Bag of Tuples inside each Tuple, letting you aggregate across the nested collection.

To handle complex, nested data representations, Pig Latin defines three constructible complex data structures:

1. Tuple

A Tuple is an ordered sequence of fields. Fields inside a tuple can be of any data type (primitive or complex). Tuples are enclosed in standard round parentheses (...) with comma-separated values:

\[ \text{Tuple Representation:} \quad (v_1, v_2, v_3, \dots, v_k) \]

Verbal description: A tuple represents an ordered list of fields enclosed in round parentheses, analogous to a single database row. Each field has a position (zero-indexed) and can be accessed by position (\$0, \$1, \$2) or by name if a schema is defined.

Example:

(1, 'Europe', 'Snacks', 4876, 97.44, 152.58)

2. Bag

A Bag is an unordered collection of tuples. Duplicate tuples are permitted within a bag. Bags are enclosed in curly braces {...} containing comma-separated tuples:

\[ \text{Bag Representation:} \quad \{ t_1, t_2, t_3, \dots, t_n \} = \{ (v_{11}, v_{12}), (v_{21}, v_{22}), \dots \} \]

Verbal description: A bag is an unordered collection of tuples enclosed in curly braces, analogous to an unindexed database table or relation partition. The GROUP operator produces a bag for each group key.

Example:

{ (1, 'Europe', 'Snacks'), (2, 'Asia', 'Milk'), (3, 'Asia', 'Groceries') }

Bag vs. Relation: In Pig, a relation (the result of LOAD or any operator) and a bag are conceptually both unordered collections of tuples. However, they differ in practice: a relation is a top-level construct that you can operate on directly, while a bag must be contained inside a relation (e.g., as the nested bag inside a grouped tuple). You cannot create a relation from a bag literal directly — A = {(1,2),(3,4)}; is an error.

3. Map

A Map is a collection of key-value pairs, where each key must be a unique string (chararray) and the value can be of any data type. Maps are enclosed in square brackets [...], with keys and values separated by a hash # symbol:

\[ \text{Map Representation:} \quad [ k_1 \# v_1, k_2 \# v_2, \dots, k_m \# v_m ] \]

Verbal description: A map is a set of key-value pairs enclosed in square brackets, where key and value are separated by a hash character. Keys are always chararray (strings); values can be any type.

Example:

[ 'id'#1, 'name'#'alpha', 'salary'#10000 ]

Pitfall — Map key types: Map keys must always be chararray (strings). You cannot use int or other types as map keys. Values can be any type. Also, the # separator is unique to Pig — do not confuse it with JSON's : notation.

6.4.3 Mathematical and Structural Representations of Complex Types

In formal database terms, Pig's complex data types correspond directly to relational algebra components:

  • A relation \(R\) in Pig Latin is represented as a Bag of Tuples:

\[ R = \{ t \mid t = (x_1, x_2, \dots, x_d) \} \] where each element \(x_i\) belongs to domain \(D_i\) (the data type of field \(i\)).

  • When a dataset is grouped by a key attribute \(k\), Pig constructs a grouped relation containing nested bags:

\[ R_{\text{grouped}} = \{ (k_A, \{ t \in R \mid t.\text{key} = k_A \}), (k_B, \{ t \in R \mid t.\text{key} = k_B \}) \} \] where each unique key \(k_A\) is paired with a nested bag containing all matching tuples.

Worked example — Grouping sales by region:

Given the relation:

R = { (1, 'Europe', 743980.08), (2, 'Asia', 440000.00), (3, 'Europe', 5286522.78) }

After GROUP R BY region:

R_grouped = {
  ('Europe', { (1, 'Europe', 743980.08), (3, 'Europe', 5286522.78) }),
  ('Asia',   { (2, 'Asia', 440000.00) })
}

Each group key is paired with a bag of all tuples sharing that key. The AVG(revenue) aggregate then operates over each nested bag.

Exam note: Exam questions frequently require constructing exact syntax representations for Tuples (...), Bags { (...), (...) }, and Maps ['key'#value] from raw record descriptions. Practice writing these from plain-text data descriptions.

6.4.4 Student Questions and Answers

Q: What is the structural difference between a Tuple and a Bag in Apache Pig?

A: A Tuple is a single ordered list of individual fields enclosed in parentheses (...), corresponding to a single row. A Bag is an unordered collection of multiple Tuples enclosed in curly braces {...}, corresponding to a set of rows or a table. Think of a Tuple as one record and a Bag as the full dataset (or a group within the dataset).

Q: How are key-value pairs represented inside a Pig Map data type?

A: A Map is enclosed in square brackets [...]. Each key must be a string chararray separated from its associated value by a hash # symbol, such as ['name'#'alpha', 'role'#'admin']. The key is always a string; the value can be any Pig type.

6.5 Pig Data Transformation Language: Loading, Inspected Data, and Output

6.5.1 The LOAD Statement and Positional versus Named Schemas

Hook: Before you can transform data, you need to bring it into Pig's world. The LOAD statement is the front door — and how you define the schema at the door determines how easily you can work with the data inside.

To bring external file data into Apache Pig for processing, developers use the LOAD statement. Executing a LOAD statement defines a Relation (the Pig term for a tabular dataset handle — a name you use to refer to the data in subsequent operations).

Positional Loading (No Schema)

If data is loaded without column definitions:

sales = LOAD 'sales.csv';

Pig assigns default positional variables to fields: \$0 for the first column, \$1 for the second column, \$2 for the third column, and so on. All fields default to bytearray type.

Pitfall — Positional loading hides errors: Without an explicit schema, Pig cannot detect type mismatches. A corrupted value like 'abc' in a numeric column will silently become null when used in arithmetic, rather than being caught at load time. Always prefer named schemas.

Named Loading with Explicit Schema

Developers can specify column names and primitive data types using the AS clause:

sales = LOAD 'sales.csv' AS (
    index: int,
    region: chararray,
    item_type: chararray,
    units_sold: int,
    unit_cost: float,
    unit_price: float
);

Once loaded with a schema, fields can be referenced directly by name (e.g., units_sold) or by positional offset (\$3). Named references are clearer and less error-prone.

6.5.2 Delimiter Handling using PigStorage

By default, Pig expects input files to be tab-delimited (\t). When loading files delimited by other characters (such as comma-separated CSV files), developers must specify the PigStorage deserializer using the USING clause:

sales = LOAD 'sales.csv' 
USING PigStorage(',') 
AS (
    index: int,
    region: chararray,
    item_type: chararray,
    units_sold: int,
    unit_cost: float,
    unit_price: float
);

PigStorage is the Swiss Army knife of loaders: PigStorage is Pig's default load/store function. It reads and writes delimited text files. The default delimiter is tab (\t), but you can pass any single character as an argument. Other built-in loaders include JsonLoader (for JSON files), AvroStorage (for Avro files), and ParquetLoader (for Parquet files).

6.5.3 Inspecting Relations with DESCRIBE and DUMP

Pig Latin provides diagnostic operators to inspect relation schemas and data contents during Grunt shell sessions:

  1. DESCRIBE relation_name;: Displays the schema, field names, and data types of a relation without scanning file data (instant — no MapReduce job):
grunt> DESCRIBE sales;
-- Output: sales: {index: int, region: chararray, item_type: chararray, units_sold: int, unit_cost: float, unit_price: float}
  1. DUMP relation_name;: Triggers MapReduce job execution, reads relation data, and prints the formatted bag of tuples directly to the terminal screen:
grunt> DUMP sales;
-- Output:
-- (1,Europe,Snacks,4876,97.44,152.58)
-- (2,Central America and the Caribbean,Baby Food,2921,159.42,255.28)
-- (3,Europe,Office Supplies,8118,524.96,651.21)

Pitfall — DUMP triggers execution: DESCRIBE is instant (metadata only). DUMP triggers a full MapReduce job on the cluster (in MapReduce mode). Avoid using DUMP on large datasets — use LIMIT first: DUMP (LIMIT sales 10);

6.5.4 Storing Transformed Data into Folders using STORE

To persist a processed relation to storage, developers use the STORE statement:

STORE sales INTO '/output/sales_processed' USING PigStorage(',');

Critical HDFS Architecture Rule: The target destination specified in STORE relation INTO 'folder_path' must always be a folder directory, never a single file name. Because MapReduce processes data across multiple parallel reducer tasks in a distributed cluster, each reducer writes its assigned output partition into a separate file (part-r-00000, part-r-00001, part-r-00002, ...) inside the specified target folder. Attempting STORE sales INTO '/output/result.csv' will create a directory called result.csv, not a single file.

6.5.5 Worked Example: Complete Ingestion Pipeline on Sales Dataset

Full walkthrough — from CSV to HDFS:

Consider a dataset containing raw mock sales records stored in sales.csv:

1,Australia and Oceania,Snacks,4876,97.44,152.58
2,Central America and the Caribbean,Baby Food,2921,159.42,255.28
3,Europe,Office Supplies,8118,524.96,651.21

The complete Pig Latin script to load, inspect, and persist this dataset:

-- Step 1: Load CSV data with explicit schema using PigStorage
sales = LOAD 'sales.csv' 
USING PigStorage(',') 
AS (
    index: int,
    region: chararray,
    item_type: chararray,
    units_sold: int,
    unit_cost: float,
    unit_price: float
);

-- Step 2: Print schema to confirm field mapping
DESCRIBE sales;
-- Output: sales: {index: int, region: chararray, item_type: chararray, units_sold: int, unit_cost: float, unit_price: float}

-- Step 3: Write processed relation to HDFS output directory
STORE sales INTO 'output/sales_ingested' USING PigStorage(',');

What happens under the hood: Pig parses the script, builds a logical plan (no execution yet), and when STORE is encountered in batch mode, compiles the plan into MapReduce jobs that read from sales.csv, apply the schema, and write to the output directory.

6.5.6 Student Questions and Answers

Q: Why does Pig require specifying a folder directory instead of a single output file path in the STORE statement?

A: In Hadoop MapReduce, data processing is parallelized across multiple reducer containers. Each reducer writes its partition of the output relation to a separate file (e.g., part-r-00000, part-r-00001) inside the destination directory. Therefore, output destinations in distributed big data frameworks are always directories, not single files. The number of output files equals the number of reducers used.

Q: What happens if a dataset is loaded without specifying column names in the LOAD statement?

A: Pig loads the data without schema metadata, assigning uninterpreted bytearray types to all fields. Columns must then be accessed using zero-based positional notation (\$0, \$1, \$2). This is called positional loading — it works but hides type errors until runtime.

6.6 Relational & Flow Operators in Pig Latin

6.6.1 Projection and Derived Column Creation with FOR EACH ... GENERATE

Hook: You have a relation with 50 columns but only need 3. Or you need to compute a new column from existing ones. FOR EACH ... GENERATE is Pig's universal tool for reshaping data — it is the equivalent of SQL's SELECT clause.

The FOR EACH ... GENERATE statement iterates row-by-row over a relation, projecting specific columns or creating new calculated attributes. Think of it as saying: "For each row in this dataset, generate a new row with these fields."

Column Projection

To extract a subset of columns (such as index, region, and item_type):

trimmed_sales = FOREACH sales GENERATE index, region, item_type;

Or using positional offsets:

trimmed_sales = FOREACH sales GENERATE \$0, \$1, \$2;

Positional Range Shortcuts

Pig Latin supports positional range shortcuts to simplify column selection:

  • \$0..\$5: Selects all columns from index \$0 through index \$5 inclusive.
  • ..\$5: Selects all columns from the first field up to index \$5.
  • \$3..: Selects all columns from index \$3 through the final column of the relation.

FOREACH ... GENERATE vs. SQL SELECT: Both project and compute columns. The key difference is that FOREACH operates on one relation at a time (you cannot join inside a FOREACH). For multi-relation operations, use JOIN, COGROUP, or CROSS first, then FOREACH on the result.

6.6.2 Mathematical Calculations: Revenue and Profit Formulas

Developers can compute new mathematical fields within FOR EACH ... GENERATE projections.

1. Revenue Calculation

Revenue for a sales row is calculated as units sold multiplied by selling price per unit:

\[ \text{Revenue} = \text{Units Sold} \times \text{Selling Price} \]

Verbal description audit trail: Units sold multiplied by selling cost gives the total revenue for that row.

Mathematical formulation: \[ R_i = U_i \times P_i \] where \(R_i \in \mathbb{R}_{\ge 0}\) is the row revenue, \(U_i \in \mathbb{Z}_{\ge 0}\) is the number of units sold, and \(P_i \in \mathbb{R}_{\ge 0}\) is the selling price per unit.

Pig Latin implementation:

sales_with_revenue = FOREACH sales GENERATE 
    \$0..\$5, 
    (units_sold * unit_price) AS revenue: float;

Numerical spot-check — Row 1 (Australia, Snacks): \(R_1 = 4876 \times 152.58 = 743,980.08\)

Verifying: \(4876 \times 150 = 731,400\); \(4876 \times 2.58 = 12,579.08\); total = \(743,979.08\) (rounding). Revenue = \$743,980.08

2. Profit Calculation

Profit per row is calculated as units sold multiplied by the difference between selling price and unit cost:

\[ \text{Profit} = \text{Units Sold} \times (\text{Selling Price} - \text{Unit Cost}) \]

Verbal description audit trail: Selling price minus cost price gives unit profit, multiplied by units sold gives total profit.

Mathematical formulation: \[ \Pi_i = U_i \times (P_i - C_i) \] where \(\Pi_i \in \mathbb{R}\) is the total profit for row \(i\), and \(C_i \in \mathbb{R}_{\ge 0}\) is the unit manufacturing cost.

Pig Latin implementation:

sales_with_profit = FOREACH sales GENERATE 
    \$0..\$5, 
    (units_sold * (unit_price - unit_cost)) AS profit: float;

6.6.3 Row Filtering with FILTER (Numeric, Comparison, and Regex)

The FILTER operator selects tuples from a relation that satisfy a logical condition (equivalent to the SQL WHERE clause). Only tuples for which the condition evaluates to true are retained.

Numeric Filtering To select records where revenue exceeds \$100,000:

high_revenue_sales = FILTER sales_with_revenue BY revenue > 100000.0;

String and Regular Expression Filtering To select records where item_type contains the substring 'Baby':

baby_products = FILTER sales BY item_type MATCHES '.*Baby.*';

FILTER supports all comparison and logical operators: ==, !=, <, >, <=, >=, AND, OR, NOT, and MATCHES (regex). Combine conditions with AND/OR: FILTER sales BY revenue > 50000.0 AND region == 'Europe';

6.6.4 Grouping with GROUP BY and Nested Bag Formats

The GROUP operator collects all tuples in a relation that share identical values for a specified grouping key.

grouped_by_region = GROUP sales_with_revenue BY region;

Output Structure of GROUP

When a relation is grouped, Pig transforms the flat relation into a new relation containing two top-level fields:

  1. group: The key value shared by the group (e.g., 'Europe').
  2. A nested Bag named after the original relation (sales_with_revenue), containing all full tuples matching that key.

Schema structure produced by GROUP:

grouped_by_region: {
    group: chararray, 
    sales_with_revenue: {
        (index: int, region: chararray, item_type: chararray, units_sold: int, unit_cost: float, unit_price: float, revenue: float)
    }
}

DUMP visual output snippet:

('Europe', { (1, 'Europe', 'Snacks', 4876, 97.44, 152.58, 743980.08), (3, 'Europe', 'Office Supplies', 8118, 524.96, 651.21, 5286522.78) })
('Asia', { (2, 'Asia', 'Milk', 2000, 130.00, 220.00, 440000.00) })

Intuition — GROUP creates a "bag of bags": Imagine sorting a deck of cards by suit. After grouping, you have four piles (hearts, diamonds, clubs, spades), each containing multiple cards. In Pig, GROUP creates one "pile" (bag) per unique key value, and each pile contains all the tuples that share that key.

6.6.5 Grouped Aggregations: Average, Sum, Min, Max

Once data is grouped, developers combine FOR EACH ... GENERATE with built-in aggregate functions (AVG, SUM, MIN, MAX, COUNT) to compute summary metrics per group.

To compute average revenue per region:

\[ \text{AVG}(\text{Revenue}_{\text{region}}) = \frac{1}{N_{\text{region}}} \sum_{j=1}^{N_{\text{region}}} R_{j,\text{region}} \]

where \(N_{\text{region}}\) is the number of tuples in the grouped bag for that region.

avg_revenue_per_region = FOREACH grouped_by_region GENERATE 
    group AS region, 
    AVG(sales_with_revenue.revenue) AS avg_revenue: double;

Aggregate function syntax: After GROUP BY key, you access the nested bag using bag_name.field_name (e.g., sales_with_revenue.revenue). The aggregate function operates over all values of that field within the bag. Built-in aggregates: AVG(), SUM(), MIN(), MAX(), COUNT() (counts non-null values), COUNT_STAR() (counts all values including nulls).

6.6.6 Relational Operations: JOIN, ORDER BY, LIMIT, DISTINCT, SPLIT, SAMPLE, UNION, and COGROUP

1. JOIN

Combines tuples from two or more relations based on matching key values:

joined_data = JOIN relation1 BY id, relation2 BY customer_id;

Supports LEFT OUTER, RIGHT OUTER, and FULL OUTER joins. By default, JOIN performs an inner join (only matching rows are kept).

2. ORDER BY

Sorts a relation based on one or more sort keys in ascending (ASC, the default) or descending (DESC) order:

sorted_sales = ORDER sales_with_revenue BY revenue DESC;

3. LIMIT

Restricts the output relation to a specified maximum number of tuples:

top_10_sales = LIMIT sorted_sales 10;

4. DISTINCT

Removes duplicate tuples from a relation (operates on the entire tuple, not individual fields):

unique_regions = DISTINCT (FOREACH sales GENERATE region);

5. SPLIT

Partitions a single relation into two or more relations based on conditional expressions. Conditions do not need to be mutually exclusive (a tuple can appear in multiple output relations):

SPLIT sales_with_revenue INTO 
    low_revenue IF revenue < 30000.0,
    medium_revenue IF (revenue >= 30000.0 AND revenue < 100000.0),
    high_revenue IF revenue >= 100000.0;

6. SAMPLE

Extracts a random sample fraction \(p \in [0.0, 1.0]\) of tuples from a relation:

sampled_sales = SAMPLE sales 0.1; -- Extracts approximately a 10% random sample

7. UNION

Combines the contents of two or more relations into a single relation (like SQL UNION ALL — duplicates are kept):

all_sales = UNION relation1, relation2;

8. COGROUP

Groups tuples from two or more relations sharing common keys, producing independent nested bags for each input relation:

cogrouped_data = COGROUP customers BY id, orders BY customer_id;

COGROUP vs. JOIN: JOIN produces a flat result — each matching pair becomes one row. COGROUP produces a nested result — each unique key gets a tuple containing the key and separate bags from each input relation. Use COGROUP when you need to process each relation's matching tuples independently; use JOIN when you want a flat combined row.

6.6.7 Pitfalls: Non-Deterministic LIMIT without ORDER BY

Classic exam pitfall: A developer writes top_10 = LIMIT sales 10; expecting the 10 highest-revenue records. Instead, they get 10 arbitrary records. The fix: always ORDER BY before LIMIT.

If a developer executes:

-- INCORRECT TOP 10 PIPELINE
top_10_raw = LIMIT sales_with_revenue 10;

Pig will return an arbitrary, non-deterministic set of 10 records based on whichever YARN mapper finished reading file splits first. To reliably extract top records, developers must sort the dataset with ORDER BY prior to calling LIMIT:

-- CORRECT TOP 10 PIPELINE
sorted_sales = ORDER sales_with_revenue BY revenue DESC;
top_10_revenue = LIMIT sorted_sales 10;

Exam note: LIMIT without ORDER BY produces non-deterministic results in a distributed system. Always sort first if you need the true top-N records.

6.6.8 Worked Walkthrough: End-to-End Sales Data Processing Script

Complete pipeline — from raw CSV to top regional summaries:

The following complete script demonstrates loading sales records, calculating revenue, filtering high-value sales, grouping by region, computing regional average revenues, sorting regions, and storing the top output:

-- Step 1: Load raw sales data
sales = LOAD 'sales.csv' 
USING PigStorage(',') 
AS (
    index: int,
    region: chararray,
    item_type: chararray,
    units_sold: int,
    unit_cost: float,
    unit_price: float
);

-- Step 2: Compute calculated revenue field
sales_rev = FOREACH sales GENERATE 
    region, 
    item_type, 
    units_sold, 
    (units_sold * unit_price) AS revenue: float;

-- Step 3: Filter records with revenue over \$50,000
filtered_sales = FILTER sales_rev BY revenue > 50000.0;

-- Step 4: Group filtered sales by region
grouped_sales = GROUP filtered_sales BY region;

-- Step 5: Compute average revenue per region
regional_summary = FOREACH grouped_sales GENERATE 
    group AS region, 
    AVG(filtered_sales.revenue) AS avg_revenue: double;

-- Step 6: Order summary by average revenue descending
sorted_summary = ORDER regional_summary BY avg_revenue DESC;

-- Step 7: Limit output to top 5 regions
top_5_regions = LIMIT sorted_summary 5;

-- Step 8: Store output to HDFS
STORE top_5_regions INTO 'output/top_5_regional_revenue' USING PigStorage(',');

What happens under the hood: This 8-step Pig script compiles into approximately 2-3 MapReduce jobs (one for the filter/group/aggregate, one for the sort, possibly one for the final store). Pig's optimizer may combine adjacent steps into fewer jobs via multiquery execution.

6.6.9 Student Questions and Answers

Q: Why will executing LIMIT 10 directly on an unsorted relation fail to return the top 10 highest-value records in Pig?

A: LIMIT simply truncates the relation to the first 10 records encountered during execution. Because distributed MapReduce mappers process data splits in arbitrary order, the returned 10 rows are non-deterministic — they depend on which mapper finishes first, not on the data values. To extract the true top 10 records, the relation must first be sorted using ORDER BY revenue DESC.

Q: How does COGROUP differ from JOIN in Pig Latin?

A: JOIN computes a flat relational join, emitting combined tuples where join keys match. COGROUP groups tuples from multiple input relations independently by key, producing a tuple containing the key and separate nested bags for each input relation. With COGROUP, you can process each relation's matching tuples independently in a subsequent FOREACH; with JOIN, you get a single flat row per match.

6.7 Built-In Functions and User-Defined Functions (UDFs) in Pig

6.7.1 Built-in Date, Time, and Statistical Utilities

Hook: Pig comes with a rich library of built-in functions so you rarely need to write custom code. But what happens when your business logic is too specialized for any built-in? That's where User-Defined Functions (UDFs) come in.

Apache Pig provides extensive libraries of built-in functions across several categories:

  • Date and Time Functions: AddDuration, CurrentTime, DaysBetween, GetYear, GetMonth, GetDay, ToDate. Useful for time-series analysis and log processing.
  • Statistical/Math Functions: AVG, SUM, MIN, MAX, COUNT, COUNT_STAR, STDEV, VARIANCE, ABS, CEIL, FLOOR, ROUND, SQRT, LOG.
  • String Functions: CONCAT, SUBSTRING, LOWER, UPPER, TRIM, INDEXOF, REPLACE, STRSPLIT, TOKENIZE, SIZE.
  • Conversion Functions: TOTUPLE, TOBAG, TOMAP, TOP, FLATTEN.
  • I/O Functions: PigStorage (delimited text), JsonLoader/JsonStorage (JSON), AvroStorage (Avro), ParquetLoader/ParquetStorer (Parquet), OrcStorage (ORC).

FLATTEN — a critical operator: FLATTEN removes one level of nesting from bags and tuples. When you GROUP BY and then want to process the nested bag, FLATTEN unwraps it. For example, FLATTEN(TOKENIZE(line)) splits a text line into individual words, each as a separate tuple.

6.7.2 Extending Pig with Custom Java UDFs

When complex business logic (such as proprietary encryption algorithms, custom statistical modeling, or domain-specific differential calculations) cannot be expressed using built-in Pig functions, developers can extend Pig using User-Defined Functions (UDFs).

4-step Java UDF workflow:

  1. Extend Pig's base Java class org.apache.pig.EvalFunc<T>.
  2. Override the exec(Tuple input) method with custom transformation logic.
  3. Package the compiled Java code into a .jar file.
  4. Register and invoke the UDF inside the Pig Latin script:
-- Step 1: Register the compiled custom Java UDF JAR
REGISTER /path/to/custom_udf.jar;

-- Step 2: Define an alias for the custom function
DEFINE DifferentialCalc com.example.pig.udf.DifferentialCalc();

-- Step 3: Execute the UDF inside a FOREACH projection
transformed_data = FOREACH sales GENERATE 
    index, 
    DifferentialCalc(units_sold, unit_cost) AS diff_val;

UDF types in Pig (four kinds):

  1. Eval functions — take one or more expressions, return a value (e.g., UPPER, MAX). Most UDFs are eval functions.
  2. Filter functions — a special eval function that returns true/false, used in FILTER statements.
  3. Load functions — specify how to read data from external storage (e.g., PigStorage, JsonLoader).
  4. Store functions — specify how to write data to external storage.

Pitfall — UDF case sensitivity: Function names in Pig are case sensitive because they map to Java class names. REGISTER and DEFINE are keywords (not case sensitive), but the function alias and fully-qualified class name must match exactly.

6.7.3 Student Questions and Answers

Q: How does a developer incorporate custom Java processing logic into an Apache Pig pipeline when standard built-in functions are insufficient?

A: The developer writes a custom Java class extending EvalFunc, overrides the exec() method, compiles the class into a JAR file, registers the JAR in the Pig script using REGISTER /path/to/jar, creates a short alias with DEFINE alias com.package.ClassName(), and invokes the alias inside a FOREACH ... GENERATE statement. This 4-step workflow (extend, override, package, register+define) is the standard pattern for all Java UDFs.

6.8 Apache Hive Data Warehousing Fundamentals & Architecture

6.8.1 Origins at Facebook and Data Warehousing Abstraction

Hook: Facebook had petabytes of user activity logs and thousands of analysts who knew SQL — but nobody wanted to write Java MapReduce. Sound familiar? Hive was Facebook's answer: give analysts a SQL interface over HDFS and let the compiler translate queries into MapReduce jobs.

Apache Hive was created at Facebook around 2006 to provide a data warehousing layer on top of Hadoop. At Facebook, data analysts and infrastructure teams managed petabyte-scale analytics datasets, but the vast majority of personnel were trained in SQL rather than Java MapReduce. The project was led by Jeff Hammerbacher's data team and became a top-level Apache project in 2010.

Hive introduces HiveQL (HQL), a declarative SQL-dialect that allows users to create tables, define schemas, and query HDFS datasets using familiar relational SQL queries.

Hive's position in the architecture: Hive is a Data Warehouse system, not a database. Key differences:

  • Hive does not store data itself — data lives in HDFS files.
  • Hive stores metadata (table definitions, schemas, locations) in a separate metastore database.
  • Hive compiles queries into MapReduce (or Tez/Spark) jobs for execution — it is a query engine, not a storage engine.
  • Hive uses schema-on-read — the schema is applied when data is read, not when it is written. This is opposite to traditional RDBMS (schema-on-write).

Real-world: Hive is positioned as a Data Warehouse system. While Pig is used for procedural data transformation (ETL), Hive is used for structured data warehousing, schema enforcement, and analytical reporting across enterprise data lakes.

Comparison — Pig vs. Hive:

Dimension Apache Pig Apache Hive
Language Pig Latin (procedural) HiveQL (declarative, SQL-like)
Primary use ETL data transformation Data warehousing, BI reporting
Target users Engineers, data scientists Analysts, BI tools
Schema Schema-on-read, optional Schema-on-read, enforced via metastore
JDBC/ODBC No Yes (via HiveServer2)
Storage Reads from HDFS (no storage) Manages tables over HDFS via metastore

6.8.2 Hive Architectural Components: Driver, Compiler, and Execution Engine

The internal architecture of Apache Hive comprises four core services:

[ User Client / CLI / JDBC / ODBC ]
           │
           ▼
     [ Hive Driver ] ◄────────► [ Metastore (Derby / MySQL) ]
           │
           ▼
    [ Hive Compiler (Parser → Optimizer → Plan) ]
           │
           ▼
[ Execution Engine (MapReduce / Tez / Spark) ]
           │
           ▼
    [ Hadoop Cluster / HDFS ]
  1. Driver: Manages the lifecycle of a HiveQL statement, receiving incoming queries from clients, maintaining session context, and coordinating with the Compiler and Execution Engine. Think of the Driver as the conductor of an orchestra — it does not play instruments but ensures every section comes in at the right time.
  1. Compiler: Parses HiveQL syntax, performs semantic checks against table schemas stored in the Metastore, generates a logical execution plan, and optimizes the plan into a Directed Acyclic Graph (DAG) of MapReduce jobs. The compiler uses a cost-based optimizer (introduced in Hive 0.14) to choose the most efficient execution strategy.
  1. Execution Engine: Submits generated MapReduce DAG tasks to YARN and monitors task execution until final query results are returned. Modern Hive supports three execution engines:
  • MapReduce (mr) — the original, disk-based engine
  • Tez — a DAG engine that avoids writing intermediate results to HDFS (faster)
  • Spark — in-memory processing engine
  1. Metastore: Stores table schema definitions, column data types, table locations in HDFS, and serialization/deserialization (SerDe) rules in a relational database. The metastore is the catalog that tells Hive where data lives and how to interpret it.

6.8.3 HiveQL to MapReduce Compilation DAG

Walkthrough — How a SQL query becomes MapReduce jobs:

When a user submits a HiveQL query containing aggregations and joins:

SELECT region, SUM(revenue) AS total_revenue
FROM sales_db.sales_table
WHERE revenue > 10000.0
GROUP BY region
ORDER BY total_revenue DESC;

The Hive Compiler converts the SQL statement into a multi-stage MapReduce DAG:

  1. Map Stage: Mappers scan table files in HDFS, evaluate the WHERE revenue > 10000.0 filter, extract (region, revenue) key-value pairs, and execute local combiner aggregations (partial sums per region on each mapper).
  1. Shuffle and Reduce Stage 1: Intermediate key-value pairs shuffle to reducers partitioned by region. Reducers calculate SUM(revenue) per region, producing regional totals.
  1. Reduce Stage 2: A final single reducer receives all regional totals, sorts records by total_revenue DESC, and writes the result to HDFS.

The number of MapReduce jobs depends on the query complexity. A simple SELECT * is one job; a query with GROUP BY, ORDER BY, and a JOIN may require 2-3 jobs chained together.

Exam note: Be prepared to sketch the Hive architecture diagram (Client → Driver → Compiler → Execution Engine → HDFS, with Metastore connected to Driver) and explain the role of each component. Also know how a SQL query gets compiled into a MapReduce DAG.

6.8.4 Student Questions and Answers

Q: How does Apache Hive differ fundamentally from Apache Pig in enterprise big data pipelines?

A: Apache Pig is a procedural data-flow scripting tool (using Pig Latin) designed primarily for ETL data transformation pipelines — you define each step explicitly. Apache Hive is a declarative data warehousing framework (using HiveQL SQL) designed for structured data querying, schema management, and business intelligence reporting over HDFS — you describe the desired result. Pig is for engineers building pipelines; Hive is for analysts running queries.

Q: What role does the Hive Compiler play when a HiveQL query is submitted?

A: The Hive Compiler receives the parsed SQL query, queries the Metastore to verify table schemas and file paths, constructs an optimized logical plan, and translates the relational query into a Directed Acyclic Graph (DAG) of physical MapReduce (or Tez/Spark) jobs for cluster execution. The optimizer chooses the most efficient plan — for example, pushing filters down to the map stage to reduce data shuffle.

6.9 Hive Metastore Architectures

6.9.1 Metastore Concept: Separation of HDFS Data and RDBMS Metadata

Hook: Hive tables feel like database tables, but the actual data lives in flat files on HDFS. So where does Hive keep the information about what columns exist, what types they are, and where the files are? The answer is the Metastore — a separate database that acts as Hive's catalog.

A foundational architectural principle of Apache Hive is the strict separation of Data and Metadata:

  • Data (Raw File Content): Stored in distributed HDFS files (e.g., CSV, ORC, Parquet files located at hdfs://namenode:9000/user/hive/warehouse/sales_db.db/sales_table). Hive never modifies the raw data files during queries — it reads them as-is.
  • Metadata (Schema Definitions): Stored separately in a Relational Database Management System (RDBMS) called the Hive Metastore. Metadata includes table names, column names, column data types, table owner, partition keys, HDFS storage locations, and SerDe (Serializer/Deserializer) rules.

Why separate data from metadata? This separation is what makes Hive flexible. You can:

  • Define multiple schemas over the same raw data files (schema-on-read)
  • Drop a table without losing the underlying HDFS data (for external tables)
  • Share the same metastore across multiple query engines (Hive, Spark SQL, Presto, Impala)
  • Change the schema without moving or rewriting data files

Configuring metastore — Embedded Derby vs. Remote MySQL:

Embedded Derby (default, single-user):

<!-- hive-site.xml — embedded Derby (default) -->
<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
</property>

Result: Metastore stored in local ./metastore_db/ directory. Only one Hive terminal can be open at a time.

Remote MySQL (production, multi-user):

<!-- hive-site.xml — remote MySQL metastore -->
<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://dbserver:3306/hive_metastore?createDatabaseIfNotExist=true</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>hive_user</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>hive_password</value>
</property>

Result: Metastore stored in MySQL database on a dedicated server. Hundreds of concurrent Hive sessions can connect simultaneously.

6.9.2 Embedded Metastore using Apache Derby

By default, Apache Hive includes an Embedded Metastore powered by Apache Derby, an embedded Java relational database.

Embedded Derby Characteristics

  • Storage Location: Writes metadata files to a local disk directory (./metastore_db) on the client machine.
  • Process Execution: Derby runs inside the same JVM process as the Hive CLI client.
  • Critical Limitation: Derby supports only a single active connection at a time. If one user opens a Hive CLI session using Derby, no other user or client application can connect to Hive simultaneously. Attempting a second connection produces a lock error.

Primary Use Case: Embedded Derby is suitable strictly for local testing, initial learning, and single-user script development.

Pitfall — "Why can't I open another Hive terminal?" This is the most common error when using the default embedded Derby metastore. If you have one hive shell open and try to open another, Derby will throw a lock error because it only supports one connection. The fix: switch to a remote metastore (MySQL) for any multi-user scenario.

6.9.3 Remote and External Metastore using MySQL/RDBMS

To support enterprise multi-tenant production clusters, Hive must be configured with a Remote / External Metastore.

Remote MySQL Metastore Characteristics

  • Storage Location: Metadata resides in a dedicated external multi-user RDBMS (such as MySQL, PostgreSQL, or Oracle).
  • Network Access: Hive clients connect to a centralized Hive Metastore Service daemon via Thrift RPC network protocols.
  • Multi-User Concurrency: Hundreds of concurrent users, BI tools (Tableau, PowerBI), and automated scripts can query Hive simultaneously without database lock conflicts.
Feature Embedded Metastore (Derby) Remote/External Metastore (MySQL/PostgreSQL)
Database Engine Embedded Apache Derby External Relational Database (MySQL, Postgres, Oracle)
JVM Execution Runs inside the local Hive client JVM process Runs in a separate dedicated database server process
Concurrency Limit Strictly single-user (1 concurrent session) Multi-tenant concurrent sessions (hundreds of users)
Target Environment Local testing, learning, initial setup Production enterprise clusters and multi-user data lakes

Exam note: Be prepared to explain why embedded Derby metastores fail in production environments (single-connection lock restriction) and why remote MySQL metastores are required for multi-tenant enterprise data lakes. The metastore does not store actual data — it stores only the catalog of where data lives and how to interpret it.

6.9.4 Student Questions and Answers

Q: Why is the default Apache Derby metastore unsuitable for production enterprise deployments of Apache Hive?

A: Apache Derby is an embedded database that accepts only a single active client connection at a time. In enterprise production environments where multiple users, scripts, and BI tools query Hive concurrently, Derby locks the metastore database, preventing multi-tenant access. Production deployments require a remote metastore using MySQL or PostgreSQL, which can handle hundreds of concurrent connections.

Q: Where is actual table data stored versus where table schema definitions are stored in Apache Hive?

A: Actual raw table data files (CSV, Parquet, ORC) are stored in distributed HDFS directory paths (e.g., /user/hive/warehouse/sales_db.db/sales_table/). Table schema metadata (column names, data types, partition keys, file locations, SerDe rules) is stored separately in the relational Hive Metastore database (Derby for local testing, MySQL for production). This strict separation of data and metadata is a core architectural principle of Hive.

6.10 Course Administration and Practical Setup Logistics

6.10.1 Cluster Setup Effort and Time Investment Expectations

Intuition — Setting up Hadoop is not like installing a desktop app: Building a working pseudo-distributed Hadoop environment is more like assembling a car from parts — every component (HDFS, YARN, MapReduce, Pig, Hive) has its own configuration files, Java dependencies, and environment variables. One wrong path or missing JAR and the whole system fails silently.

Setting up enterprise big data software components locally requires substantial hands-on effort. Building a complete functional single-node pseudo-distributed Hadoop environment (HDFS, YARN, MapReduce, Sqoop, Flume, Pig, and Hive) involves extensive configuration file editing (core-site.xml, hdfs-site.xml, yarn-site.xml, hive-site.xml), environment variable pathing, and Java dependency debugging.

Pedagogical Expectations:

  • Setting up core Hadoop (HDFS and YARN) for the first time requires approximately 8 hours of dedicated troubleshooting.
  • Setting up Apache Pig requires approximately 3 additional hours.
  • Setting up Apache Hive and configuring the metastore can require up to 16 hours of troubleshooting before achieving a fully functional setup.
  • Overall Course Workload: As a 4-credit intensive course, students are expected to invest approximately 120 total hours across the semester (30 hours per credit) in self-study, hands-on lab environment setup, and script execution.

Professor's warning — start early: Setting up complex tools like Hive often involves long hours of frustrating error messages (port conflicts, missing MySQL JDBC connector JARs, metastore schema initialization errors) before achieving that single breakthrough moment when all daemons initialize cleanly. Students are urged not to accumulate setup tasks until the end of the term. The setup itself is a learning experience — debugging environment issues teaches you how the components connect.

6.10.2 Assignment Structure: Group versus Individual Evaluation

In response to student feedback regarding past group assignment challenges across mixed student cohorts:

  • Past Friction: Randomly assigned multi-cohort project groups experienced uneven student participation, communication barriers, and scheduling conflicts.
  • Policy Flexibility: For upcoming major assignments, students will have the option to complete project deliverables either in self-selected collaborative groups or individually.

6.10.3 Scheduling Extra Live Hands-on Sessions

To reinforce theoretical concepts with practical terminal command walkthroughs, an extra hands-on demonstration class focusing on Hive setup, table creation, and HiveQL execution was scheduled based on student consensus for Saturday at 8:00 PM, followed by the regular Sunday morning session.

6.10.4 Student Questions and Answers

Q: What strategy is recommended for managing the heavy hands-on setup workload required for Hadoop, Pig, and Hive?

A: Students should set up pseudo-distributed Hadoop, Pig, and Hive environments on their personal laptops immediately rather than deferring setup until exam week. Allocating dedicated setup hours incrementally prevents last-minute configuration bottlenecks. Each component builds on the previous one (HDFS → YARN → Pig → Hive), so getting HDFS working first unlocks the rest.

Exam Guidance Summary

Exam note: The following points distill the most examinable material from this lecture. Review each item and ensure you can explain it in 2-3 sentences.

  • MapReduce Usability & Motivation: Be prepared to explain why Yahoo and Facebook developed Pig and Hive in 2004 to eliminate raw Java MapReduce boilerplate. Know the declarative (Hive) vs. procedural (Pig) distinction.
  • Pig Execution Modes: Memorize launch flags and filesystem behaviors for Local Mode (pig -x local, local disk, single JVM) versus MapReduce Cluster Mode (pig, HDFS, YARN containers). Know when to use each.
  • Pig Structural Limitations: Understand that Pig has no native storage engine, no background web server/daemon, no remote JDBC interface, and is unsuitable for sub-second real-time OLTP queries.
  • Pig Complex Data Types: Be ready to write precise syntax representations for Tuples (1, 'Europe'), Bags { (1, 'Europe'), (2, 'Asia') }, and Maps ['key'#value]. Know the difference between a Tuple (single ordered record) and a Bag (unordered collection of Tuples).
  • HDFS Output Directories: Remember that STORE relation INTO 'path' always targets directories, not single files, because parallel MapReduce reducers output separate part files (part-r-00000).
  • Pig Operator Syntax: Know syntax and operational mechanics for LOAD, FILTER, FOREACH ... GENERATE, GROUP BY, ORDER BY, LIMIT, SPLIT, SAMPLE, UNION, and COGROUP.
  • Top-N Non-Determinism Pitfall: Understand why calling LIMIT 10 without a preceding ORDER BY col DESC produces non-deterministic, arbitrary records rather than the true top 10. Always sort before limiting.
  • Java UDF Integration: Know the 4-step workflow for custom Java UDFs: extend EvalFunc, override exec(), compile JAR, and execute REGISTER /path/to/jar and DEFINE.
  • Hive Architectural Components: Be ready to sketch and explain the roles of Hive Driver, Compiler, Execution Engine, and Metastore. Know the data flow: Client → Driver → Compiler → Execution Engine → HDFS.
  • Hive Metastore Distinctions: Be ready to compare Embedded Derby metastores (single connection limit, testing only) versus Remote MySQL metastores (multi-tenant concurrent access, production standard).

Key Industry Applications

  • ETL Data Pipelines (Apache Pig):

Tech organizations (such as Yahoo and Twitter) used Pig Latin scripts to write complex Extract, Transform, Load (ETL) data pipelines that ingest web logs, strip corrupted records, compute derived fields, and output cleansed datasets. At its peak, over 80% of Yahoo's MapReduce jobs were generated by Pig Latin scripts. ETL remains a core use case in modern data engineering, though Spark has largely replaced Pig for new pipelines.

  • Enterprise Data Warehousing (Apache Hive):

Organizations (such as Facebook) use Apache Hive as an enterprise data warehouse layer over petabyte-scale HDFS data lakes, allowing business analysts to run SQL queries and integrate SQL-based BI reporting tools (Tableau, PowerBI, Looker). Hive's SQL compatibility makes it the default query engine for data analysts who do not write Java or Python. Major cloud platforms (AWS EMR, Google Dataproc, Azure HDInsight) all offer managed Hive services.

  • Custom Business Logic Execution (Pig UDFs):

Companies package proprietary algorithms (such as custom fraud detection scoring, domain-specific text parsers, or proprietary encryption routines) into custom Java UDFs registered inside Pig pipelines. UDFs allow Pig to handle business logic that goes beyond standard SQL operations — for example, parsing custom log formats or computing domain-specific risk scores.

  • Multi-Tenant Enterprise Metastore Architecture:

Enterprise cloud data platforms deploy central remote MySQL/PostgreSQL Metastore services to allow hundreds of concurrent users, automated ETL jobs, and query engines (Hive, Spark SQL, Presto, Impala) to share unified table metadata across data lakes. The metastore has become a de facto standard catalog format — even non-Hive engines like Spark SQL and Presto read Hive metastore schemas to discover and query tables.

BDA Lecture 6 notes

Big Data Analytics· postgraduate· 2026-08-01

Sections Breakdown

16.1 Lecture Overview, Progress Tracking, and Hadoop Ecosystem Architecture

Positions Pig and Hive in the Hadoop ecosystem, recaps YARN, Sqoop, and Flume from Lecture 5, and explains the MapReduce usability gap that motivated Yahoo (Pig) and Facebook (Hive).

26.2 Apache Pig Fundamentals, Evolution, and Data Flow Scripting

Pig's origins at Yahoo, the procedural Pig Latin design, productivity gains over Java MapReduce, and the ecosystem shift toward Spark.

36.3 Pig Execution Modes, Architecture, and Grunt Shell CLI

Local vs MapReduce cluster mode, Pig's structural limitations (no storage engine, no server daemon, no OLTP), and the Grunt shell debugging commands.

46.4 Pig Data Model and Data Types

The eight primitive types and the complex structures Tuples, Bags, and Maps, plus their formal relational-algebra representation.

56.5 Pig Data Transformation Language: Loading, Inspected Data, and Output

LOAD with positional vs named schemas, PigStorage delimiters, DESCRIBE and DUMP diagnostics, and folder-based STORE output.

66.6 Relational & Flow Operators in Pig Latin

FOREACH GENERATE, FILTER, GROUP BY, aggregations, JOIN, ORDER BY, LIMIT, DISTINCT, SPLIT, SAMPLE, UNION, COGROUP, and the non-deterministic LIMIT pitfall.

76.7 Built-In Functions and User-Defined Functions (UDFs) in Pig

Pig's built-in function libraries, FLATTEN, and the four-step workflow for extending Pig with custom Java EvalFunc UDFs.

86.8 Apache Hive Data Warehousing Fundamentals & Architecture

Hive's origins at Facebook, the Driver-Compiler-Execution Engine-Metastore architecture, and how HiveQL compiles into MapReduce DAGs.

96.9 Hive Metastore Architectures

The separation of HDFS data from RDBMS metadata, and the embedded Derby vs remote MySQL metastore configurations.

106.10 Course Administration and Practical Setup Logistics

Hands-on setup effort expectations, assignment structure options, and extra live hands-on sessions.

11Exam Guidance Summary

Consolidated exam topics across Pig and Hive: execution modes, data types, STORE directories, operator syntax, LIMIT pitfalls, UDFs, and metastore distinctions.

12Key Industry Applications

Real-world Pig ETL pipelines, Hive data warehousing, custom Java UDF business logic, and multi-tenant metastore architectures.

Postgraduate students in Big Data Analytics

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Apache Pig and Hive Origins and the MapReduce Usability Gap

Must-know: Yahoo created Pig (procedural data-flow) and Facebook created Hive (SQL-like declarative) to bridge the MapReduce usability gap for non-Java developers.

⚠️ Top pitfall: Confusing declarative (SQL/HiveQL — describe what you want) with procedural (Pig Latin — describe how to transform step by step).

Self-check: Which company created Pig and which created Hive? What programming paradigm does each use?

Connects to: 6.2 Apache Pig Fundamentals, Evolution, and Data Flow Scripting, 6.8 Apache Hive Data Warehousing Fundamentals & Architecture

Apache Pig Fundamentals and Pig Latin

Must-know: Pig Latin is procedural (explicit step-by-step pipeline); SQL/HiveQL is declarative (describe the desired result). Pig compiles to disk-bound MapReduce jobs; Spark uses in-memory computation.

⚠️ Top pitfall: Confusing procedural (Pig — you specify HOW) with declarative (SQL/Hive — you specify WHAT).

Self-check: What is the code compression ratio between Java MapReduce and Pig Latin for a typical ETL task?

Connects to: 6.1 Lecture Overview, Progress Tracking, and Hadoop Ecosystem Architecture, 6.3 Pig Execution Modes, Architecture, and Grunt Shell CLI, 6.8 Apache Hive Data Warehousing Fundamentals & Architecture

Pig Execution Modes and Structural Limitations

Must-know: Local mode (pig -x local, single JVM, local disk) vs MapReduce mode (pig, YARN + HDFS). Pig has no storage engine, no web server, no JDBC/ODBC — it is a client-side batch execution framework only.

⚠️ Top pitfall: Assuming Pig can serve real-time queries or that external apps can connect to Pig via JDBC. Pig has no background daemon.

Self-check: What command launches Pig in local mode? What filesystem does it read from?

Connects to: 6.1 Lecture Overview, Progress Tracking, and Hadoop Ecosystem Architecture, 6.2 Apache Pig Fundamentals, Evolution, and Data Flow Scripting

Pig Data Types and Complex Structures

Must-know: Write exact syntax for Tuples (1, 'Europe'), Bags { (1, 'Europe'), (2, 'Asia') }, Maps ['key'#value]. Know that bytearray is the silent default type when no schema is declared.

\[ R_{\text{grouped}} = \{ (k_A, \{ t \in R \mid t.\text{key} = k_A \}), ... \} \]

⚠️ Top pitfall: Confusing Tuple parentheses () with Bag curly braces {}. Map keys must always be chararray (strings).

Self-check: Write a Pig Map containing the key 'name' with value 'alpha' and key 'id' with value 1.

Connects to: 6.5 Pig Data Transformation Language: Loading, Inspected Data, and Output, 6.6 Relational & Flow Operators in Pig Latin

Pig LOAD, DESCRIBE, DUMP, and STORE

Must-know: STORE targets directories (not files) because reducers write separate part files. PigStorage defaults to tab delimiter; pass ',' for CSV. Without AS clause, fields default to bytearray with positional $0, $1 notation.

⚠️ Top pitfall: Writing STORE INTO '/output/file.csv' expecting a single file — it creates a directory named file.csv with multiple part files inside.

Self-check: What is the default delimiter for PigStorage? How do you load a CSV file?

Connects to: 6.4 Pig Data Model and Data Types, 6.6 Relational & Flow Operators in Pig Latin

Pig Relational and Flow Operators

Must-know: LIMIT without ORDER BY = non-deterministic. GROUP produces (group_key, nested_bag). FOREACH GENERATE projects/computes columns. COGROUP nests bags per relation; JOIN produces flat combined rows.

\[ R_i = U_i \times P_i \]

⚠️ Top pitfall: Using LIMIT 10 without ORDER BY and expecting the top 10 records. Confusing COGROUP (nested bags) with JOIN (flat rows).

Self-check: What does GROUP BY produce in its output tuple? How does COGROUP differ from JOIN?

Connects to: 6.4 Pig Data Model and Data Types, 6.5 Pig Data Transformation Language: Loading, Inspected Data, and Output, 6.7 Built-In Functions and User-Defined Functions (UDFs) in Pig

Pig Built-In Functions and Java UDFs

Must-know: 4-step Java UDF workflow: extend EvalFunc<T>, override exec(Tuple), package JAR, REGISTER + DEFINE in script. Know the four UDF types: eval, filter, load, store.

⚠️ Top pitfall: Function names are case sensitive (they map to Java class names). REGISTER is a keyword (not case sensitive) but the class name must match exactly.

Self-check: What are the four steps to create and use a custom Java UDF in Pig?

Connects to: 6.6 Relational & Flow Operators in Pig Latin

Apache Hive Architecture and HiveQL

Must-know: Sketch Hive architecture: Client → Driver → Compiler → Execution Engine → HDFS, with Metastore connected to Driver. HiveQL compiles to MapReduce DAGs. Hive uses schema-on-read.

⚠️ Top pitfall: Confusing Hive (data warehouse, SQL-like, reads HDFS) with Pig (ETL tool, procedural). Hive does NOT store data — data lives in HDFS.

Self-check: Name the four core architectural components of Apache Hive and describe the role of each.

Connects to: 6.1 Lecture Overview, Progress Tracking, and Hadoop Ecosystem Architecture, 6.9 Hive Metastore Architectures

Hive Metastore Architectures

Must-know: Embedded Derby = single connection, local testing only. Remote MySQL = multi-tenant, production standard. Metastore stores metadata (schemas), NOT actual data (which lives in HDFS).

⚠️ Top pitfall: Opening two Hive terminals with default Derby metastore — the second one will fail with a lock error.

Self-check: Why does the default embedded Derby metastore fail in production? What is the alternative?

Connects to: 6.8 Apache Hive Data Warehousing Fundamentals & Architecture

Course Administration and Practical Setup

Must-know: This section is administrative and not directly examinable. However, the practical setup experience (HDFS config, YARN config, Pig setup, Hive metastore config) reinforces understanding of how components connect.

⚠️ Top pitfall: Deferring setup tasks until exam week — the setup itself teaches how Hadoop components interconnect.

Self-check: Approximately how many hours does it take to set up a complete pseudo-distributed Hadoop + Pig + Hive environment?

Exam Guidance Summary

Must-know: This is the consolidated exam guidance — review all 10 bullet points for complete exam preparation.

⚠️ Top pitfall: Not reviewing all exam guidance points systematically before the exam.

Self-check: What are the three things Pig cannot do (no storage, no server, no real-time)?

Key Industry Applications

Must-know: Know specific real-world use cases: Yahoo (Pig for ETL), Facebook (Hive for SQL analytics), multi-tenant metastore (MySQL-backed for BI tool integration).

⚠️ Top pitfall: Describing industry applications in generic terms (e.g., 'used in engineering') rather than naming specific companies and tools.

Self-check: Name two companies that heavily used Pig and one that created Hive.

Was this lecture useful?

Loading comments…