SlideShare a Scribd company logo
Apache Hadoop
Pig Fundamentals

Shashidhar HB
1








Why Hadoop
Hadoop n The Cloud Industry
Querying Large Data... Pig to Rescue
Pig: Why? What? How?
Pig Basics: Install, Configure, Try
Dwelling Deeper into Pig-PigLatin
Q&A

2
You have 10x more DATA
Than you did 3 years ago!

MORE about your
BUSINESS?

BUT do you know 10x

NO!
3
A lot of data, BIG data!

Information
(The Big Picture)

We are not able to effectively
store and analyze all the data we have, so we are not able to see the big picture!

5


BigData / Web Scale: are datasets that grow so large that
they become awkward to work with traditional database
management tools



Handling Big Data using traditional approach is costly and
rigid (Difficulties include capture, storage, search, sharing,
analytics and visualization)



Google,Yahoo, Facebook, LinkedIn handles “Petabytes”
of data everyday.



They all use HADOOP to solve there BIG DATA problem
6
7
So Mr. HADOOP says he has a
solution to our BIG problem !

8


Hadoop is an open-source software for RELIABLE
and SCALABLE distributed computing



Hadoop provides a comprehensive solution to handle
Big Data



Hadoop is
 HDFS : High Availability Data Storage subsystem
(http://labs.google.com/papers/gfs.html: 2003)

+
 MapReduce: Parallel Processing system
(http://labs.google.com/papers/mapreduce.html: 2004)
9


2008: Yahoo! Launched Hadoop



2009: Hadoop source code was made available to the
free world



2010: Facebook claimed that they have the largest
Hadoop cluster in the world with 21 PB of storage



2011: Facebook announced the data has grown to 30
PB
10


Stats :Facebook
▪ Started in 2004: 1 million users
▪ August 2008: Facebook reaches over 100 million active users
▪ Now: 750+ million active users
“Bottom line.. More users more DATA”



The BIG challenge at Facebook!!
Using historical data is a very big part of improving the user experience on
Facebook. So storing and processing all these bytes is of immense importance.

Facebook tried Hadoop for this.
11
Hadoop turned out to be a great
solution, but there was one little
problem!

12



Map Reduce requires skilled JAVA programmers
to write standard MapReduce programs
Developers are more fluent in querying data using
SQL

“Pig says, No Problemo!”
13


Input: User profiles, Page
visits



Find the top 5 most
visited pages by users
aged 18-25

14
15
1.

Users = LOAD ‘users’ AS (name, age);

2.

Filtered = FILTER Users BY age >= 18 AND age <= 25;

3.

Pages = LOAD ‘pages’ AS (user, url);

4.

Joined = JOIN Filtered BY name, Pages BY user;

5.

Grouped = GROUP Joined BY url;

6.

Summed = FOREACH Grouped generate GROUP, COUNT(Joined) AS
clicks;

7.

Sorted = ORDER Summed BY clicks DESC;

8.

Top5 = LIMIT Sorted 5;

9.

STORE Top5 INTO ‘top5sites’;
16


Pig is a dataflow language
• Language is called PigLatin
• Pretty simple syntax
• Under the covers, PigLatin scripts are turned into MapReduce
jobs and executed on the cluster



Pig Latin: High-level procedural language



Pig Engine: Parser, Optimizer and
distributed query execution
17
PIG








Pig is procedural
Nested relational data model
(No constraints on Data
Types)
Schema is optional
Scan-centric analytic
workloads (No Random reads
or writes)
Limited query optimization

SQL








SQL is declarative
Flat relational data model
(Data is tied to a specific Data
Type)
Schema is required
OLTP + OLAP workloads

Significant opportunity for
query optimization
18
PIG


Users = load 'users' as (name, age, ipaddr);



Clicks = load 'clicks' as (user, url, value);



ValuableClicks = filter Clicks by value > 0;



UserClicks = join Users by name,
ValuableClicks by user;




Geoinfo = load 'geoinfo' as (ipaddr, dma);
UserGeo = join UserClicks by ipaddr,
Geoinfo by ipaddr; ByDMA = group
UserGeo by dma;



ValuableClicksPerDMA = foreach ByDMA
generate group, COUNT(UserGeo);
store ValuableClicksPerDMA into
'ValuableClicksPerDMA';



SQL

insert into
ValuableClicksPerDMA select
dma, count(*) from geoinfo
join ( select name, ipaddr
from users join clicks on
(users.name = clicks.user)
where value > 0; ) using ipaddr
group by dma;

19


Joining datasets



Grouping data



Referring to elements by position rather than name ($0, $1,
etc)



Loading non-delimited data using a custom SerDe (Writing
a custom Reader and Writer)



Creation of user-defined functions (UDF), written in Java



And more..
20
Under the hood

21
Pig runs as a client-side application. Even if you want to run Pig on a Hadoop
cluster, there is nothing extra to install on the cluster: Pig launches jobs and
interacts with HDFS (or other Hadoop file systems) from your workstation.
Download a stable release from http://hadoop.apache.org/pig/releases.html
and unpack the tarball in a suitable place on your workstation:
% tar xzf pig-x.y.z.tar.gz
It’s convenient to add Pig’s binary directory to your command-line path.
For example:

% export PIG_INSTALL=/home/tom/pig-x.y.z
% export PATH=$PATH:$PIG_INSTALL/bin
You also need to set the JAVA_HOME environment variable to point to
suitable Java installation.

22


Execution Types
 Local mode (pig -x local)
 Hadoop mode



Pig must be configured to the cluster’s namenode
and jobtracker
1. Put hadoop config directory in PIG classpath
% export PIG_CLASSPATH=$HADOOP_INSTALL/conf/
2. Create a pig.properties
fs.default.name=hdfs://localhost/
mapred.job.tracker=localhost:8021
23


Script: Pig can run a script file that contains Pig commands.
For example,
% pig script.pig
Runs the commands in the local file ”script.pig”.
Alternatively, for very short scripts, you can use the -e option to run a script
specified
as a string on the command line.



Grunt: Grunt is an interactive shell for running Pig commands.
Grunt is started when no file is specified for Pig to run, and the -e option is not used.
Note: It is also possible to run Pig scripts from within Grunt using run and exec.



Embedded: You can run Pig programs from Java, much like you can use JDBC to run SQL
programs from Java.
There are more details on the Pig wiki at http://wiki.apache.org/pig/EmbeddedPig
24


PigLatin: A Pig Latin program consists of a collection of statements. A
statement can be thought of as an operation, or a command
For example,
1. A GROUP operation is a type of statement:
grunt> grouped_records = GROUP records BY year;
2. The command to list the files in a Hadoop filesystem is another example of a statement:
ls /
3. LOAD operation to load data from tab seperated file to PIG record
grunt> records = LOAD ‘sample.txt’
AS (year:chararray, temperature:int, quality:int);



Data: In Pig, a single element of data is an atom
A collection of atoms – such as a row, or a partial row – is a tuple
Tuples are collected together into bags
Atom –>

Row/Partial Row

–> Tuple

–> Bag
25
Example contents of ‘employee.txt’ a tab delimited text










1
Krishna 234000000
none
2
Krishna_01
234000000
none
124163
Shashi 10000 cloud
124164
Gopal
1000000 setlabs
124165
Govind 1000000 setlabs
124166
Ram
450000 es
124167
Madhusudhan
450000 e&r
124168
Hari
6500000 e&r
124169
Sachith 50000 cloud

26
--Loading data from employee.txt into emps bag and with a
schema
empls
=
LOAD
‘employee.txt’
AS
(id:int, name:chararray,
salary:double, dept:chararray);
--Filtering the data as required
rich = FILTER empls BY $2 > 100000;

--Sorting
sortd = ORDER rich BY salary DESC;
--Storing the final results
STORE sortd INTO ‘rich_employees.txt’;
-- Or alternatively we can dump the record on the screen
DUMP sortd;
-------------------------------------------------------------------Group by salary
grp = GROUP empls BY salary;
--Get count of employees in each salary group
cnt = FOREACH grp GENERATE group, COUNT(empls.id) as emp_cnt;
27


To view the schema of a relation
 DESCRIBE empls;



To view step-by-step execution of a series of statements
 ILLUSTRATE empls;



To view the execution plan of a relation
 EXPLAIN empls;



Join two data sets
LOAD 'data1' AS (col1, col2, col3, col4);
LOAD 'data2' AS (colA, colB, colC);
jnd = JOIN data1 BY col3, data2 BY colA PARALLEL 50;
STORE jnd INTO 'outfile‘;
28


Load using PigStorage
 empls = LOAD ‘employee.txt’ USING PigStorage('t')

AS (id:int, name:chararray, salary:double,
dept:chararray);



Store using PigStorage
 STORE srtd INTO ‘rich_employees.txt’ USING

PigStorage('t');

29
Flexibility with PIG
Is that all we can do with the PIG!!??

30


Pig provides extensive support for user-defined
functions (UDFs) as a way to specify custom
processing. Functions can be a part of almost
every operator in Pig



All UDF’s are case sensitive

31


Eval Functions (EvalFunc)
 Ex: StringConcat (built-in) : Generates the concatenation of the first two
fields of a tuple.



Aggregate Functions (EvalFunc & Algebraic)
 Ex: COUNT, AVG ( both built-in)



Filter Functions (FilterFunc)
 Ex: IsEmpty (built-in)



Load/Store Functions (LoadFunc/ StoreFunc)
 Ex: PigStorage (built-in)
Note: URL for built in functions:
http://pig.apache.org/docs/r0.7.0/api/org/apache/pig/builtin/package-summary.html

32


Piggy Bank
 Piggy Bank is a place for Pig users to share their functions



DataFu (Linkedin’s collection of UDF’s)
 Hadoop library for large-scale data processing

33
package myudfs;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.util.WrappedIOException;
public class UPPER extends EvalFunc <String>
{
public String exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try{
String str = (String)input.get(0);
return str.toUpperCase();
}catch(Exception e){
throw WrappedIOException.wrap("Caught exception processing input row ", e);
}
}
}
34
-- myscript.pig
 REGISTER myudfs.jar;
Note: myudfs.jar should not be surrounded with quotes

 A = LOAD 'employee_data' AS (id: int,name: chararray,

salary: double, dept: chararray);
 B = FOREACH A GENERATE myudfs.UPPER(name);
 DUMP B;
35




java -cp pig.jar org.apache.pig.Main -x local
myscript.pig
or
pig -x local myscript.pig

Note: myudfs.jar should be in class path!


Locating an UDF jar file
 Pig first checks the classpath.
 Pig assumes that the location is either an absolute path or a

path relative to the location from which Pig was invoked
36
Pig Type
bytearray
chararray
int
long
float
double
tuple
bag
map

Java Class
DataByteArray
String
Integer
Long
Float
Double
Tuple
DataBag
Map<Object, Object>

37
All is well, but.. What about the
performance trade offs?

38
Source: Yahoo
39
Q&A
Mail me :
shashidhar_hb@infosys.com

40
That’s all folks!

41

More Related Content

PDF
Introduction to pig & pig latin
knowbigdata
 
PDF
Hadoop pig
Sean Murphy
 
PPTX
Introduction to Pig | Pig Architecture | Pig Fundamentals
Skillspeed
 
PPTX
Apache pig power_tools_by_viswanath_gangavaram_r&d_dsg_i_labs
Viswanath Gangavaram
 
PDF
Introduction To Apache Pig at WHUG
Adam Kawa
 
PPTX
Introduction to Pig
Prashanth Babu
 
PPTX
Pig, Making Hadoop Easy
Nick Dimiduk
 
PDF
Pig Tutorial | Twitter Case Study | Apache Pig Script and Commands | Edureka
Edureka!
 
Introduction to pig & pig latin
knowbigdata
 
Hadoop pig
Sean Murphy
 
Introduction to Pig | Pig Architecture | Pig Fundamentals
Skillspeed
 
Apache pig power_tools_by_viswanath_gangavaram_r&d_dsg_i_labs
Viswanath Gangavaram
 
Introduction To Apache Pig at WHUG
Adam Kawa
 
Introduction to Pig
Prashanth Babu
 
Pig, Making Hadoop Easy
Nick Dimiduk
 
Pig Tutorial | Twitter Case Study | Apache Pig Script and Commands | Edureka
Edureka!
 

What's hot (20)

KEY
Hive vs Pig for HadoopSourceCodeReading
Mitsuharu Hamba
 
PDF
Big Data Hadoop Training
stratapps
 
PPTX
Pig programming is more fun: New features in Pig
daijy
 
PDF
Apache spark session
knowbigdata
 
PDF
introduction to data processing using Hadoop and Pig
Ricardo Varela
 
KEY
Getting Started on Hadoop
Paco Nathan
 
PDF
Apache Pig: Making data transformation easy
Victor Sanchez Anguix
 
PPT
Hadoop basics
Antonio Silveira
 
PPT
Introduction To Map Reduce
rantav
 
PPTX
Apache pig
Sadiq Basha
 
PDF
Hadoop Administration pdf
Edureka!
 
PPT
HIVE: Data Warehousing & Analytics on Hadoop
Zheng Shao
 
PPTX
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Simplilearn
 
PDF
Getting started with Hadoop, Hive, and Elastic MapReduce
obdit
 
PPT
Another Intro To Hadoop
Adeel Ahmad
 
PDF
Interview questions on Apache spark [part 2]
knowbigdata
 
PDF
Facebooks Petabyte Scale Data Warehouse using Hive and Hadoop
royans
 
PPT
Hadoop at Yahoo! -- University Talks
yhadoop
 
PDF
R, Hadoop and Amazon Web Services
Portland R User Group
 
PPT
Hadoop hive presentation
Arvind Kumar
 
Hive vs Pig for HadoopSourceCodeReading
Mitsuharu Hamba
 
Big Data Hadoop Training
stratapps
 
Pig programming is more fun: New features in Pig
daijy
 
Apache spark session
knowbigdata
 
introduction to data processing using Hadoop and Pig
Ricardo Varela
 
Getting Started on Hadoop
Paco Nathan
 
Apache Pig: Making data transformation easy
Victor Sanchez Anguix
 
Hadoop basics
Antonio Silveira
 
Introduction To Map Reduce
rantav
 
Apache pig
Sadiq Basha
 
Hadoop Administration pdf
Edureka!
 
HIVE: Data Warehousing & Analytics on Hadoop
Zheng Shao
 
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Simplilearn
 
Getting started with Hadoop, Hive, and Elastic MapReduce
obdit
 
Another Intro To Hadoop
Adeel Ahmad
 
Interview questions on Apache spark [part 2]
knowbigdata
 
Facebooks Petabyte Scale Data Warehouse using Hive and Hadoop
royans
 
Hadoop at Yahoo! -- University Talks
yhadoop
 
R, Hadoop and Amazon Web Services
Portland R User Group
 
Hadoop hive presentation
Arvind Kumar
 
Ad

Viewers also liked (17)

PPT
Hadoop and Hive
Zheng Shao
 
ODP
Hadoop Installation and basic configuration
Gerrit van Vuuren
 
PPT
Hive - SerDe and LazySerde
Zheng Shao
 
PPTX
Introduction to Apache Pig
Tapan Avasthi
 
PDF
Hive Functions Cheat Sheet
Hortonworks
 
PPTX
MapReduce Design Patterns
Donald Miner
 
PDF
Analytical Queries with Hive: SQL Windowing and Table Functions
DataWorks Summit
 
PDF
Optimizing Hive Queries
Owen O'Malley
 
PDF
Map reduce: beyond word count
Jeff Patti
 
PPTX
Hive: Loading Data
Benjamin Leonhardi
 
PPTX
How to understand and analyze Apache Hive query execution plan for performanc...
DataWorks Summit/Hadoop Summit
 
PPTX
Introduction to MapReduce | MapReduce Architecture | MapReduce Fundamentals
Skillspeed
 
PPT
Hive Object Model
Zheng Shao
 
PDF
Apache Hive 2.0 SQL, Speed, Scale by Alan Gates
Big Data Spain
 
DOC
Sql queires
MohitKumar1985
 
PDF
Hive tuning
Michael Zhang
 
PPT
Hadoop Real Life Use Case & MapReduce Details
Anju Singh
 
Hadoop and Hive
Zheng Shao
 
Hadoop Installation and basic configuration
Gerrit van Vuuren
 
Hive - SerDe and LazySerde
Zheng Shao
 
Introduction to Apache Pig
Tapan Avasthi
 
Hive Functions Cheat Sheet
Hortonworks
 
MapReduce Design Patterns
Donald Miner
 
Analytical Queries with Hive: SQL Windowing and Table Functions
DataWorks Summit
 
Optimizing Hive Queries
Owen O'Malley
 
Map reduce: beyond word count
Jeff Patti
 
Hive: Loading Data
Benjamin Leonhardi
 
How to understand and analyze Apache Hive query execution plan for performanc...
DataWorks Summit/Hadoop Summit
 
Introduction to MapReduce | MapReduce Architecture | MapReduce Fundamentals
Skillspeed
 
Hive Object Model
Zheng Shao
 
Apache Hive 2.0 SQL, Speed, Scale by Alan Gates
Big Data Spain
 
Sql queires
MohitKumar1985
 
Hive tuning
Michael Zhang
 
Hadoop Real Life Use Case & MapReduce Details
Anju Singh
 
Ad

Similar to Apache Pig (20)

PPTX
03 pig intro
Subhas Kumar Ghosh
 
PPTX
An Introduction to Apache Pig
Sachin Vakkund
 
PPTX
Pig_Presentation
Arjun Shah
 
PPTX
power point presentation on pig -hadoop framework
bhargavi804095
 
PDF
Sql saturday pig session (wes floyd) v2
Wes Floyd
 
PPTX
Introduction to PIG
Shanmathy Prabakaran
 
PDF
43_Sameer_Kumar_Das2
Mr.Sameer Kumar Das
 
PDF
Apache Pig: A big data processor
Tushar B Kute
 
PPTX
Pig power tools_by_viswanath_gangavaram
Viswanath Gangavaram
 
PPTX
Pig
madu mathicp
 
PPTX
Apache PIG
Prashant Gupta
 
PPTX
Introduction_to_Apache_Pig.pptx for lpu students
abcxyz19691969
 
PPTX
PigHive.pptx
DenizDural2
 
PPTX
Apache Hadoop India Summit 2011 talk "Pig - Making Hadoop Easy" by Alan Gate
Yahoo Developer Network
 
PDF
Unit V.pdf
KennyPratheepKumar
 
PDF
Practical pig
trihug
 
PPTX
Understanding Pig and Hive in Apache Hadoop
mohindrachinmay
 
PPTX
Pig
jramsingh
 
PDF
Pig
Vetri V
 
03 pig intro
Subhas Kumar Ghosh
 
An Introduction to Apache Pig
Sachin Vakkund
 
Pig_Presentation
Arjun Shah
 
power point presentation on pig -hadoop framework
bhargavi804095
 
Sql saturday pig session (wes floyd) v2
Wes Floyd
 
Introduction to PIG
Shanmathy Prabakaran
 
43_Sameer_Kumar_Das2
Mr.Sameer Kumar Das
 
Apache Pig: A big data processor
Tushar B Kute
 
Pig power tools_by_viswanath_gangavaram
Viswanath Gangavaram
 
Apache PIG
Prashant Gupta
 
Introduction_to_Apache_Pig.pptx for lpu students
abcxyz19691969
 
PigHive.pptx
DenizDural2
 
Apache Hadoop India Summit 2011 talk "Pig - Making Hadoop Easy" by Alan Gate
Yahoo Developer Network
 
Unit V.pdf
KennyPratheepKumar
 
Practical pig
trihug
 
Understanding Pig and Hive in Apache Hadoop
mohindrachinmay
 
Pig
Vetri V
 

Recently uploaded (20)

PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Doc9.....................................
SofiaCollazos
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 

Apache Pig

  • 2.        Why Hadoop Hadoop n The Cloud Industry Querying Large Data... Pig to Rescue Pig: Why? What? How? Pig Basics: Install, Configure, Try Dwelling Deeper into Pig-PigLatin Q&A 2
  • 3. You have 10x more DATA Than you did 3 years ago! MORE about your BUSINESS? BUT do you know 10x NO! 3
  • 4. A lot of data, BIG data! Information (The Big Picture) We are not able to effectively store and analyze all the data we have, so we are not able to see the big picture! 5
  • 5.  BigData / Web Scale: are datasets that grow so large that they become awkward to work with traditional database management tools  Handling Big Data using traditional approach is costly and rigid (Difficulties include capture, storage, search, sharing, analytics and visualization)  Google,Yahoo, Facebook, LinkedIn handles “Petabytes” of data everyday.  They all use HADOOP to solve there BIG DATA problem 6
  • 6. 7
  • 7. So Mr. HADOOP says he has a solution to our BIG problem ! 8
  • 8.  Hadoop is an open-source software for RELIABLE and SCALABLE distributed computing  Hadoop provides a comprehensive solution to handle Big Data  Hadoop is  HDFS : High Availability Data Storage subsystem (http://labs.google.com/papers/gfs.html: 2003) +  MapReduce: Parallel Processing system (http://labs.google.com/papers/mapreduce.html: 2004) 9
  • 9.  2008: Yahoo! Launched Hadoop  2009: Hadoop source code was made available to the free world  2010: Facebook claimed that they have the largest Hadoop cluster in the world with 21 PB of storage  2011: Facebook announced the data has grown to 30 PB 10
  • 10.  Stats :Facebook ▪ Started in 2004: 1 million users ▪ August 2008: Facebook reaches over 100 million active users ▪ Now: 750+ million active users “Bottom line.. More users more DATA”  The BIG challenge at Facebook!! Using historical data is a very big part of improving the user experience on Facebook. So storing and processing all these bytes is of immense importance. Facebook tried Hadoop for this. 11
  • 11. Hadoop turned out to be a great solution, but there was one little problem! 12
  • 12.   Map Reduce requires skilled JAVA programmers to write standard MapReduce programs Developers are more fluent in querying data using SQL “Pig says, No Problemo!” 13
  • 13.  Input: User profiles, Page visits  Find the top 5 most visited pages by users aged 18-25 14
  • 14. 15
  • 15. 1. Users = LOAD ‘users’ AS (name, age); 2. Filtered = FILTER Users BY age >= 18 AND age <= 25; 3. Pages = LOAD ‘pages’ AS (user, url); 4. Joined = JOIN Filtered BY name, Pages BY user; 5. Grouped = GROUP Joined BY url; 6. Summed = FOREACH Grouped generate GROUP, COUNT(Joined) AS clicks; 7. Sorted = ORDER Summed BY clicks DESC; 8. Top5 = LIMIT Sorted 5; 9. STORE Top5 INTO ‘top5sites’; 16
  • 16.  Pig is a dataflow language • Language is called PigLatin • Pretty simple syntax • Under the covers, PigLatin scripts are turned into MapReduce jobs and executed on the cluster  Pig Latin: High-level procedural language  Pig Engine: Parser, Optimizer and distributed query execution 17
  • 17. PIG      Pig is procedural Nested relational data model (No constraints on Data Types) Schema is optional Scan-centric analytic workloads (No Random reads or writes) Limited query optimization SQL      SQL is declarative Flat relational data model (Data is tied to a specific Data Type) Schema is required OLTP + OLAP workloads Significant opportunity for query optimization 18
  • 18. PIG  Users = load 'users' as (name, age, ipaddr);  Clicks = load 'clicks' as (user, url, value);  ValuableClicks = filter Clicks by value > 0;  UserClicks = join Users by name, ValuableClicks by user;   Geoinfo = load 'geoinfo' as (ipaddr, dma); UserGeo = join UserClicks by ipaddr, Geoinfo by ipaddr; ByDMA = group UserGeo by dma;  ValuableClicksPerDMA = foreach ByDMA generate group, COUNT(UserGeo); store ValuableClicksPerDMA into 'ValuableClicksPerDMA';  SQL insert into ValuableClicksPerDMA select dma, count(*) from geoinfo join ( select name, ipaddr from users join clicks on (users.name = clicks.user) where value > 0; ) using ipaddr group by dma; 19
  • 19.  Joining datasets  Grouping data  Referring to elements by position rather than name ($0, $1, etc)  Loading non-delimited data using a custom SerDe (Writing a custom Reader and Writer)  Creation of user-defined functions (UDF), written in Java  And more.. 20
  • 21. Pig runs as a client-side application. Even if you want to run Pig on a Hadoop cluster, there is nothing extra to install on the cluster: Pig launches jobs and interacts with HDFS (or other Hadoop file systems) from your workstation. Download a stable release from http://hadoop.apache.org/pig/releases.html and unpack the tarball in a suitable place on your workstation: % tar xzf pig-x.y.z.tar.gz It’s convenient to add Pig’s binary directory to your command-line path. For example: % export PIG_INSTALL=/home/tom/pig-x.y.z % export PATH=$PATH:$PIG_INSTALL/bin You also need to set the JAVA_HOME environment variable to point to suitable Java installation. 22
  • 22.  Execution Types  Local mode (pig -x local)  Hadoop mode  Pig must be configured to the cluster’s namenode and jobtracker 1. Put hadoop config directory in PIG classpath % export PIG_CLASSPATH=$HADOOP_INSTALL/conf/ 2. Create a pig.properties fs.default.name=hdfs://localhost/ mapred.job.tracker=localhost:8021 23
  • 23.  Script: Pig can run a script file that contains Pig commands. For example, % pig script.pig Runs the commands in the local file ”script.pig”. Alternatively, for very short scripts, you can use the -e option to run a script specified as a string on the command line.  Grunt: Grunt is an interactive shell for running Pig commands. Grunt is started when no file is specified for Pig to run, and the -e option is not used. Note: It is also possible to run Pig scripts from within Grunt using run and exec.  Embedded: You can run Pig programs from Java, much like you can use JDBC to run SQL programs from Java. There are more details on the Pig wiki at http://wiki.apache.org/pig/EmbeddedPig 24
  • 24.  PigLatin: A Pig Latin program consists of a collection of statements. A statement can be thought of as an operation, or a command For example, 1. A GROUP operation is a type of statement: grunt> grouped_records = GROUP records BY year; 2. The command to list the files in a Hadoop filesystem is another example of a statement: ls / 3. LOAD operation to load data from tab seperated file to PIG record grunt> records = LOAD ‘sample.txt’ AS (year:chararray, temperature:int, quality:int);  Data: In Pig, a single element of data is an atom A collection of atoms – such as a row, or a partial row – is a tuple Tuples are collected together into bags Atom –> Row/Partial Row –> Tuple –> Bag 25
  • 25. Example contents of ‘employee.txt’ a tab delimited text          1 Krishna 234000000 none 2 Krishna_01 234000000 none 124163 Shashi 10000 cloud 124164 Gopal 1000000 setlabs 124165 Govind 1000000 setlabs 124166 Ram 450000 es 124167 Madhusudhan 450000 e&r 124168 Hari 6500000 e&r 124169 Sachith 50000 cloud 26
  • 26. --Loading data from employee.txt into emps bag and with a schema empls = LOAD ‘employee.txt’ AS (id:int, name:chararray, salary:double, dept:chararray); --Filtering the data as required rich = FILTER empls BY $2 > 100000; --Sorting sortd = ORDER rich BY salary DESC; --Storing the final results STORE sortd INTO ‘rich_employees.txt’; -- Or alternatively we can dump the record on the screen DUMP sortd; -------------------------------------------------------------------Group by salary grp = GROUP empls BY salary; --Get count of employees in each salary group cnt = FOREACH grp GENERATE group, COUNT(empls.id) as emp_cnt; 27
  • 27.  To view the schema of a relation  DESCRIBE empls;  To view step-by-step execution of a series of statements  ILLUSTRATE empls;  To view the execution plan of a relation  EXPLAIN empls;  Join two data sets LOAD 'data1' AS (col1, col2, col3, col4); LOAD 'data2' AS (colA, colB, colC); jnd = JOIN data1 BY col3, data2 BY colA PARALLEL 50; STORE jnd INTO 'outfile‘; 28
  • 28.  Load using PigStorage  empls = LOAD ‘employee.txt’ USING PigStorage('t') AS (id:int, name:chararray, salary:double, dept:chararray);  Store using PigStorage  STORE srtd INTO ‘rich_employees.txt’ USING PigStorage('t'); 29
  • 29. Flexibility with PIG Is that all we can do with the PIG!!?? 30
  • 30.  Pig provides extensive support for user-defined functions (UDFs) as a way to specify custom processing. Functions can be a part of almost every operator in Pig  All UDF’s are case sensitive 31
  • 31.  Eval Functions (EvalFunc)  Ex: StringConcat (built-in) : Generates the concatenation of the first two fields of a tuple.  Aggregate Functions (EvalFunc & Algebraic)  Ex: COUNT, AVG ( both built-in)  Filter Functions (FilterFunc)  Ex: IsEmpty (built-in)  Load/Store Functions (LoadFunc/ StoreFunc)  Ex: PigStorage (built-in) Note: URL for built in functions: http://pig.apache.org/docs/r0.7.0/api/org/apache/pig/builtin/package-summary.html 32
  • 32.  Piggy Bank  Piggy Bank is a place for Pig users to share their functions  DataFu (Linkedin’s collection of UDF’s)  Hadoop library for large-scale data processing 33
  • 33. package myudfs; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.impl.util.WrappedIOException; public class UPPER extends EvalFunc <String> { public String exec(Tuple input) throws IOException { if (input == null || input.size() == 0) return null; try{ String str = (String)input.get(0); return str.toUpperCase(); }catch(Exception e){ throw WrappedIOException.wrap("Caught exception processing input row ", e); } } } 34
  • 34. -- myscript.pig  REGISTER myudfs.jar; Note: myudfs.jar should not be surrounded with quotes  A = LOAD 'employee_data' AS (id: int,name: chararray, salary: double, dept: chararray);  B = FOREACH A GENERATE myudfs.UPPER(name);  DUMP B; 35
  • 35.   java -cp pig.jar org.apache.pig.Main -x local myscript.pig or pig -x local myscript.pig Note: myudfs.jar should be in class path!  Locating an UDF jar file  Pig first checks the classpath.  Pig assumes that the location is either an absolute path or a path relative to the location from which Pig was invoked 36
  • 37. All is well, but.. What about the performance trade offs? 38

Editor's Notes

  • #7: BIG Data -  are datasets that grow so large that they become awkward to work with using on-hand database management tools. Difficulties include capture, storage,search, sharing, analytics, and visualizing.Data management system which is Highly Available, Reliable, Transparent, High Performance, Scalable, Accessible, Secure, Usable, and Inexpensive.
  • #8: Source: Wikipedia
  • #11: Source: Internet (Googling)
  • #12: Facebook statisticsURL: http://www.facebook.com/press/info.php?factsheet
  • #14: Img Source: Yahoohadoop website“Pig Makes Hadoop Easy to Drive”Pig Vs Hivehttp://developer.yahoo.com/blogs/hadoop/posts/2010/08/pig_and_hive_at_yahoo/Pig Vs SQLhttp://developer.yahoo.com/blogs/hadoop/posts/2010/01/comparing_pig_latin_and_sql_fo/
  • #15: Input: User profiles, PageVisitsFind the top 5 mostvisited pages by usersaged 18-25
  • #16: Input: User profiles, Page visitsFind the top 5 most visited pages by usersaged 18-25
  • #19: http://developer.yahoo.com/blogs/hadoop/posts/2010/01/comparing_pig_latin_and_sql_fo/insert into ValuableClicksPerDMA select dma, count(*) from geoinfo join ( select name, ipaddr from users join clicks on (users.name = clicks.user) where value &gt; 0; ) using ipaddr group by dma; The Pig Latin for this will look like:Users = load &apos;users&apos; as (name, age, ipaddr); Clicks = load &apos;clicks&apos; as (user, url, value); ValuableClicks = filter Clicks by value &gt; 0;UserClicks = join Users by name, ValuableClicks by user; Geoinfo = load &apos;geoinfo&apos; as (ipaddr, dma);UserGeo = join UserClicks by ipaddr, Geoinfo by ipaddr; ByDMA = group UserGeo by dma; ValuableClicksPerDMA = foreachByDMA generate group, COUNT(UserGeo); store ValuableClicksPerDMA into &apos;ValuableClicksPerDMA&apos;;
  • #20: http://developer.yahoo.com/blogs/hadoop/posts/2010/01/comparing_pig_latin_and_sql_fo/insert into ValuableClicksPerDMA select dma, count(*) from geoinfo join ( select name, ipaddr from users join clicks on (users.name = clicks.user) where value &gt; 0; ) using ipaddr group by dma; The Pig Latin for this will look like:Users = load &apos;users&apos; as (name, age, ipaddr); Clicks = load &apos;clicks&apos; as (user, url, value); ValuableClicks = filter Clicks by value &gt; 0;UserClicks = join Users by name, ValuableClicks by user; Geoinfo = load &apos;geoinfo&apos; as (ipaddr, dma);UserGeo = join UserClicks by ipaddr, Geoinfo by ipaddr; ByDMA = group UserGeo by dma; ValuableClicksPerDMA = foreachByDMA generate group, COUNT(UserGeo); store ValuableClicksPerDMA into &apos;ValuableClicksPerDMA&apos;;
  • #21: SerDe - Serializer/Deserializer
  • #24: Execution TypesPig has two execution types or modes: local mode and Hadoop mode.Local mode (pig -x local)In local mode, Pig runs in a single JVM and accesses the local filesystem. This mode issuitable only for small datasets, and when trying out Pig. Local mode does not useHadoop. In particular, it does not use Hadoop’s local job runner; instead, Pig translatesqueries into a physical plan that it executes itself.Hadoop modeIn Hadoop mode, Pig translates queries into MapReduce jobs and runs them on aHadoop cluster. The cluster may be a pseudo- or fully distributed cluster. Hadoop mode(with a fully distributed cluster) is what you use when you want to run Pig on largedatasets.
  • #25: import java.io.IOException;import org.apache.pig.PigServer;public class WordCount { public static void main(String[] args) {PigServerpigServer = new PigServer(); try {pigServer.registerJar(&quot;/mylocation/tokenize.jar&quot;);runMyQuery(pigServer, &quot;myinput.txt&quot;; } catch (IOExceptione) {e.printStackTrace(); } } public static void runMyQuery(PigServerpigServer, String inputFile) throws IOException { pigServer.registerQuery(&quot;A = load &apos;&quot; + inputFile + &quot;&apos; using TextLoader();&quot;);pigServer.registerQuery(&quot;B = foreach A generate flatten(tokenize($0));&quot;);pigServer.registerQuery(&quot;C = group B by $1;&quot;);pigServer.registerQuery(&quot;D = foreach C generate flatten(group), COUNT(B.$0);&quot;);pigServer.store(&quot;D&quot;, &quot;myoutput&quot;); }}
  • #26: PIG | RDBMSAtom ~ CellTuple ~ RowBags ~ Table
  • #27: Example contents of ‘employee.txt’ a tab delimited text1 Krishna 234000000 none2 Krishna_01 234000000 none124163 Shashi 10000 cloud124164 Gopal 1000000 setlabs124165 Govind 1000000 setlabs124166 Ram 450000 es124167 Madhusudhan 450000 e&amp;r124168 Hari 6500000 e&amp;r124169 Sachith 50000 cloud
  • #28: Example contents of ‘people.txt’ a tab delimited text1 Krishna 234000000 none2 Krishna_01 234000000 none124163 Shashi 10000 cloud124164 Gopal 1000000 setlabs124165 Govind 1000000 setlabs124166 Ram 450000 es124167 Madhusudhan 450000 e&amp;r124168 Hari 6500000 e&amp;r124169 Sachith 50000 cloud --Loading data from people.txt into emps bag and with a schemaemps = LOAD &apos;people.txt&apos; AS (id:int, name:chararray, salary:double, dept:chararray); --Filtering the data as requiredrich = FILTER emps BY $2 &gt; 100000; --Sortingsrtd = ORDER rich BY salary DESC; --Storing the final resultsSTORE srtd INTO &apos;rich_people.txt&apos;;-- Or alternatively we can dump the record on the screenDUMP srtd;Import data using SQOOP1.Import moviesqoop import \--connect jdbc:mysql://localhost/movielens \--table movie --fields-terminated-by &apos;\t&apos; \--username training --password training2. Import movieratingsqoop import \--connect jdbc:mysql://localhost/movielens \--table movierating --fields-terminated-by &apos;\t&apos; \--username training --password training
  • #29: PARALLEL keyword only effects the number of reduce tasks. Map parallelism is determined by the input file, one map for each HDFS block. At most 2 map or reduce tasks can run on a machine simultaneously.grunt&gt; personal = load &apos;personal.txt&apos; as (empid,name,phonenumber);grunt&gt; official = load &apos;official.txt&apos; as (empid,dept,dc); grunt&gt; joined = join personal by empid, official by empid;grunt&gt; dump joined;
  • #33: http://pig.apache.org/docs/r0.7.0/udf.htmlEval FunctionsEval is the most common type of function How to write? UPPER extends EvalFunc Code snippet -- myscript.pig REGISTER myudfs.jar; A = LOAD &apos;employee_data&apos; AS (id: int,name: chararray, salary: double, dept: chararray); B = FOREACH A GENERATE myudfs.UPPER(name); DUMP B; Sample UDF package myudfs; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.impl.util.WrappedIOException; public class UPPER extends EvalFunc (String) { public String exec(Tuple input) throws IOException { if (input == null || input.size() == 0) return null; try{ String str = (String)input.get(0); return str.toUpperCase(); }catch(Exception e){ throw WrappedIOException.wrap(&quot;Caught exception processing input row &quot;, e); } } } How to execute the above script? java -cp pig.jar org.apache.pig.Main -x local myscript.pig or pig -x local myscript.pig &quot;Note: myudfs.jar should be in class path!&quot;Aggregate Functions An aggregate function is an eval function that takes a bag and returns a scalar value. One interesting and useful property of many aggregate functions is that they can be computed incrementally in a distributed fashion. Aggregate functions are usually applied to grouped data. How to write? COUNT extends EvalFunc (Long) implements Algebraic Ex: COUNT, AVG (built-in)Filter Functions Filter functions are eval functions that return a boolean value. Filter functions can be used anywhere a Boolean expression is appropriate, including the FILTER operator. Ex: IsEmpty (built-in) How to write?IsEmpty extends FilterFunc How to use it? D = FILTER C BY not IsEmpty(A);Load/Store Functions The load/store user-defined functions control how data goes into Pig and comes out of Pig. Often, the same function handles both input and output but that does not have to be the case. Ex: PigStorage (built-in) How to write? LOAD: SimpleTextLoader extends LoadFunc STORE: SimpleTextStorer extends StoreFunc
  • #35: Tuple: An ordered list of Data. A tuple has fields, numbered 0 through (number of fields - 1). The entry in the field can be any datatype, or it can be null. Tuples are constructed only by a TupleFactory. A DefaultTupleFactory is provided by the system. If a user wishes to use their own type of Tuple, they should also provide an implementation of TupleFactory to construct their types of Tuples. Fields are numbered from 0.