Apache Pig
Introductory
Pig is a large-scale data processing system, the scripts are written in Pig Latin, a dataflow language
- Pig Engine Parses: compiles Pig Latin scripts into MapReduce jobs run on top of Hadoop
- Pig Latin: a dataflow language
- Pig: the high level language interface for Hadoop
Why not MapReduce
Compute the natural join $R(A,B) \Join S(B,C)$
- Implementation in MapReduce:
- Each input tuple
R(a,b)into key-value pair(b,(a,R)) - Each input tuple
S(b,c)into(b,(c,S))
- Map processes send each key-value pair with key
bto Reduce processh(b) - Each Reduce process matches all the pairs
(b,(a,R))with all(b,(c,S))and outputs(a,b,c)
- Each input tuple
The implementation is complicated, we need a faster code development
Although the performance is on par with (maybe ~2 times slower than) raw Hadoop, it is convenient in the development
Pig Components
Two Main Components:
- High-level language (Pig Latin)
- Two execution modes
- Local: reads/writes to local file system
- Mapreduce: connects to Hadoop cluster and reads/writes to HDFS
Two modes:
- Interactive mode: using console
- Batch mode: submit a script
Pig Compilation

Introductory Example 1
Task: Find users who tend to visit “good” pages
Implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# Operates directly over files -- schames optional
Visits = load '/data/visits' as (user, url, time);
# User-defined functions (UDFs): can be used in every construct
Visits = foreach Visits generate user, Canonicalize(url), time;
# Operates directly over files -- schames optional
Pages = load '/data/pages' as (url, pagerank);
VP = join Visits by url, Pages by url;
UserVisits = group VP by user;
UserPageranks = foreach UserVisits generate user, AVG(VP.pagerank) as avgpr;
GoodUsers = filter UserPageranks by avgpr > '0.5';
Store GoodUsers into '/data/good_users';Conceptual Dataflow:

Illustration:

Introductory Example 2
1 | # MapReduce Job 1: group by url + foreach |
Pig Latin
Language Features
Keywords
Load,Filter,Foreach Generate,Group By,Store,Join,Distinct,Order By, …Aggregations
Count,Avg,Sum,Max,MinSchema
Defines at query-time not when files are loadedUser Defined Functions (UDFs)
- As first-class citizens in the language
- UDFs can be written in other languages, e.g. Java, Python, Javascript, etc

Data Types
- Atom: a simple atomic value
'alice' - Tuple: a sequence of fields, each can be any of the data types
('alice', 'lakers') - Bag: a collection of tuples (similar to set)
{('alice', 'lakers'), ('alice', ('iPod', 'apple'))} - Map: a collection of data items that is associated with a dedicated atom (similar to the dictionary)
['fan of' -> {'lackers', 'iPod'}, 'age' -> 20]
Expressions
| Expression Type | Example | Value for tuple t |
|---|---|---|
| Constant | 'bob' |
Independent of t |
| Field by position | $0 |
$\text{‘alice’}$ |
| Field by name | f3 |
$[\text{‘age’} \rightarrow 20]$ |
| Projection | f2.$0 |
$\begin{Bmatrix} (\text{‘lackers’}) \\ (\text{‘iPod’}) \end{Bmatrix}$ |
| Map Loopup | f3#'age' |
$20$ |
| Function Evaluation | SUM(f2.$1) |
$1 + 2 = 3$ |
| Conditional Expression | f3#'age' > 18 ? 'adult' : 'minor' |
$\text{adult’}$ |
| Flattening (remove the bags and tuples) | FLATTEN(f2) |
$\text{‘lackers’}, 1, \text{iPod’}, 2$ |
- Other examples:

Commands and Operations
LOAD: Specify input data1
queries = LOAD 'query_log.txt' USING myLoad() AS (userID, queryString, timestamp);

FOREACH: Per-tuple processing1
expandedQueries = FOREACH queries GENERATE userID, expandQuery(queryString);

FLATTEN: Remove the nested data in tuples (or bags)1
FLATTEN(expandedQueries);

FILTER: Discarding unwanted data1
FILTER expandedQueries BY userId == 'alice';

COGROUP: Getting related data together1
grouped_data = COGROUP results BY queryString, revenue BY queryString;

JOIN: Cross product of two tables1
join_result = JOIN results BY queryString, revenue BY queryString;

STORE: Create output1
final_result = STORE join_results INTO `myoutput` USING myStore();

1
STORE(&DUMP) # output data to screen
Other operators such as
UNION,CROSS,ORDER,DISTINCT,LIMIT
Additional Operators
Re-partition Join: using
parallel xto customise the number of partitions1
C = join beta by name, B by user parallel 40;

Replicated Join: using
using 'replicated'to conduct the replicated join
Optimization in joining a big dataset with a small one1
C = join Big by user, small by name using 'replicated';

Multiple Outputs: Pig is able to produce multiple outputs to different files

User Defined Function
Types of UDF’s:
- Eval Functions (extends
EvalFunc<String>) - Aggregate Functions (extends
EvalFunc<Long>implements Algebraic) - Filter Functions (extends
FilterFunc)
- Eval Functions (extends
Sample UDF
1
2
3
4
5
6
7
8
9
10public class TopLevelDomain extends
EvalFunc<String> {
public String exec(Tuple tuple) throws IOException {
Object o = tuple.get(0); if (o == null) {
return null;
}
return Validator.getTLD(o.toString());
}
}
Pig Latin vs. SQL
Pig Latin
- Pig Latin is procedural (dataflow programming), step-by-step query style is much cleaner and easier to write
- Lazy evaluation: data not processed prior to STORE command
- Data can be stored at any point during the pipeline
- Schema and data types are lazily defined at run-time
- An execution plan can be explicitly defined (Use optimizer hints)
SQL
- SQL is declarative but not step-by-step style
- Query plans are solely decided by the system
- Data cannot be stored in the middle
- Schema and data types are defined at the creation time
Optimization
- Schema and type checking
- Translating into efficient physical dataflow (i.e., sequence of one or more MapReduce jobs)
- Exploiting data reduction opportunities (e.g., early partial aggregation via a combiner)
- Executing the system-level dataflow (i.e., running the MapReduce jobs) n Tracking progress, errors, etc.
- Logic Plan: The Pig Latin script

- Physical Plan: Automatically optimize the executions

Apache Tez
- Tez is a distributed execution framework targeting data-processing applications
- NOT a standlone computation engine like MapReduce or Spark ; Instead, it is intended to be use as a “backend” library
- Based on expressing a computation as a DAG dataflow graph
- Highly customizable to meet a broad spectrum of use cases
- Built on top of YARN: the resource management framework for Hadoop

Usage
TeZ is an Alternative Execution Library for realizing Pig’s Logical Computation Plan
- The Required Data Processing Flow is represented as a Directed-Acyclic Graph (DAG) (which is what PIG has been doing all along)
- TeZ can then be used to realize/execute the DAG-based dataflow/computation to avoid limitations imposed by the rigid 2-stage MapReduce model

Example 1
1 | f = Load 'foo' AS (x, y, z); |

Example 2
1 | l = Load 'left' AS (x, y); |


