Passing parameters to Pig scripts

The Pig scripting language Pig Latin allows for parameter substitution at run-time.  Like any script, the ability to define parameters makes it far easier to share code with other users.  To do this in Pig Latin, you simply modify your script as shown below:

ALL_PLAYER_STATS = load '/user/hduser/baseball/batting/*.csv' using PigStorage (',') as ( playerID:chararray, teamID:chararray, yearID:int);
FILTERED_TEAM = filter ALL_PLAYER_STATS by teamID == '$TEAMID';
dump FILTERED_TEAM;

Then, when you want to execute your script you specify the value like this:

pig -x mapreduce -p TEAMID=BOS batting.pig

Failure to specify the parameter at run-time will throw the following error:

ERROR org.apache.pig.Main - ERROR 2999: Unexpected internal error. Undefined parameter : TEAMID

You can specify as many parameters as you like with the -p option.  For example:

ALL_PLAYER_STATS = load '/user/hduser/baseball/batting/*csv' using PigStorage (',') as
    ( playerID:chararray, teamID:chararray, yearID:int);
FILTERED_TEAM = filter ALL_PLAYER_STATS by teamID == '$TEAMID' and yearID >= $MIN_YEAR; 
dump FILTERED_TEAM;

Notice that because yearID is defined as int in my schema that I dropped the single quotes around it.  Failure to do so will cause Pig to treat the value as a string – which will not match the type defined in the schema.  The error you’ll see is:

ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1039: 
<file test.pig, line 2, column 50> In alias FILTERED_TEAM, incompatible 
types in GreaterThanEqual Operator left hand side:int right hand side:chararray

To execute the multi-parameter script:

pig -x mapreduce -p TEAMID=NYY -p YEARID=2001 batting.pig

Advertisements
This entry was posted in hadoop, pig, scripting and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s