Pig data model and operators
This lecture introduces Apache Pig, its nested data model and its engine. It then works through every core Pig Latin operator with small input-output traces. After this page you can predict the output of LOAD, FILTER, GROUP and COUNT on small data.
What Apache Pig isSearch on YouTube
Apache Pig is an abstraction over MapReduce. It is a tool that analyses large data sets. Analysts express the work as data flows. The language for these flows is Pig Latin. Pig Latin gives a rich set of types and operators. Programmers can add their own functions (UDFs) to read, write and process data.
Pig converts every script into optimised MapReduce jobs. The jobs run across the Hadoop cluster. They read input from HDFS. They write results back to HDFS.
Think of a recipe. Each line takes the dish of the previous line and changes it. LOAD brings the ingredients. FILTER removes what fails the test. GROUP sorts the rest into bowls.
Why Pig existsSearch on YouTube
Hand-written MapReduce jobs need long Java programs. The slide compares about 200 lines of Java with about 10 lines of Pig Latin. It reports development time falling by almost 16 times. Pig Latin looks like SQL, so it is quick to learn. Built-in operators cover join, filter, order and more. Nested types such as tuple, bag and map hold semi-structured data. The multi-query approach keeps scripts short.
The slide reports development time falling by almost 16 times. The syntax stays SQL-like, so analysts learn it fast.
Features of PigSearch on YouTube
- Rich set of operators for join, sort and filter.
- Ease of programming: Pig Latin resembles SQL.
- Optimisation: tasks optimise their own execution plans.
- Extensibility: users build new functions from old operators.
- UDFs: user-defined functions written in Java run inside scripts.
- All kinds of data: structured and unstructured data, with results stored in HDFS.
Applications of PigSearch on YouTube
| Area | Work |
|---|---|
| Web logs | Process huge log sources at scale |
| Search platforms | Run data processing pipelines for search |
| Time-sensitive loads | Process urgent data loads fast |
Data model of PigSearch on YouTube
Pig data nests in four levels. A field holds one value. A tuple holds an ordered set of fields. A bag holds a collection of tuples. A relation is a named bag. A map stands apart: it holds key-value pairs.
| Concept | Description | Analogy | Example |
|---|---|---|---|
| Field (atom) | One atomic value | A cell | 'Hyderabad' |
| Tuple | Ordered set of fields | A row | (001, 'Rajiv', 21, 'Hyd') |
| Bag | Collection of tuples, duplicates allowed | A table | { (..), (..), (..) } |
| Map | Key-value pairs | A JSON object | [name#'Rajiv', age#21] |
| Relation | A named bag of tuples | The data set | A = LOAD '...'; |
A field can itself hold a tuple, bag or map. This recursion lets Pig model JSON-like data with no fixed schema.
Fast Trucks Bring Red Mangoes
Field · Tuple · Bag · Relation (a named bag) · Map. Map stands apart with keys.
FieldSearch on YouTube
A field is the smallest unit of data. It is also called an atom. Any single value is a field, whatever its type. Atomic types are int, long, float, double, chararray and bytearray. Fields in one tuple need not share a type. A field can also hold a complex value: a tuple, bag or map.
-- two fields: a name and an age
'rajash', 30TupleSearch on YouTube
A tuple is an ordered set of fields. It resembles a row of a relational table. Tuples use parentheses: (field1, field2, field3, ...). Fields are reached by position: `$0` is the first field, `$1` the second. A tuple has fixed length. Its fields may mix types.
students = LOAD 'students.txt' USING PigStorage(',')
AS (id:int, name:chararray, age:int, city:chararray);
-- each input line becomes ONE tuple: (001, 'Rajiv', 21, 'Hyderabad')BagSearch on YouTube
A bag is a collection of tuples. Duplicates are allowed. Each tuple may hold any number of fields. Tuples in one bag may differ in size and type. Bags use curly braces: {tuple1, tuple2, ...}. There are two kinds. An outer bag is a relation. An inner bag is nested in a tuple and comes from GROUP.
grouped = GROUP students BY city;
-- each 'group' field of the result is an inner bag, e.g. {(Raja,30),(Mohammad,45)}RelationSearch on YouTube
A relation is a bag of tuples with a name. The name is the alias left of =. Every LOAD, FILTER, GROUP and JOIN makes a new relation. Relations are unordered. No order of tuples is promised. Chain aliases to build a pipeline.
A = LOAD 'students.txt' AS (id:int, name:chararray, age:int, city:chararray);
B = FILTER A BY age > 21;
C = GROUP B BY city;
DUMP C;Here A, B and C are three relations. Each step feeds the next.
MapSearch on YouTube
A map holds key-value pairs: [key#value, key#value, ...]. Each key is a chararray and is unique in the map. Each value may be any type, even a tuple, bag or map. Maps model semi-structured data such as JSON profiles.
records = LOAD 'profiles.json' AS (details:map[]);
name = FOREACH records GENERATE details#'name';
-- input map: [name#Raja, age#30]; output: (Raja)A field holds one value. A map holds many values, each reached by its own key.
Architecture of PigSearch on YouTube
A script passes through five stages. The Grunt shell or Pig Server takes the script. The parser builds a DAG. The optimiser trims the plan. The compiler emits MapReduce jobs. The execution engine runs them on Hadoop with HDFS.
Grunt Shell and Pig ServerSearch on YouTube
The Grunt shell is the interactive command line. Analysts type one statement at a time and see results at once. It suits data exploration and debugging. Start it with pig. The Pig Server is a Java class. It submits Pig programs from inside a Java application with no shell. It runs whole .pig scripts, for example with pig script.pig.
pig
grunt> A = LOAD 'file.csv';
grunt> DUMP A;pig script.pigPigServer p = new PigServer(...);Parser, optimiser and compilerSearch on YouTube
The script turns into a plan in three steps.
- Parse the script. The parser checks syntax and types. It builds a DAG. Nodes are operators such as
LOAD,FILTERandGROUP. Edges are data flows. - Optimise the DAG. The optimiser applies logical rewrites. Examples are projection pushdown, filter pushdown and merged operations. These cut the work MapReduce must do.
- Compile the plan. The compiler turns the logical plan into a physical plan. It then emits a series of MapReduce jobs for Hadoop.
DAG means Directed Acyclic Graph. It is the internal picture of the data flow.
Execution engine, MapReduce and HDFSSearch on YouTube
- The execution engine submits the compiled jobs to the cluster. It tracks progress until the jobs finish.
- MapReduce processes input splits in parallel in map tasks. Reduce tasks aggregate results.
GROUP,JOINandORDERuse the reduce phase hard. - HDFS holds the input data and takes back the output. Data splits into blocks across the cluster.
Simple FILTER and FOREACH steps often stay map-only. GROUP, JOIN and ORDER need a reduce phase. Output lands in HDFS as part-files, one file per reduce task.
Execution modesSearch on YouTube
| Local mode | MapReduce mode |
|---|---|
| Runs on one machine with the local file system | Runs on a real Hadoop cluster with HDFS |
| Needs no Hadoop and no HDFS | Each statement launches back-end MapReduce jobs |
| Used for testing | Used for real data in HDFS |
pig -x localpigExecution mechanismsSearch on YouTube
| Mechanism | Command | Use |
|---|---|---|
| Interactive (Grunt shell) | DUMP A; | Type statements and see output at once |
| Batch (script file) | pig myscript.pig | Run a whole .pig file in one go |
| Embedded (UDF) | X = FOREACH A GENERATE myUDF(f1); | Call own Java functions in a script |
Pig Latin operatorsSearch on YouTube
| Category | Operators |
|---|---|
| Relational | CROSS, DISTINCT, FILTER, FOREACH, UNION, SPLIT, ORDER BY, GROUP, LIMIT, JOIN, RANK |
| Arithmetic | Addition, subtraction, multiplication, division, modulo |
| Boolean | AND, OR, NOT |
This lecture covers LOAD through SPLIT in the list above. JOIN and RANK belong to l06.
LOADSearch on YouTube
LOAD reads data from the file system into a relation. PigStorage is the default load function. Pass a delimiter with USING PigStorage(','). Give the schema with AS (field:type, ...).
A = LOAD '/path/file.txt' USING PigStorage(',') AS (name:chararray, age:int, marks:float);USING names the loader and delimiter. AS names each field with its type. Without AS, all fields stay untyped.
Worked example. Load a file with three fields per line.
A = LOAD 'data' USING PigStorage(',') AS (name:chararray, age:int, marks:float);
DUMP A;Input file lines:
John,18,4.0
Mary,19,3.8
Bill,20,3.9
Joe,18,3.8DUMP prints the relation:
(John,18,4.0)
(Mary,19,3.8)
(Bill,20,3.9)
(Joe,18,3.8)Each line becomes one tuple. Field order follows the file.
STORESearch on YouTube
STORE writes a relation to the file system. It writes a directory, not one file. Output rows use tabs between fields.
STORE A INTO 'output_latin';A is the relation to save. 'output_latin' is the new output directory.
-- relation A holds (John,18,4.0), (Mary,19,3.8), (Bill,20,3.9), (Joe,18,3.8)
STORE A INTO 'output_latin';
-- output directory holds: John 18 4.0 / Mary 19 3.8 / Bill 20 3.9 / Joe 18 3.8Remove the target directory before STORE. The command fails if the output directory already exists.
CROSSSearch on YouTube
CROSS builds the Cartesian product of two or more relations. Each tuple of A pairs with each tuple of B. Fields glue in order: all of A first, then all of B.
X = CROSS A, B; pairs each tuple of A with each tuple of B. For tuples in A and in B, the result holds tuples.
Worked example. A holds 2 tuples. B holds 3 tuples. Expect tuples.
X = CROSS A, B;
DUMP X;Inputs:
| Relation A | (1,2,3) | (4,2,1) | |
| Relation B | (2,4) | (8,9) | (1,3) |
Output (first tuple of A with all of B, then the second):
(1,2,3,2,4)
(1,2,3,8,9)
(1,2,3,1,3)
(4,2,1,2,4)
(4,2,1,8,9)
(4,2,1,1,3)Count the rows: 6. This matches .
DISTINCTSearch on YouTube
DISTINCT drops duplicate tuples. It compares whole tuples. Two rows count as duplicates only if every field matches.
X = DISTINCT A;One operator with no extra clause. It keeps one copy of each distinct tuple.
Worked example. A holds 5 tuples with two repeats.
X = DISTINCT A;
DUMP X;Input DUMP A:
(8,3,4)
(1,2,3)
(4,3,3)
(4,3,3)
(1,2,3)Output DUMP X (3 unique tuples, order not promised):
(1,2,3)
(4,3,3)
(8,3,4)Five rows shrink to three. Use it before ORDER BY or as a de-duplication step.
ORDER BYSearch on YouTube
ORDER BY sorts a relation on one or more fields. Add ASC or DESC for direction. Ties may land in any order.
A = LOAD 'data' USING PigStorage(',') AS (a1:int, a2:int, a3:int);
X = ORDER A BY a3 DESC;a3 is the third field. DESC sorts from large to small.
Worked example. Sort 6 tuples by the third field, descending.
A = LOAD 'data' USING PigStorage(',') AS (a1:int, a2:int, a3:int);
X = ORDER A BY a3 DESC;
DUMP X;Input third-field values: 3, 1, 4, 3, 5, 3.
(1,2,3)
(4,2,1)
(8,3,4)
(4,3,3)
(7,2,5)
(8,4,3)Output (5 first, then 4, then the three 3s, then 1):
(7,2,5)
(8,3,4)
(1,2,3)
(4,3,3)
(8,4,3)
(4,2,1)The three tuples with third field 3 may swap places. Order of ties is undefined.
LIMITSearch on YouTube
LIMIT caps the number of output tuples. It promises nothing about which tuples survive. Order the relation first for a stable top-N.
X = LIMIT A 3;The result holds at most 3 tuples. Without a prior ORDER, any 3 may appear.
Worked example. Limit the 6-tuple relation above to 3 rows.
X = LIMIT A 3;
DUMP X;One possible output:
(1,2,3)
(4,2,1)
(8,3,4)No promise covers these exact rows. For the true top 3, run ORDER first, then LIMIT.
FILTERSearch on YouTube
FILTER keeps tuples that pass a test. It resembles the WHERE clause of SQL. Dropped tuples leave the pipeline.
A = LOAD 'data' USING PigStorage(',') AS (f1:int, f2:int, f3:int);
X = FILTER A BY f3 == 3;f3 is the third field. Only tuples with third field equal to 3 stay in X.
Worked example. Keep tuples whose third field equals 3.
A = LOAD 'data' USING PigStorage(',') AS (f1:int, f2:int, f3:int);
X = FILTER A BY f3 == 3;
DUMP X;Input (third fields: 3, 1, 3, 3, 5):
(1,2,3)
(4,2,1)
(8,4,3)
(4,3,3)
(7,2,5)Take the rows with third field 3 in input order:
(1,2,3)
(8,4,3)
(4,3,3)Three of five rows survive. Real-world forms use named fields:
FILTER deptdata BY state == 'Kerala';
FILTER studentdata BY name == 'ABC';Kept rows are those with third field 3. Rows with third field 1 or 5 drop out.
FOREACH GENERATESearch on YouTube
FOREACH ... GENERATE projects columns from a relation. It resembles the SELECT clause of SQL. It picks a subset of fields from each tuple.
X = FOREACH A GENERATE f1;Each output tuple holds only the first field. Name several fields to keep several columns.
Worked example. Project the first field of 5 tuples.
Input:
(1,2,3)
(4,2,1)
(8,4,3)
(4,3,3)
(7,2,5)Output:
(1)
(4)
(8)
(4)
(7)Row count stays 5. Each row shrinks to one field. Named-field form on student records:
foreach_data = FOREACH student_details GENERATE id, age, city;
-- (1,21,Hyderabad), (2,22,Kolkata), (3,22,Delhi), (4,21,Pune)GROUPSearch on YouTube
GROUP collects rows by a key field. Each output tuple has two fields. The first is group, the key value. The second is a bag with all matching tuples. This bag is the inner bag.
A = LOAD 'data' USING PigStorage(',') AS (name:chararray, age:int, marks:float);
B = GROUP A BY age;age is the key. Each key value gets one output row with its bag.
Worked example. Group 4 students by age.
A = LOAD 'data' USING PigStorage(',') AS (name:chararray, age:int, marks:float);
B = GROUP A BY age;
DUMP B;Input:
(John,18,4.0)
(Mary,19,3.8)
(Bill,20,3.9)
(Joe,18,3.8)Output (3 groups from 4 rows):
(18,{(John,18,4.0),(Joe,18,3.8)})
(19,{(Mary,19,3.8)})
(20,{(Bill,20,3.9)})Age 18 owns a bag of 2 tuples. Ages 19 and 20 own bags of 1 tuple each.
GROUP powers all aggregation. COUNT, MAX, SUM and AVG always follow a GROUP. Learn the shape above once and every aggregate becomes easy.
COUNTSearch on YouTube
COUNT counts elements of a bag. It needs a prior GROUP. It skips NULL values.
A = LOAD 'data' USING PigStorage(',') AS (a1:int, a2:int, a3:int);
B = GROUP A BY a1;
Result = FOREACH B GENERATE COUNT(A);COUNT(A) counts tuples in the bag A of each group. NULL entries add nothing.
Worked example. Count bag sizes for 4 groups.
Grouped input:
(1,{(1,3,7),(1,3,6)})
(3,{(3,8,9)})
(5,{(5,1,2),(5,2,3)})
(7,{(7,2,5)})Count tuples per bag: 2, 1, 2, 1.
(2)
(1)
(2)
(1)Each output row matches one group. Bag sizes turn into plain counts.
MAXSearch on YouTube
MAX takes the largest value in a single-column bag. It needs a prior GROUP. It works on numbers and on chararray fields. It skips NULL values.
A = LOAD 'data' USING PigStorage(',') AS (a1:int, a2:int, a3:int);
B = GROUP A BY a1;
Result = FOREACH B GENERATE group, MAX(A.a3);A.a3 is the third field of bag A. Output pairs each key with its maximum.
Worked example. Find the top marks per student group.
Grouped input:
(Sam,{(Sam,f,3.8),(Sam,e,3.4),(Sam,d,2.2)})
(Rohan,{(Rohan,c,3.6),(Rohan,b,2.8),(Rohan,a,2.4)})Sam: maximum of 3.8, 3.4, 2.2 is 3.8. Rohan: maximum of 3.6, 2.8, 2.4 is 3.6.
(Sam,3.8)
(Rohan,3.6)Practice (extra). Department summary with GROUP, COUNT, AVG and MAX.
Input emps = LOAD 'emps.txt' AS (id:int, name:chararray, dept:chararray, sal:int);:
(101,Asha,Sales,40000)
(102,Manoj,Sales,50000)
(103,Divya,HR,45000)
(104,Kiran,HR,55000)
(105,Ravi,Sales,45000)Group by department:
grpd = GROUP emps BY dept;
-- (Sales,{(101,Asha,Sales,40000),(102,Manoj,Sales,50000),(105,Ravi,Sales,45000)})
-- (HR,{(103,Divya,HR,45000),(104,Kiran,HR,55000)})Aggregate each bag:
summary = FOREACH grpd GENERATE group, COUNT(emps), AVG(emps.sal), MAX(emps.sal);
DUMP summary;Sales bag holds 3 tuples, so count is 3. Average is . Maximum of 40000, 50000, 45000 is 50000. HR bag holds 2 tuples, so count is 2. Average is . Maximum of 45000, 55000 is 55000.
(Sales,3,45000,50000)
(HR,2,50000,55000)TOKENIZESearch on YouTube
TOKENIZE splits a string into a bag of word-tuples. Each input line yields one bag. It is the first half of text pipelines.
Result = FOREACH A GENERATE TOKENIZE(a1);a1 is the text field. Output holds one bag per input line.
Worked example. Tokenise 3 lines.
Input lines:
Apache Pig is a high level data flow platform.
It executes Map Reduce programs of Hadoop.
The language for Pig is pig Latin.Output (one bag per line):
{(Apache),(Pig),(is),(a),(high),(level),(data),(flow),(platform)}
{(It),(executes),(Map),(Reduce),(programs),(of),(Hadoop)}
{(The),(language),(for),(Pig),(is),(pig),(Latin)}Line 1 gives 9 word-tuples. Line 2 gives 7. Line 3 gives 7. Case is kept: Pig and pig differ.
FLATTENSearch on YouTube
FLATTEN un-nests a bag into plain tuples. It turns each element of the bag into its own row. TOKENIZE plus FLATTEN turns each text line into one row per word.
words = FOREACH input GENERATE FLATTEN(TOKENIZE(line, ' ')) AS word;TOKENIZE makes one bag per line. FLATTEN spreads each bag into rows. The result is one tuple per word.
Word countSearch on YouTube
Word count chains four steps. Load lines. Spread them into words. Group equal words. Count each group. This pattern fits many text pipelines.
input = LOAD '/path/to/file/' AS (line:chararray);
words = FOREACH input GENERATE FLATTEN(TOKENIZE(line, ' ')) AS word;
grouped = GROUP words BY word;
wordcount = FOREACH grouped GENERATE group, COUNT(words);Worked example. Count words in two lines.
Input (5 words per line, 10 total):
This is a hadoop class
hadoop is a bigdata technologyTokenise and flatten. Each line spreads into word rows.
(This)(is)(a)(hadoop)(class)(hadoop)(is)(a)(bigdata)(technology)Group equal words. Seven distinct words give seven groups.
(a,{(a),(a)})
(is,{(is),(is)})
(This,{(This)})
(class,{(class)})
(hadoop,{(hadoop),(hadoop)})
(bigdata,{(bigdata)})
(technology,{(technology)})Count each bag. Bags of size 2 give count 2.
(a,2)
(is,2)
(This,1)
(class,1)
(hadoop,2)
(bigdata,1)
(technology,1)Tallies add to 10: 2 + 2 + 1 + 1 + 2 + 1 + 1. The count matches the word total.
The Hive version needs a nested query (Hive is the topic of l08):
SELECT word, COUNT(1) AS count FROM
(SELECT explode(split(sentence, ' ')) AS word FROM texttable) tempTable
GROUP BY word;Four Pig Latin lines replace one nested Hive query. Both stay far shorter than hand-written MapReduce Java.
UNIONSearch on YouTube
UNION merges two or more relations into one. It stacks all tuples in one bag. Input schemas need not match. This leniency beats the strict union of SQL.
student = UNION student1, student2;The result holds every tuple of student1 plus every tuple of student2. No schema match is forced.
Worked example (extra). Stack two student files.
student1 = LOAD 'student_data1.txt' USING PigStorage(',')
AS (id:int, firstname:chararray, lastname:chararray, phone:chararray);
student2 = LOAD 'student_data2.txt' USING PigStorage(',')
AS (id:int, firstname:chararray, lastname:chararray, phone:chararray);
student = UNION student1, student2;If student1 holds 2 tuples and student2 holds 3 tuples, student holds 5 tuples. No rows merge. No duplicates drop. For de-duplication, add DISTINCT after the union.
SPLITSearch on YouTube
SPLIT routes one relation into several. Each branch keeps tuples that pass its own IF test. It splits one pipeline into many by threshold or category.
SPLIT student_details INTO student_details1 IF age < 23, student_details2 IF (22 < age AND age > 25);Branch 1 keeps ages below 23. Branch 2 keeps ages above 25. Ages 23 to 25 match neither branch and fall out.
Worked example (extra). Split 5 students by age.
student_details = LOAD 'student_details.txt' USING PigStorage(',')
AS (id:int, firstname:chararray, lastname:chararray, age:int,
phone:chararray, city:chararray);
SPLIT student_details INTO young IF age < 23, senior IF age > 25;Test ages 20, 22, 24, 26 and 30. Ages 20 and 22 pass branch 1. Ages 26 and 30 pass branch 2. Age 24 matches neither and is dropped.
young: 2 tuples (ages 20, 22)
senior: 2 tuples (ages 26, 30)End-to-end scriptSearch on YouTube
Each line maps to one idea from this lecture. The engine path runs beside it.
students = LOAD 'students.txt' USING PigStorage(',')
AS (id:int, name:chararray, age:int, city:chararray);
adults = FILTER students BY age > 21;
grouped = GROUP adults BY city;
DUMP grouped;| Line | Idea |
|---|---|
students, adults, grouped | Relations, one per step |
| One file line | One tuple |
id, name, age, city | Fields |
| All rows of one city | One inner bag |
Path through the engine:
- Grunt shell or Pig Server takes the script.
- Parser builds the DAG and checks types.
- Optimiser pushes the
FILTERearlier where possible. - Compiler emits MapReduce jobs.
- Execution engine submits the jobs.
GROUPtriggers a reduce phase. - Results read from and written to HDFS.
Quick self-testSearch on YouTube
1. What is Pig Latin, and what does Pig turn it into?
Pig Latin is the data-flow language of Pig. Pig compiles each script into optimised MapReduce jobs. The jobs run on Hadoop over data in HDFS.
2. Order these from smallest to largest: bag, field, relation, tuple. Where does a map fit?
Field, then tuple, then bag, then relation (a named bag). A map stands apart: it holds key-value pairs and can nest inside any level.
3. CROSS: A holds (1,2), (3,4), (5,6) and B holds (7,8), (9,0). How many output tuples, and what are they?
tuples: (1,2,7,8), (1,2,9,0), (3,4,7,8), (3,4,9,0), (5,6,7,8), (5,6,9,0). Each tuple of A pairs with each tuple of B.
4. FILTER: (Ravi,22), (Sima,19), (Dev,22) with schema (name:chararray, age:int). What does FILTER BY age == 22 return?
(Ravi,22) and (Dev,22). Sima fails the test and drops out. Two of three rows survive.
5. GROUP: (Asha,Sales), (Manoj,Sales), (Divya,HR) grouped by department, then COUNT per group. What are the counts?
Sales bag holds 2 tuples, so count is 2. HR bag holds 1 tuple, so count is 1. Result: (Sales,2), (HR,1).
6. SPLIT with IF age < 23 and IF age > 25 on ages 20, 22, 24, 26, 30. Which rows land where?
Ages 20 and 22 go to branch 1. Ages 26 and 30 go to branch 2. Age 24 matches neither test and is dropped.
7. Why does LIMIT need a prior ORDER for a top-N query?
LIMIT alone returns any N tuples. No order is promised. ORDER first fixes the ranking, so LIMIT then keeps the true top rows.
8. Why does STORE fail, and what is the fix?
It fails if the output directory already exists. Pig never overwrites output dirs. Remove or rename the directory first, then rerun.
9. Why pair TOKENIZE with FLATTEN in word count?
TOKENIZE alone yields one bag per line. GROUP would then group whole bags, not words. FLATTEN spreads each bag into one row per word, so grouping counts words.
10. Contrast local mode with MapReduce mode. When is each used?
Local mode runs on one machine with local files and needs no Hadoop. MapReduce mode runs on a cluster over HDFS. Local mode suits testing; MapReduce mode suits real data.
- Pig is an abstraction over MapReduce. Pig Latin scripts become optimised MapReduce jobs over HDFS.
- Data nests as field, then tuple, then bag, then relation. Maps hold key-value pairs for semi-structured data.
- Scripts enter via the Grunt shell or Pig Server. Parser builds a DAG, optimiser trims it, compiler emits jobs.
- Local mode tests on one machine. MapReduce mode runs on the cluster. Batch, interactive and embedded mechanisms cover every run style.
LOADreads withPigStorageandAS.STOREwrites a new directory and fails if it exists.CROSSyields tuples.DISTINCTdrops full-tuple duplicates.ORDERsorts withASCorDESC.LIMITcaps rows but promises no order.FILTERkeeps passing tuples.FOREACH ... GENERATEprojects columns likeSELECT.GROUPmakes (key, inner bag) tuples.COUNTandMAXaggregate each bag and skipNULL.TOKENIZEplusFLATTENturns lines into one row per word. Group plus count finishes word count.UNIONstacks relations with no forced schema match.SPLITroutes tuples byIFtests and drops the rest.
Tutorial 13 :Apache Pig
Data Model and Execution Mode in Apache Pig
Pig Latin Data Model and Data Types
Apache Pig Tutorial 1