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:
    1. Each input tuple R(a,b) into key-value pair (b,(a,R))
    2. Each input tuple S(b,c) into (b,(c,S))
    • Map processes send each key-value pair with key b to Reduce process h(b)
    • Each Reduce process matches all the pairs (b,(a,R)) with all (b,(c,S)) and outputs (a,b,c)

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:

    1. High-level language (Pig Latin)
    2. Two execution modes
      • Local: reads/writes to local file system
      • Mapreduce: connects to Hadoop cluster and reads/writes to HDFS
  • Two modes:

    1. Interactive mode: using console
    2. 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
2
3
4
5
6
7
8
9
10
11
12
13
# MapReduce Job 1: group by url + foreach
visits = load '/data/visits' as (user, url, time);
gVisits = group visits by url;
urlCounts = foreach gVisits generate url, count(visits);

# MapReduce Job 2: join
urlInfo = load '/data/urlInfo' as (url, category, pRank);
urlCategoryCount = join urlCounts by url, urlInfo by url;

# MapReduce Job 3: group by category + for each
gCategories = group urlCategoryCount by category;
topUrls = foreach gCategories generate top(urlCounts,10);
store topUrls into '/data/topUrls';

Pig Latin

Language Features

  • Keywords
    Load, Filter, Foreach Generate, Group By, Store, Join, Distinct, Order By, …

  • Aggregations
    Count, Avg, Sum, Max, Min

  • Schema
    Defines at query-time not when files are loaded

  • User 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

  1. Atom: a simple atomic value
    'alice'
  2. Tuple: a sequence of fields, each can be any of the data types
    ('alice', 'lakers')
  3. Bag: a collection of tuples (similar to set)
    {('alice', 'lakers'), ('alice', ('iPod', 'apple'))}
  4. 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

  1. LOAD: Specify input data

    1
    queries = LOAD 'query_log.txt' USING myLoad() AS (userID, queryString, timestamp);

  2. FOREACH: Per-tuple processing

    1
    expandedQueries = FOREACH queries GENERATE userID, expandQuery(queryString);

  3. FLATTEN: Remove the nested data in tuples (or bags)

    1
    FLATTEN(expandedQueries);

  4. FILTER: Discarding unwanted data

    1
    FILTER expandedQueries BY userId == 'alice';

  5. COGROUP: Getting related data together

    1
    grouped_data = COGROUP results BY queryString, revenue BY queryString;

  6. JOIN: Cross product of two tables

    1
    join_result = JOIN results BY queryString, revenue BY queryString;

  7. STORE: Create output

    1
    final_result = STORE join_results INTO `myoutput` USING myStore();

    1
    STORE(&DUMP)    # output data to screen
  8. Other operators such as UNION, CROSS, ORDER, DISTINCT, LIMIT

Additional Operators

  1. Re-partition Join: using parallel x to customise the number of partitions

    1
    C = join beta by name, B by user parallel 40;

  2. Replicated Join: using using 'replicated' to conduct the replicated join
    Optimization in joining a big dataset with a small one

    1
    C = join Big by user, small by name using 'replicated';

  3. 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)
  • Sample UDF

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class TopLevelDomain extends
    EvalFunc<String> {
    @Override
    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

  1. Schema and type checking
  2. Translating into efficient physical dataflow (i.e., sequence of one or more MapReduce jobs)
  3. Exploiting data reduction opportunities (e.g., early partial aggregation via a combiner)
  4. 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

  1. The Required Data Processing Flow is represented as a Directed-Acyclic Graph (DAG) (which is what PIG has been doing all along)
  2. 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
2
3
4
5
f = Load 'foo' AS (x, y, z);
g1 = GROUP f BY y;
g2 = GROUP f BY z;
j = JOIN g1 BY group,
g2 BY group;

Example 2

1
2
3
l = Load 'left' AS (x, y);
r = Load 'right' AS (x, z);
j = JOIN l BY x, x BY y, USING 'skewed';