How To Process Data with Apache Pig

This Hadoop tutorial is from the Hortonworks Sandbox – a single-node Hadoop cluster running in a virtual machine. Download to run this and other tutorials in the series.

This tutorial was derived from material in the Hortonworks developer training. These classes cover uses of the tools in the Hortonworks Data Platform and how to develop applications and projects using the Hortonworks Data Platform. You can find more information about this subject at Data Analysis with Pig & Hive

Hortonworks Hadoop Essentials Video

What is Pig?

Pig is a high level scripting language that is used with Apache Hadoop. Pig excels at describing data analysis problems as data flows. Pig is complete in that you can do all the required data manipulations in Apache Hadoop with Pig. In addition through the User Defined Functions(UDF) facility in Pig you can have Pig invoke code in many languages like JRuby, Jython and Java. Conversely you can execute Pig scripts in other languages. The result is that you can use Pig as a component to build larger and more complex applications that tackle real business problems.

A good example of a Pig application is the ETL transaction model that describes how a process will extract data from a source, transform it according to a rule set and then load it into a datastore. Pig can ingest data from files, streams or other sources using the User Defined Functions(UDF). Once it has the data it can perform select, iteration, and other transforms over the data. Again the UDF feature allows passing the data to more complex algorithms for the transform. Finally Pig can store the results into the Hadoop Data File System.

Pig scripts are translated into a series of MapReduce jobs that are run on the Apache Hadoop cluster. As part of the translation the Pig interpreter does perform optimizations to speed execution on Apache Hadoop. We are going to write a Pig script that will do our data analysis task.

Our data processing task

We are going to read in a baseball statistics file. We are going to compute the highest runs by a player for each year. This file has all the statistics from 1871-2011 and it contains over 90,000 rows. Once we have the highest runs we will extend the script to translate a player id field into the first and last names of the players.

Downloading the data

The data file we are using comes from the site www.seanlahman.com. You can download the data file in csv zip form from:

http://seanlahman.com/files/database/lahman591-csv.zip

Once you have the file you will need to unzip the file into a directory. We will be uploading just the master.csv and batting.csv files.

Uploading the data files

We start by selecting the File Browser from the top tool bar. The File Browser allows us to view the Hortonworks Data Platform(HDP) file store. This is separate from the local file system. In a Hadoop cluster this would be your view of the Hadoop Data File System(HDFS). For the Hortonworks Sandbox it will be part of the file system in the Hortonworks Sandbox VM.

Click on the Upload button to select the files we want to upload into the Hortonworks Sandbox environment.

You want to select Files. Then you will get a dialog box.

When you click on the Upload a file button you will get a dialog box. Navigate to where you stored the Batting.csv file on your local disk and select Batting.csv. Do the same thing for Master.csv. When you are done you will see there are two files in your directory.

Now that we have our data files we can start writing our Pig script. Click on the Pig icon at the top of the screen.

/p>

We see the Pig user interface in our browser window. On the left is a list of the saved scripts. On the right is the composition area where we will be writing our script. Below the composition area are buttons to Save, Execute, Explain and perform a Syntax check of the current script. At the very bottom are status boxes where we will see logs, error message and the output of our script.

To get started fill in a name for your script. You can not save it until we add our first line of code. The first thing we need to do is load the data. We use the load statement for this. The PigStorage function is what does the loading and we pass it a comma as the data delimiter. Our code is:

batting = load 'Batting.csv' using PigStorage(',');

The next thing we want to do is name the fields. We will use a FOREACH statement to iterate through the batting data object. We can use Pig Helper that is at the bottom of the composition area to provide us with a template. We will click on Pig Helper, select Data processing functions and then click on the FOREACH template. We can then replace each element by hitting the tab key.

So the FOREACH statement will iterate through the batting data object and GENERATE pulls out selected fields and assigns them names. The new data object we are creating is then named runs. Our code will now be:

runs = FOREACH batting GENERATE $0 as playerID, $1 as year, $8 as runs;

The next line of code is a group statement that groups the elements in runs by the year field. So the grp_data object will then be indexed by year. In the next statement as we iterate through grp_data we will go through year by year. Type in the code:

grp_data = GROUP runs by (year);

In the next FOREACH statement we are going to find the maximum runs for each year. The code for this is:

max_runs = FOREACH grp_data GENERATE group as grp,MAX(runs.runs) as max_runs;

Now that we have the maximum runs we need to join this with the runs data object so we can pick up the player id. The result will be a dataset with Year, PlayerID and Max Run. At the end we dump the data to the output.

join_max_run = JOIN max_runs by ($0, max_runs), runs by (year,runs);
join_data = FOREACH join_max_run GENERATE $0 as year, $2 as playerID, $1 as runs;
dump join_data;

Let’s take a look at our script. The first thing to notice is we never really address single rows of data to the left of the equals sign and on the right we just describe what we want to do for each row. We just assume things are applied to all the rows. We also have powerful operators like GROUP and JOIN to sort rows by a key and to build new data objects.

At this point we can save our script. Fill in a name in the box below “Pig script:” if you haven’t already. Click on the save button and the your script will show up in the bar on the left.

We can execute our code by clicking on the execute button at the bottom of the composition area. As the jobs are run you will get a progress bar at the bottom.

When the job completes the results are displaying in the green box at the bottom.

If you scroll down to the “Logs…” and click on the link you can see the log file of your jobs.

So we have created a simple Pig script that reads in some comma separated data. Once we have that set of records in Pig we pull out the playerID, year and runs fields from each row. We them sort them by year with one statement, GROUP. Then for each year we find the maximum runs. This is finally mapped to the playerID and we produce our final dataset.

As mentioned before Pig operates on data flows. We consider each group of rows together and we specify how we operate on them as a group. As the datasets get larger and/or add fields our Pig script will remain pretty much the same because it is concentrating on how we want to manipulate the data.

Comments

Matt
|
July 8, 2014 at 11:46 pm
|

Hi All, Wonder if someone could help me, As a complete neophyte with Hadoop and Pig I could do with some basic explaination of what exactly is happening in the code below, a step by step guide as to what is actually happening under the covers, can any one help me or guide me to a website that would assist:

max_runs = FOREACH grp_data GENERATE group as grp,MAX(runs.runs) as max_runs;

I understand this much:
Create a relation called “max_runs” this is created by stepping through each row in the “grp_data” relation and creating…

Then I’m kind of lost, I know what the the output is, but I don’t really UNDERSTAND well enough to take this away and apply it elsewhere

Thanks for any help

Stefan
|
July 7, 2014 at 2:17 am
|

HI, the reason the code does not work is that the first line of Battings.csv contains column descriptions. Therefore Aran’s code filters the runs and creates the raw_runs which eliminate the first row.

Elmer Buard
|
July 5, 2014 at 2:39 pm
|

Cannot get either code to execute wothout errors;
batting = LOAD ‘Batting.csv’ USING PigStorage(‘,’);
raw_runs = FILTER batting BY $1>0;
runs = FOREACH raw_runs GENERATE $0 AS playerID, $1 AS year, $8 AS runs;
grp_data = GROUP runs BY (year);
max_runs = FOREACH grp_data GENERATE group as grp, MAX(runs.runs) AS max_runs;
join_max_runs = JOIN max_runs BY ($0, max_runs), runs BY (year, runs);
join_data = FOREACH join_max_runs GENERATE $0 AS year, $2 AS playerID, $1 AS runs;
DUMP join_data;

Rajesh Toleti
|
July 3, 2014 at 4:01 am
|

To make above code working please remove headers from ‘batting.csv’ file

|
July 2, 2014 at 12:47 am
|

and well, the problem is that you should add this lien of script “raw_runs = FILTER batting BY $1>0;” , because we must filter out the first line of data (header line)
which is this one:
playerID,yearID,stint,teamID,lgID,G,G_batting,AB,R,H,2B,3B,HR,RBI,SB,CS,BB,SO,IBB,HBP,SH,SF,GIDP,G_old

Greg
|
June 23, 2014 at 9:08 am
|

just installed Vbox appliance and have some probles to follow the tutorial: How to process data with apache pig. the example code raises the following error:
2014-06-23 09:02:51,080 [main] INFO org.apache.pig.Main – Apache Pig version 0.12.1.2.1.1.0-385 (rexported) compiled Apr 16 2014, 15:59:00
2014-06-23 09:02:51,081 [main] INFO org.apache.pig.Main – Logging error messages to: /hadoop/yarn/local/usercache/hue/appcache/application_1403539156648_0001/container_1403539156648_0001_01_000002/pig_1403539371077.log
2014-06-23 09:02:52,030 [main] INFO org.apache.pig.impl.util.Utils – Default bootup file /home/yarn/.pigbootup not found
2014-06-23 09:02:52,249 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
2014-06-23 09:02:52,249 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:52,250 [main] INFO org.apache.pig.backend.hadoop.executionengine.HExecutionEngine – Connecting to hadoop file system at: hdfs://sandbox.hortonworks.com:8020
2014-06-23 09:02:52,952 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:52,997 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,034 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,073 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,119 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,225 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,260 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,295 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,329 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,365 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:53,424 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
2014-06-23 09:02:54,663 [main] ERROR org.apache.pig.tools.grunt.Grunt – ERROR 1070: Could not resolve max using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Details at logfile: /hadoop/yarn/local/usercache/hue/appcache/application_1403539156648_0001/container_1403539156648_0001_01_000002/pig_1403539371077.log

Joe Quint
|
June 20, 2014 at 1:49 pm
|

BTW, if you follow the tutorial closely the author used the sandbox folder so the load should look like:

batting = LOAD ‘sandbox/Batting.csv’ using PigStorage(‘,’);

Rajesh
|
June 20, 2014 at 10:24 am
|

What was the cause of failure? Was there any record with null as “year”?

David Hawke
|
June 8, 2014 at 12:01 pm
|

Thanks Aran! your code worked. Why do you think the raw_runs filter is needed though if you don’t mind sharing?
Also the error message I was getting is that the pig loader was failing to find the Batting.csv file which was very misleading.

Donald
|
May 29, 2014 at 1:21 pm
|

The information in this tutorial is helpful.

I have noticed that the file ‘Batting.csv’ contains column headings in the first record. This causes a problem during the execution of the script. Removing the first record from the file can make the script functional. This is a suggestion.

Patrick Alexander
|
May 19, 2014 at 5:04 pm
|

Input(s):
Failed to read data from “hdfs://sandbox.hortonworks.com:8020/user/hue/Batting.csv”

batting = load ‘Batting.csv’ using PigStorage(‘,’);
not loading any data !!

what if the source data is loaded into a sub-directory ? what is the correct script to load data from the sub-directory ?

Patrick Alexander
|
May 19, 2014 at 4:59 pm
|

batting = load ‘Batting.csv’ using PigStorage(‘,’);
not loading any data !!

what if the source data is loaded into a sub-directory ? what is the correct script to load data from the sub-directory ?

Patrick Alexander
|
May 19, 2014 at 4:43 pm
|

how should I load the file if I didn’t put it on root ?
batting = load ‘test2/lahman591-csv/Batting.csv’ using PigStorage(‘,’);
this is failing !

Vahid
|
May 16, 2014 at 2:17 pm
|

I have a problem with all my pig scripts on sandbox and all were failed.

ls: cannot access /usr/lib/hive/lib/slf4j-api-*.jar: No such file or directory

It would be great if you can help me!

Aran
|
May 5, 2014 at 9:41 pm
|

The code doesn’t work. I found a working version on your forum:

batting = LOAD ‘Batting.csv’ USING PigStorage(‘,’);
raw_runs = FILTER batting BY $1>0;
runs = FOREACH raw_runs GENERATE $0 AS playerID, $1 AS year, $8 AS runs;
grp_data = GROUP runs BY (year);
max_runs = FOREACH grp_data GENERATE group as grp, MAX(runs.runs) AS max_runs;
join_max_runs = JOIN max_runs BY ($0, max_runs), runs BY (year, runs);
join_data = FOREACH join_max_runs GENERATE $0 AS year, $2 AS playerID, $1 AS runs;
DUMP join_data;

    Satya
    |
    July 17, 2014 at 3:03 pm
    |

    Thanks Aran for the working code. It looks like the Filter statement made the code to work.

    Chris H.
    |
    July 3, 2014 at 1:15 pm
    |

    Thanks for reposting this Aran, it was very helpful.

    |
    July 2, 2014 at 12:41 am
    |

    Thank you Aran, It has been a while and it seems like no one manages this tutorial.
    For those who could not make the tutorial script run, try the one from Aran.

    Ben
    |
    June 30, 2014 at 2:03 pm
    |

    Thank you!

    Piotr Sobolewski
    |
    June 25, 2014 at 12:27 pm
    |

    Thanks for this solution. It works.

    Mauricio
    |
    June 18, 2014 at 6:59 pm
    |

    Thanks Aran for sharing the code in this forum. Well, actually the code example is not wrong in terms of logical flow, but it is corrupted in line 5 when the statement “join_max_run = JOIN max_runs by ($0, max_runs), runs by (year,runs);” does have 1 misspelling mistake. If you see at the expression “(year,runs)” is not separated by a space between the variables, so this simple error will crash the job. I’ve spent a lot of time debugging jobs for misspelling mistakes that I can tell they are a pain in the heck. I hope you will find this post useful.

    Keith
    |
    June 13, 2014 at 8:06 am
    |

    Thank you Aran, your version of the code works for me.

    Anand
    |
    June 10, 2014 at 8:34 pm
    |

    I am getting a bunch of errors when I try running this

    ls: cannot access /usr/lib/hive/lib/slf4j-api-*.jar: No such file or directory
    2014-06-10 20:31:04,641 [main] INFO org.apache.pig.Main – Apache Pig version 0.12.1.2.1.1.0-385 (rexported) compiled Apr 16 2014, 15:59:00
    2014-06-10 20:31:04,642 [main] INFO org.apache.pig.Main – Logging error messages to: /hadoop/yarn/local/usercache/hue/appcache/application_1402456675484_0003/container_1402456675484_0003_01_000002/pig_1402457464639.log
    2014-06-10 20:31:05,503 [main] INFO org.apache.pig.impl.util.Utils – Default bootup file /home/yarn/.pigbootup not found
    2014-06-10 20:31:05,656 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
    2014-06-10 20:31:05,656 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:05,656 [main] INFO org.apache.pig.backend.hadoop.executionengine.HExecutionEngine – Connecting to hadoop file system at: hdfs://sandbox.hortonworks.com:8020
    2014-06-10 20:31:06,288 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,324 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,356 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,389 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,416 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,419 [main] WARN org.apache.pig.PigServer – Empty string specified for jar path
    2014-06-10 20:31:06,490 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,539 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,592 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    2014-06-10 20:31:06,641 [main] INFO org.apache.hadoop.conf.Configuration.deprecation – fs.default.name is deprecated. Instead, use fs.defaultFS
    Unexpected character ‘‘’
    2014-06-10 20:31:06,828 [main] ERROR org.apache.pig.PigServer – exception during parsing: Error during parsing. Unexpected character ‘‘’
    Failed to parse: Unexpected character ‘‘’
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:243)
    at org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:179)
    at org.apache.pig.PigServer$Graph.parseQuery(PigServer.java:1678)
    at org.apache.pig.PigServer$Graph.access$000(PigServer.java:1411)
    at org.apache.pig.PigServer.parseAndBuild(PigServer.java:344)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:369)
    at org.apache.pig.PigServer.executeBatch(PigServer.java:355)
    at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:140)
    at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:769)
    at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:372)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:198)
    at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:173)
    at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
    at org.apache.pig.Main.run(Main.java:478)
    at org.apache.pig.Main.main(Main.java:156)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
    2014-06-10 20:31:06,832 [main] ERROR org.apache.pig.tools.grunt.Grunt – ERROR 1200: Unexpected character ‘‘’

    Jim M
    |
    June 8, 2014 at 2:32 am
    |

    Thank you for posting this here, Aran. Helped me get through this tutorial.

Jack Price
|
May 1, 2014 at 7:14 am
|

I have created the pig script and it works but how do I download the scripts once I have done the lab. Where exactly is the directory for the scripts – if I wanted to use the hue file browser to download the scripts.

It’s very frustrating to not be able to find the pig scripts – even though I can see the scripts in ‘My Scripts’ of Pig in Hue.

Please help!

Ethels
|
February 14, 2014 at 10:35 am
|

This was really insightful and inspiring. Thank you so much for this, I really appreciate you guys.

Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

If you have specific technical questions, please post them in the Forums

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>