You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pig.apache.org by bi...@apache.org on 2013/04/02 05:32:42 UTC

svn commit: r1463367 [10/11] - in /pig/site: author/src/documentation/content/xdocs/ publish/ publish/docs/r0.11.1/ publish/docs/r0.11.1/images/ publish/docs/r0.11.1/skin/ publish/docs/r0.11.1/skin/css/ publish/docs/r0.11.1/skin/images/ publish/docs/r0...

Added: pig/site/publish/docs/r0.11.1/udf.html
URL: http://svn.apache.org/viewvc/pig/site/publish/docs/r0.11.1/udf.html?rev=1463367&view=auto
==============================================================================
--- pig/site/publish/docs/r0.11.1/udf.html (added)
+++ pig/site/publish/docs/r0.11.1/udf.html Tue Apr  2 03:32:39 2013
@@ -0,0 +1,2204 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<meta content="Apache Forrest" name="Generator">
+<meta name="Forrest-version" content="0.9">
+<meta name="Forrest-skin-name" content="pelt">
+<title>User Defined Functions</title>
+<link type="text/css" href="skin/basic.css" rel="stylesheet">
+<link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
+<link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
+<link type="text/css" href="skin/profile.css" rel="stylesheet">
+<script src="skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="skin/fontsize.js" language="javascript" type="text/javascript"></script>
+<link rel="shortcut icon" href="">
+</head>
+<body onload="init()">
+<script type="text/javascript">ndeSetTextSize();</script>
+<div id="top">
+<!--+
+    |breadtrail
+    +-->
+<div class="breadtrail">
+<a href="http://www.apache.org/">Apache</a> &gt; <a href="http://hadoop.apache.org/">Hadoop</a> &gt; <a href="http://hadoop.apache.org/pig/">Pig</a><script src="skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
+</div>
+<!--+
+    |header
+    +-->
+<div class="header">
+<!--+
+    |start group logo
+    +-->
+<div class="grouplogo">
+<a href="http://hadoop.apache.org/"><img class="logoImage" alt="Hadoop" src="images/hadoop-logo.jpg" title="Apache Hadoop"></a>
+</div>
+<!--+
+    |end group logo
+    +-->
+<!--+
+    |start Project Logo
+    +-->
+<div class="projectlogo">
+<a href="http://hadoop.apache.org/pig/"><img class="logoImage" alt="Pig" src="images/pig-logo.gif" title="A platform for analyzing large datasets."></a>
+</div>
+<!--+
+    |end Project Logo
+    +-->
+<!--+
+    |start Search
+    +-->
+<div class="searchbox">
+<form action="http://www.google.com/search" method="get" class="roundtopsmall">
+<input value="" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">&nbsp; 
+                    <input name="Search" value="Search" type="submit">
+</form>
+</div>
+<!--+
+    |end search
+    +-->
+<!--+
+    |start Tabs
+    +-->
+<ul id="tabs">
+<li>
+<a class="unselected" href="http://hadoop.apache.org/pig/">Project</a>
+</li>
+<li>
+<a class="unselected" href="http://wiki.apache.org/pig/">Wiki</a>
+</li>
+<li class="current">
+<a class="selected" href="index.html">Pig 0.11.1 Documentation</a>
+</li>
+</ul>
+<!--+
+    |end Tabs
+    +-->
+</div>
+</div>
+<div id="main">
+<div id="publishedStrip">
+<!--+
+    |start Subtabs
+    +-->
+<div id="level2tabs"></div>
+<!--+
+    |end Endtabs
+    +-->
+<script type="text/javascript"><!--
+document.write("Last Published: " + document.lastModified);
+//  --></script>
+</div>
+<!--+
+    |breadtrail
+    +-->
+<div class="breadtrail">
+
+             &nbsp;
+           </div>
+<!--+
+    |start Menu, mainarea
+    +-->
+<!--+
+    |start Menu
+    +-->
+<div id="menu">
+<div onclick="SwitchMenu('menu_selected_1.1', 'skin/')" id="menu_selected_1.1Title" class="menutitle" style="background-image: url('skin/images/chapter_open.gif');">Pig</div>
+<div id="menu_selected_1.1" class="selectedmenuitemgroup" style="display: block;">
+<div class="menuitem">
+<a href="index.html">Overview</a>
+</div>
+<div class="menuitem">
+<a href="start.html">Getting Started</a>
+</div>
+<div class="menuitem">
+<a href="basic.html">Pig Latin Basics</a>
+</div>
+<div class="menuitem">
+<a href="func.html">Built In Functions</a>
+</div>
+<div class="menupage">
+<div class="menupagetitle">User Defined Functions</div>
+</div>
+<div class="menuitem">
+<a href="cont.html">Control Structures</a>
+</div>
+<div class="menuitem">
+<a href="cmds.html">Shell and Utililty Commands</a>
+</div>
+<div class="menuitem">
+<a href="perf.html">Performance and Efficiency</a>
+</div>
+<div class="menuitem">
+<a href="test.html">Testing and Diagnostics</a>
+</div>
+<div class="menuitem">
+<a href="pig-index.html">Index</a>
+</div>
+</div>
+<div onclick="SwitchMenu('menu_1.2', 'skin/')" id="menu_1.2Title" class="menutitle">Miscellaneous</div>
+<div id="menu_1.2" class="menuitemgroup">
+<div class="menuitem">
+<a href="api/">API Docs</a>
+</div>
+<div class="menuitem">
+<a href="jdiff/changes.html">API Changes</a>
+</div>
+<div class="menuitem">
+<a href="https://cwiki.apache.org/confluence/display/PIG">Wiki</a>
+</div>
+<div class="menuitem">
+<a href="https://cwiki.apache.org/confluence/display/PIG/FAQ">FAQ</a>
+</div>
+<div class="menuitem">
+<a href="http://hadoop.apache.org/pig/releases.html">Release Notes</a>
+</div>
+</div>
+<div id="credit"></div>
+<div id="roundbottom">
+<img style="display: none" class="corner" height="15" width="15" alt="" src="skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
+<!--+
+  |alternative credits
+  +-->
+<div id="credit2"></div>
+</div>
+<!--+
+    |end Menu
+    +-->
+<!--+
+    |start content
+    +-->
+<div id="content">
+<div title="Portable Document Format" class="pdflink">
+<a class="dida" href="udf.pdf"><img alt="PDF -icon" src="skin/images/pdfdoc.gif" class="skin"><br>
+        PDF</a>
+</div>
+<h1>User Defined Functions</h1>
+<div id="front-matter">
+<div id="minitoc-area">
+<ul class="minitoc">
+<li>
+<a href="#udfs">Introduction</a>
+</li>
+<li>
+<a href="#udf-java">Writing Java UDFs</a>
+<ul class="minitoc">
+<li>
+<a href="#eval-functions">Eval Functions</a>
+</li>
+<li>
+<a href="#load-store-functions"> Load/Store Functions</a>
+</li>
+<li>
+<a href="#Advanced+Topics">Advanced Topics</a>
+</li>
+</ul>
+</li>
+<li>
+<a href="#python-udfs">Writing Python UDFs</a>
+<ul class="minitoc">
+<li>
+<a href="#register-python">Registering the UDF</a>
+</li>
+<li>
+<a href="#decorators">Decorators and Schemas</a>
+</li>
+<li>
+<a href="#Example+Scripts">Example Scripts</a>
+</li>
+<li>
+<a href="#python-advanced">Advanced Topics</a>
+</li>
+</ul>
+</li>
+<li>
+<a href="#js-udfs">Writing JavaScript UDFs</a>
+<ul class="minitoc">
+<li>
+<a href="#register-js">Registering the UDF</a>
+</li>
+<li>
+<a href="#schema-return-types">Return Types and Schemas</a>
+</li>
+<li>
+<a href="#js-example">Example Scripts</a>
+</li>
+<li>
+<a href="#js-advanced">Advanced Topics</a>
+</li>
+</ul>
+</li>
+<li>
+<a href="#jruby-udfs">Writing Ruby UDFs</a>
+<ul class="minitoc">
+<li>
+<a href="#write-jruby">Writing a Ruby UDF</a>
+</li>
+<li>
+<a href="#jruby-schema-return-types">Return Types and Schemas</a>
+</li>
+<li>
+<a href="#register-jruby">Registering the UDF</a>
+</li>
+<li>
+<a href="#jruby-example">Example Scripts</a>
+</li>
+<li>
+<a href="#jruby-advanced">Advanced Topics</a>
+</li>
+</ul>
+</li>
+<li>
+<a href="#groovy-udfs">Writing Groovy UDFs</a>
+<ul class="minitoc">
+<li>
+<a href="#register-groovy">Registering the UDF</a>
+</li>
+<li>
+<a href="#groovy-schema-return-types">Return Types and Schemas</a>
+</li>
+<li>
+<a href="#groovy-type-conversions">Type Conversions</a>
+</li>
+<li>
+<a href="#groovy-advanced">Advanced Topics</a>
+</li>
+</ul>
+</li>
+<li>
+<a href="#piggybank">Piggy Bank</a>
+<ul class="minitoc">
+<li>
+<a href="#piggbank-access">Accessing Functions</a>
+</li>
+<li>
+<a href="#piggybank-contribute">Contributing Functions</a>
+</li>
+</ul>
+</li>
+</ul>
+</div>
+</div>
+
+
+<a name="udfs"></a>
+<h2 class="h3">Introduction</h2>
+<div class="section">
+<p>
+Pig provides extensive support for user defined functions (UDFs) as a way to specify custom processing. Pig UDFs can currently be implemented in three languages: Java, Python, JavaScript, Ruby and Groovy. 
+</p>
+<p>
+The most extensive support is provided for Java functions. You can customize all parts of the processing including data load/store, column transformation, and aggregation. Java functions are also more efficient because they are implemented in the same language as Pig and because additional interfaces are supported such as the <a href="#algebraic-interface">Algebraic Interface</a> and the <a href="#accumulator-interface">Accumulator Interface</a>.
+</p>
+<p>
+Limited support is provided for Python, JavaScript, Ruby and Groovy functions. These functions are new, still evolving, additions to the system. Currently only the basic interface is supported; load/store functions are not supported. Furthermore, JavaScript, Ruby and Groovy are provided as experimental features because they did not go through the same amount of testing as Java or Python. At runtime note that Pig will automatically detect the usage of a scripting UDF in the Pig script and will automatically ship the corresponding scripting jar, either Jython, Rhino, JRuby or Groovy-all, to the backend.</p>
+<p></p>
+<p>
+Pig also provides support for Piggy Bank, a repository for JAVA UDFs. Through Piggy Bank you can access Java UDFs written by other users and contribute Java UDFs that you have written.
+</p>
+</div>
+
+
+<!-- ================================================================== -->
+<!-- WRITING UDFS -->
+
+
+<a name="udf-java"></a>
+<h2 class="h3">Writing Java UDFs</h2>
+<div class="section">
+<a name="eval-functions"></a>
+<h3 class="h4">Eval Functions</h3>
+<a name="eval-functions-use"></a>
+<h4>How to Use a Simple Eval Function</h4>
+<p>Eval is the most common type of function. It can be used in <span class="codefrag">FOREACH</span> statements as shown in this script: </p>
+<pre class="code">
+-- myscript.pig
+REGISTER myudfs.jar;
+A = LOAD 'student_data' AS (name: chararray, age: int, gpa: float);
+B = FOREACH A GENERATE myudfs.UPPER(name);
+DUMP B;
+</pre>
+<p>The command below can be used to run the script. Note that all examples in this document run in local mode for simplicity 
+but the examples can also run in Hadoop mode. For more information on how to run Pig, please see the PigTutorial. </p>
+<pre class="code">
+java -cp pig.jar org.apache.pig.Main -x local myscript.pig
+</pre>
+<p>The first line of the script provides the location of the <span class="codefrag">jar&nbsp;file</span> that contains the UDF. 
+(Note that there are no quotes around the jar file. Having quotes would result in a syntax error.) 
+To locate the jar file, Pig first checks the <span class="codefrag">classpath</span>. If the jar file can't be found in the classpath, 
+Pig assumes that the location is either an absolute path or a path relative to the location from which Pig was invoked. 
+If the jar file can't be found, an error will be printed: <span class="codefrag">java.io.IOException:&nbsp;Can't&nbsp;read&nbsp;jar&nbsp;file:&nbsp;myudfs.jar</span>. </p>
+<p>Multiple <span class="codefrag">register</span> commands can be used in the same script. If the same fully-qualified function is present in multiple jars, 
+the first occurrence will be used consistently with Java semantics. </p>
+<p>The name of the UDF has to be fully qualified with the package name or an error will be reported: 
+<span class="codefrag">java.io.IOException:&nbsp;Cannot&nbsp;instantiate:UPPER</span>. Also, the function name is case sensitive (UPPER and upper are not the same). 
+A UDF can take one or more parameters. The exact signature of the function should clear from its documentation. </p>
+<p>The function provided in this example takes an ASCII string and produces its uppercase version. If you are familiar with column transformation functions 
+in SQL, you will recognize that UPPER fits this concept. However, as we will see later in the document, eval functions in Pig go beyond column 
+transformation functions and include aggregate and filter functions. </p>
+<p>If you are just a user of UDFs, this is most of what you need to know about UDFs to use them in your code.  </p>
+<a name="eval-functions-write"></a>
+<h4> How to Write a Simple Eval Function</h4>
+<p>Let's now look at the implementation of the <span class="codefrag">UPPER</span> UDF. </p>
+<pre class="code">
+1  package myudfs;
+2  import java.io.IOException;
+3  import org.apache.pig.EvalFunc;
+4  import org.apache.pig.data.Tuple;
+5
+6  public class UPPER extends EvalFunc&lt;String&gt;
+7  {
+8    public String exec(Tuple input) throws IOException {
+9        if (input == null || input.size() == 0)
+10            return null;
+11        try{
+12            String str = (String)input.get(0);
+13           return str.toUpperCase();
+14        }catch(Exception e){
+15            throw new IOException("Caught exception processing input row ", e);
+16        }
+17    }
+18  }
+</pre>
+<p>Line 1 indicates that the function is part of the <span class="codefrag">myudfs</span> package. The UDF class extends the <span class="codefrag">EvalFunc</span> class which is the base class for all eval functions. It is parameterized with the return type of the UDF which is a Java <span class="codefrag">String</span> in this case. We will look into the <span class="codefrag">EvalFunc</span> class in more detail later, but for now all we need to do is to implement the <span class="codefrag">exec</span> function. This function is invoked on every input tuple. The input into the function is a tuple with input parameters in the order they are passed to the function in the Pig script. In our example, it will contain a single string field corresponding to the student name. </p>
+<p>The first thing to decide is what to do with invalid data. This depends on the format of the data. If the data is of type <span class="codefrag">bytearray</span> it means that it has not yet been converted to its proper type. In this case, if the format of the data does not match the expected type, a NULL value should be returned. If, on the other hand, the input data is of another type, this means that the conversion has already happened and the data should be in the correct format. This is the case with our example and that's why it throws an error (line 15.) </p>
+<p>Also, note that lines 9-10 check if the input data is null or empty and if so returns null. </p>
+<p>The actual function implementation is on lines 12-13 and is self-explanatory. </p>
+<p>Now that we have the function implemented, it needs to be compiled and included in a jar. You will need to build <span class="codefrag">pig.jar</span> to compile your UDF. You can use the following set of commands to checkout the code from SVN repository and create pig.jar: </p>
+<pre class="code">
+svn co http://svn.apache.org/repos/asf/pig/trunk
+cd trunk
+ant
+</pre>
+<p>You should see <span class="codefrag">pig.jar</span> in your current working directory. The set of commands below first compiles the function and then creates a jar file that contains it. </p>
+<pre class="code">
+cd myudfs
+javac -cp pig.jar UPPER.java
+cd ..
+jar -cf myudfs.jar myudfs
+</pre>
+<p>You should now see <span class="codefrag">myudfs.jar</span> in your current working directory. You can use this jar with the script described in the previous section. </p>
+<a name="aggregate-functions"></a>
+<h4>Aggregate Functions</h4>
+<p>Aggregate functions are another common type of eval function. Aggregate functions are usually applied to grouped data, as shown in this script: </p>
+<pre class="code">
+-- myscript2.pig
+A = LOAD 'student_data' AS (name: chararray, age: int, gpa: float);
+B = GROUP A BY name;
+C = FOREACH B GENERATE group, COUNT(A);
+DUMP C;
+</pre>
+<p>The script above uses the <span class="codefrag">COUNT</span> function to count the number of students with the same name. There are a couple of things to note about this script. First, even though we are using a function, there is no <span class="codefrag">register</span> command. Second, the function is not qualified with the package name. The reason for both is that <span class="codefrag">COUNT</span> is a <span class="codefrag">builtin</span> function meaning that it comes with the Pig distribution. These are the only two differences between builtins and UDFs. Builtins are discussed in more detail later in this document.  </p>
+<a name="algebraic-interface"></a>
+<h4>Algebraic Interface</h4>
+<p>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. We call these functions <span class="codefrag">algebraic</span>. <span class="codefrag">COUNT</span> is an example of an algebraic function because we can count the number of elements in a subset of the data and then sum the counts to produce a final output. In the Hadoop world, this means that the partial computations can be done by the map and combiner, and the final result can be computed by the reducer. </p>
+<p>It is very important for performance to make sure that aggregate functions that are algebraic are implemented as such. Let's look at the implementation of the COUNT function to see what this means. (Error handling and some other code is omitted to save space. The full code can be accessed <a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/builtin/COUNT.java?view=markup"> here</a>.)</p>
+<pre class="code">
+public class COUNT extends EvalFunc&lt;Long&gt; implements Algebraic{
+    public Long exec(Tuple input) throws IOException {return count(input);}
+    public String getInitial() {return Initial.class.getName();}
+    public String getIntermed() {return Intermed.class.getName();}
+    public String getFinal() {return Final.class.getName();}
+    static public class Initial extends EvalFunc&lt;Tuple&gt; {
+        public Tuple exec(Tuple input) throws IOException {return TupleFactory.getInstance().newTuple(count(input));}
+    }
+    static public class Intermed extends EvalFunc&lt;Tuple&gt; {
+        public Tuple exec(Tuple input) throws IOException {return TupleFactory.getInstance().newTuple(sum(input));}
+    }
+    static public class Final extends EvalFunc&lt;Long&gt; {
+        public Tuple exec(Tuple input) throws IOException {return sum(input);}
+    }
+    static protected Long count(Tuple input) throws ExecException {
+        Object values = input.get(0);
+        if (values instanceof DataBag) return ((DataBag)values).size();
+        else if (values instanceof Map) return new Long(((Map)values).size());
+    }
+    static protected Long sum(Tuple input) throws ExecException, NumberFormatException {
+        DataBag values = (DataBag)input.get(0);
+        long sum = 0;
+        for (Iterator (Tuple) it = values.iterator(); it.hasNext();) {
+            Tuple t = it.next();
+            sum += (Long)t.get(0);
+        }
+        return sum;
+    }
+}
+</pre>
+<p>
+<span class="codefrag">COUNT</span> implements <span class="codefrag">Algebraic</span> interface which looks like this: </p>
+<pre class="code">
+public interface Algebraic{
+    public String getInitial();
+    public String getIntermed();
+    public String getFinal();
+}
+</pre>
+<p>For a function to be algebraic, it needs to implement <span class="codefrag">Algebraic</span> interface that consist of definition of three classes derived from <span class="codefrag">EvalFunc</span>. The contract is that the  <span class="codefrag">exec</span> function of the <span class="codefrag">Initial</span> class is called once and is passed the original input tuple. Its output is a tuple that contains partial results. The <span class="codefrag">exec</span> function of the <span class="codefrag">Intermed</span> class can be called zero or more times and takes as its input a tuple that contains partial results produced by the <span class="codefrag">Initial</span> class or by prior invocations of the <span class="codefrag">Intermed</span> class and produces a tuple with another partial result. Finally, the <span class="codefrag">exec</span> function of the <span class="codefrag">Final</span> class is called and produces the final result as a scalar type. </p>
+<p>Here's the way to think about this in the Hadoop world. The <span class="codefrag">exec</span> function of the <span class="codefrag">Initial</span> class is invoked once for each input tuple by the <span class="codefrag">map</span> process and produces partial results. The <span class="codefrag">exec</span> function of the <span class="codefrag">Intermed</span> class is invoked once by each <span class="codefrag">combiner</span> invocation (which can happen zero or more times) and also produces partial results. The <span class="codefrag">exec</span> function of the <span class="codefrag">Final</span> class is invoked once by the reducer and produces the final result. </p>
+<p>Take a look at the <span class="codefrag">COUNT</span> implementation to see how this is done. Note that the <span class="codefrag">exec</span> function of the <span class="codefrag">Initial</span> and <span class="codefrag">Intermed</span> classes is parameterized with <span class="codefrag">Tuple</span> and the <span class="codefrag">exec</span> of the <span class="codefrag">Final</span> class is parameterized with the real type of the function, which in the case of the <span class="codefrag">COUNT</span> is <span class="codefrag">Long</span>. Also, note that the fully-qualified name of the class needs to be returned from <span class="codefrag">getInitial</span>, <span class="codefrag">getIntermed</span>, and <span class="codefrag">getFinal</span> methods. </p>
+<a name="accumulator-interface"></a>
+<h4>Accumulator Interface</h4>
+<p>In Pig, problems with memory usage can occur when data, which results from a group or cogroup operation, needs to be placed in a bag  and passed in its entirety to a UDF.</p>
+<p>This problem is partially addressed by Algebraic UDFs that use the combiner and can deal with data being passed to them incrementally during different processing phases (map, combiner, and reduce). However, there are a number of UDFs that are not Algebraic, don't use the combiner, but still don&rsquo;t need to be given all data at once. </p>
+<p>The new Accumulator interface is designed to decrease memory usage by targeting such UDFs. For the functions that implement this interface, Pig guarantees that the data for the same key is passed continuously but in small increments. To work with incremental data, here is the interface a UDF needs to implement:</p>
+<pre class="code">
+public interface Accumulator &lt;T&gt; {
+   /**
+    * Process tuples. Each DataBag may contain 0 to many tuples for current key
+    */
+    public void accumulate(Tuple b) throws IOException;
+    /**
+     * Called when all tuples from current key have been passed to the accumulator.
+     * @return the value for the UDF for this key.
+     */
+    public T getValue();
+    /**
+     * Called after getValue() to prepare processing for next key. 
+     */
+    public void cleanup();
+}
+</pre>
+<p>There are several things to note here:</p>
+<ol>
+	
+<li>Each UDF must extend the EvalFunc class and implement all necessary functions there.</li>
+	
+<li>If a function is algebraic but can be used in a FOREACH statement with accumulator functions, it needs to implement the Accumulator interface in addition to the Algebraic interface.</li>
+	
+<li>The interface is parameterized with the return type of the function.</li>
+	
+<li>The accumulate function is guaranteed to be called one or more times, passing one or more tuples in a bag, to the UDF. (Note that the tuple that is passed to the accumulator has the same content as the one passed to exec &ndash; all the parameters passed to the UDF &ndash; one of which should be a bag.)</li>
+	
+<li>The getValue function is called after all the tuples for a particular key have been processed to retrieve the final value.</li>
+	
+<li>The cleanup function is called after getValue but before the next value is processed.</li>
+
+</ol>
+<p>Here us a code snippet of the integer version of the MAX function that implements the interface:</p>
+<pre class="code">
+public class IntMax extends EvalFunc&lt;Integer&gt; implements Algebraic, Accumulator&lt;Integer&gt; {
+    &hellip;&hellip;.
+    /* Accumulator interface */
+    
+    private Integer intermediateMax = null;
+    
+    @Override
+    public void accumulate(Tuple b) throws IOException {
+        try {
+            Integer curMax = max(b);
+            if (curMax == null) {
+                return;
+            }
+            /* if bag is not null, initialize intermediateMax to negative infinity */
+            if (intermediateMax == null) {
+                intermediateMax = Integer.MIN_VALUE;
+            }
+            intermediateMax = java.lang.Math.max(intermediateMax, curMax);
+        } catch (ExecException ee) {
+            throw ee;
+        } catch (Exception e) {
+            int errCode = 2106;
+            String msg = "Error while computing max in " + this.getClass().getSimpleName();
+            throw new ExecException(msg, errCode, PigException.BUG, e);           
+        }
+    }
+
+    @Override
+    public void cleanup() {
+        intermediateMax = null;
+    }
+
+    @Override
+    public Integer getValue() {
+        return intermediateMax;
+    }
+}
+</pre>
+<a name="filter-functions"></a>
+<h4> Filter Functions</h4>
+<p>Filter functions are eval functions that return a <span class="codefrag">boolean</span> value. Filter functions can be used anywhere a Boolean expression is appropriate, including the <span class="codefrag">FILTER</span> operator or <span class="codefrag">bincond</span> expression. </p>
+<p>The example below uses the <span class="codefrag">IsEmpy</span> builtin filter function to implement joins. </p>
+<pre class="code">
+-- inner join
+A = LOAD 'student_data' AS (name: chararray, age: int, gpa: float);
+B = LOAD 'voter_data' AS (name: chararray, age: int, registration: chararay, contributions: float);
+C = COGROUP A BY name, B BY name;
+D = FILTER C BY not IsEmpty(A);
+E = FILTER D BY not IsEmpty(B);
+F = FOREACH E GENERATE flatten(A), flatten(B);
+DUMP F;
+</pre>
+<p>Note that, even if filtering is omitted, the same results will be produced because the <span class="codefrag">foreach</span> results is a cross product and cross products get rid of empty bags. However, doing up-front filtering is more efficient since it reduces the input of the cross product. </p>
+<pre class="code">
+-- full outer join
+A = LOAD 'student_data' AS (name: chararray, age: int, gpa: float);
+B = LOAD 'voter_data' AS (name: chararray, age: int, registration: chararay, contributions: float);
+C = COGROUP A BY name, B BY name;
+D = FOREACH C GENERATE group, flatten((IsEmpty(A) ? null : A)), flatten((IsEmpty(B) ? null : B));
+dump D;
+</pre>
+<p>The implementation of the <span class="codefrag">IsEmpty</span> function looks like this: </p>
+<pre class="code">
+import java.io.IOException;
+import java.util.Map;
+
+import org.apache.pig.FilterFunc;
+import org.apache.pig.PigException;
+import org.apache.pig.backend.executionengine.ExecException;
+import org.apache.pig.data.DataBag;
+import org.apache.pig.data.Tuple;
+import org.apache.pig.data.DataType;
+
+/**
+ * Determine whether a bag or map is empty.
+ */
+public class IsEmpty extends FilterFunc {
+
+    @Override
+    public Boolean exec(Tuple input) throws IOException {
+        try {
+            Object values = input.get(0);
+            if (values instanceof DataBag)
+                return ((DataBag)values).size() == 0;
+            else if (values instanceof Map)
+                return ((Map)values).size() == 0;
+            else {
+                int errCode = 2102;
+                String msg = "Cannot test a " +
+                DataType.findTypeName(values) + " for emptiness.";
+                throw new ExecException(msg, errCode, PigException.BUG);
+            }
+        } catch (ExecException ee) {
+            throw ee;
+        }
+    }
+} 
+</pre>
+<a name="udf_simulation"></a>
+<h4>Implement UDF by Simulation</h4>
+<p>When implementing more advanced types of EvalFuncs, the simpler implementations can be automatically provided by Pig.  Thus if your UDF implements <a href="#Algebraic-Interface">Algebraic</a> then you will get the Accumulator interface and basic the basic EvalFunc exec method for free.  Similarly, if your UDF implements <a href="#Accumulator-Interface">Accumulator Interface</a> you will get the basic EvalFunc exec method for free.  You will not get the Algebraic implemenation.  Note that these free implementations are based on simulation, which might not be the most efficient.  If you wish to ensure the efficiency of your Accumulator of EvalFunc exec method, you may still implement them yourself and your implementations will be used.</p>
+<a name="pig-types"></a>
+<h4> Pig Types and Native Java Types</h4>
+<p>The main thing to know about Pig's type system is that Pig uses native Java types for almost all of its types, as shown in this table. </p>
+<table class="ForrestTable" cellspacing="1" cellpadding="4">
+
+<tr>
+
+<th colspan="1" rowspan="1">
+Pig Type
+</th>
+<th colspan="1" rowspan="1">
+Java Class
+</th>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> bytearray </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> DataByteArray </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> chararray </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> String </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> int </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Integer </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> long </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Long </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> float </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Float </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> double </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Double </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> tuple </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Tuple </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> bag </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> DataBag </p>
+
+</td>
+
+</tr>
+
+<tr>
+
+<td colspan="1" rowspan="1">
+
+<p> map </p>
+
+</td>
+<td colspan="1" rowspan="1">
+
+<p> Map&lt;Object, Object&gt; </p>
+
+</td>
+
+</tr>
+
+</table>
+<p>All Pig-specific classes are available <a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/data/"> here</a>. </p>
+<p>
+<span class="codefrag">Tuple</span> and <span class="codefrag">DataBag</span> are different in that they are not concrete classes but rather interfaces. This enables users to extend Pig with their own versions of tuples and bags. As a result, UDFs cannot directly instantiate bags or tuples; they need to go through factory classes: <span class="codefrag">TupleFactory</span> and <span class="codefrag">BagFactory</span>. </p>
+<p>The builtin <span class="codefrag">TOKENIZE</span> function shows how bags and tuples are created. A function takes a text string as input and returns a bag of words from the text. (Note that currently Pig bags always contain tuples.) </p>
+<pre class="code">
+package org.apache.pig.builtin;
+
+import java.io.IOException;
+import java.util.StringTokenizer;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.data.BagFactory;
+import org.apache.pig.data.DataBag;
+import org.apache.pig.data.Tuple;
+import org.apache.pig.data.TupleFactory;
+
+public class TOKENIZE extends EvalFunc&lt;DataBag&gt; {
+    TupleFactory mTupleFactory = TupleFactory.getInstance();
+    BagFactory mBagFactory = BagFactory.getInstance();
+
+    public DataBag exec(Tuple input) throws IOException 
+        try {
+            DataBag output = mBagFactory.newDefaultBag();
+            Object o = input.get(0);
+            if ((o instanceof String)) {
+                throw new IOException("Expected input to be chararray, but  got " + o.getClass().getName());
+            }
+            StringTokenizer tok = new StringTokenizer((String)o, " \",()*", false);
+            while (tok.hasMoreTokens()) output.add(mTupleFactory.newTuple(tok.nextToken()));
+            return output;
+        } catch (ExecException ee) {
+            // error handling goes here
+        }
+    }
+}
+</pre>
+<a name="schemas"></a>
+<h4>Schemas and Java UDFs</h4>
+<p>Pig uses type information for validation and performance. It is important for UDFs to participate in type propagation. Our UDFs generally make no effort to communicate their output schema to Pig. This is because Pig can usually figure out this information by using Java's <a href="http://java.sun.com/developer/technicalArticles/ALT/Reflection/"> Reflection</a>. If your UDF returns a scalar or a map, no work is required. However, if your UDF returns a tuple or a bag (of tuples), it needs to help Pig figure out the structure of the tuple. </p>
+<p>If a UDF returns a tuple or a bag and schema information is not provided, Pig assumes that the tuple contains a single field of type bytearray. If this is not the case, then not specifying the schema can cause failures. We look at this next. </p>
+<p>Let's assume that we have UDF <span class="codefrag">Swap</span> that, given a tuple with two fields, swaps their order. Let's assume that the UDF does not specify a schema and look at the scripts below: </p>
+<pre class="code">
+register myudfs.jar;
+A = load 'student_data' as (name: chararray, age: int, gpa: float);
+B = foreach A generate flatten(myudfs.Swap(name, age)), gpa;
+C = foreach B generate $2;
+D = limit B 20;
+dump D;
+</pre>
+<p>This script will result in the following error cause by line 4 ( <span class="codefrag">C = foreach B generate $2;</span>). </p>
+<pre class="code">
+java.io.IOException: Out of bound access. Trying to access non-existent column: 2. Schema {bytearray,gpa: float} has 2 column(s).
+</pre>
+<p>This is because Pig is only aware of two columns in B while line 4 is requesting the third column of the tuple. (Column indexing in Pig starts with 0.) </p>
+<p>The function, including the schema, looks like this: </p>
+<pre class="code">
+package myudfs;
+import java.io.IOException;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.data.Tuple;
+import org.apache.pig.data.TupleFactory;
+import org.apache.pig.impl.logicalLayer.schema.Schema;
+import org.apache.pig.data.DataType;
+
+public class Swap extends EvalFunc&lt;Tuple&gt; {
+    public Tuple exec(Tuple input) throws IOException {
+        if (input == null || input.size()   2
+            return null;
+        try{
+            Tuple output = TupleFactory.getInstance().newTuple(2);
+            output.set(0, input.get(1));
+            output.set(1, input.get(0));
+            return output;
+        } catch(Exception e){
+            System.err.println("Failed to process input; error - " + e.getMessage());
+            return null;
+        }
+    }
+    public Schema outputSchema(Schema input) {
+        try{
+            Schema tupleSchema = new Schema();
+            tupleSchema.add(input.getField(1));
+            tupleSchema.add(input.getField(0));
+            return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input),tupleSchema, DataType.TUPLE));
+        }catch (Exception e){
+                return null;
+        }
+    }
+}
+</pre>
+<p>The function creates a schema with a single field (of type <span class="codefrag">FieldSchema) of type tuple</span>. The name of the field is constructed using the <span class="codefrag">getSchemaName</span> function of the <span class="codefrag">EvalFunc</span> class. The name consists of the name of the UDF function, the first parameter passed to it, and a sequence number to guarantee uniqueness. In the previous script, if you replace <span class="codefrag">dump&nbsp;D;</span>  with <span class="codefrag">describe&nbsp;B;</span> , you will see the following output: 
+</p>
+<pre class="code">
+B: {myudfs.swap_age_3::age: int,myudfs.swap_age_3::name: chararray,gpa: float}
+</pre>
+<p>The second parameter to the <span class="codefrag">FieldSchema</span> constructor is the schema representing this field, which in this case is a tuple with two fields. The third parameter represents the type of the schema, which in this case is a <span class="codefrag">TUPLE</span>. All supported schema types are defined in the <span class="codefrag">org.apache.pig.data.DataType</span> class. </p>
+<pre class="code">
+public class DataType {
+    public static final byte UNKNOWN   =   0;
+    public static final byte NULL      =   1;
+    public static final byte BOOLEAN   =   5; // internal use only
+    public static final byte BYTE      =   6; // internal use only
+    public static final byte INTEGER   =  10;
+    public static final byte LONG      =  15;
+    public static final byte FLOAT     =  20;
+    public static final byte DOUBLE    =  25;
+    public static final byte BYTEARRAY =  50;
+    public static final byte CHARARRAY =  55;
+    public static final byte MAP       = 100;
+    public static final byte TUPLE     = 110;
+    public static final byte BAG       = 120;
+    public static final byte ERROR     =  -1;
+    // more code here
+}
+</pre>
+<p>You need to import the <span class="codefrag">org.apache.pig.data.DataType</span> class into your code to define schemas. You also need to import the schema class <span class="codefrag">org.apache.pig.impl.logicalLayer.schema.Schema</span>. </p>
+<p>The example above shows how to create an output schema for a tuple. Doing this for a bag is very similar. Let's extend the <span class="codefrag">TOKENIZE</span> function to do that.</p>
+<p>As you can see in the example below, this is very similar to the output schema definition in the <span class="codefrag">Swap</span> function. One difference is that instead of reusing input schema, we create a brand new field schema to represent the tokens stored in the bag. The other difference is that the type of the schema created is BAG (not TUPLE). </p>
+<pre class="code">
+package org.apache.pig.builtin;
+
+import java.io.IOException;
+import java.util.StringTokenizer;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.data.BagFactory;
+import org.apache.pig.data.DataBag;
+import org.apache.pig.data.Tuple;
+import org.apache.pig.data.TupleFactory;
+import org.apache.pig.impl.logicalLayer.schema.Schema;
+import org.apache.pig.data.DataType;
+
+public class TOKENIZE extends EvalFunc&lt;DataBag&gt; {
+    TupleFactory mTupleFactory = TupleFactory.getInstance();
+    BagFactory mBagFactory = BagFactory.getInstance();
+    public DataBag exec(Tuple input) throws IOException {
+        try {
+            DataBag output = mBagFactory.newDefaultBag();
+            Object o = input.get(0);
+            if ((o instanceof String)) {
+                throw new IOException("Expected input to be chararray, but  got " + o.getClass().getName());
+            }
+            StringTokenizer tok = new StringTokenizer((String)o, " \",()*", false);
+            while (tok.hasMoreTokens()) output.add(mTupleFactory.newTuple(tok.nextToken()));
+            return output;
+        } catch (ExecException ee) {
+            // error handling goes here
+        }
+    }
+    public Schema outputSchema(Schema input) {
+         try{
+             Schema bagSchema = new Schema();
+             bagSchema.add(new Schema.FieldSchema("token", DataType.CHARARRAY));
+
+             return new Schema(new Schema.FieldSchema(getSchemaName(this.getClass().getName().toLowerCase(), input),
+                                                    bagSchema, DataType.BAG));
+         }catch (Exception e){
+            return null;
+         }
+    }
+}
+</pre>
+<p></p>
+<p>One more note about schemas and UDFs. Users have requested the ability to examine the input schema of the data before processing the data via a UDF. For example, they would like to know how to convert an input tuple to a map such that the keys in the map are the names of the input columns. Currently there is no way to do this. This is a feature we would like to support in the future.</p>
+<a name="error-handling"></a>
+<h4> Error Handling</h4>
+<p>There are several types of errors that can occur in a UDF: </p>
+<ol>
+
+<li>
+<p>An error that affects a particular row but is not likely to impact other rows. An example of such an error would be a malformed input value or divide by zero problem. A reasonable handling of this situation would be to emit a warning and return a null value. <span class="codefrag">ABS</span> function in the next section demonstrates this approach. The current approach is to write the warning to <span class="codefrag">stderr</span>. Eventually we would like to pass a logger to the UDFs. Note that returning a NULL value only makes sense if the malformed value is of type <span class="codefrag">bytearray</span>. Otherwise the proper type has been already created and should have an appropriate value. If this is not the case, it is an internal error and should cause the system to fail. Both cases can be seen in the implementation of the <span class="codefrag">ABS</span> function in the next section. </p>
+
+</li>
+
+<li>
+<p>An error that affects the entire processing but can succeed on retry. An example of such a failure is the inability to open a lookup file because the file could not be found. This could be a temporary environmental issue that can go away on retry. A UDF can signal this to Pig by throwing an <span class="codefrag">IOException</span> as with the case of the <span class="codefrag">ABS</span> function below. </p>
+
+</li>
+
+<li>
+<p>An error that affects the entire processing and is not likely to succeed on retry. An example of such a failure is the inability to open a lookup file because of file permission problems. Pig currently does not have a way to handle this case. Hadoop does not have a way to handle this case either. It will be handled the same way as 2 above. </p>
+
+</li>
+
+</ol>
+<a name="function-overloading"></a>
+<h4>Function Overloading</h4>
+<p>Before the type system was available in Pig, all values for the purpose of arithmetic calculations were assumed to be doubles as the safest choice. However, this is not very efficient if the data is actually of type integer or long. (We saw about a 2x slowdown of a query when using double where integer could be used.) Now that Pig supports types we can take advantage of the type information and choose the function that is most efficient for the provided operands. </p>
+<p>UDF writers are encouraged to provide type-specific versions of a function if this can result in better performance. On the other hand, we don't want the users of the functions to worry about different functions - the right thing should just happen. Pig allows for this via a function table mechanism as shown in the next example. </p>
+<p>This example shows the implementation of the <span class="codefrag">ABS</span> function that returns the absolute value of a numeric value passed to it as input. </p>
+<pre class="code">
+import java.io.IOException;
+import java.util.List;
+import java.util.ArrayList;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.FuncSpec;
+import org.apache.pig.data.Tuple;
+import org.apache.pig.impl.logicalLayer.FrontendException;
+import org.apache.pig.impl.logicalLayer.schema.Schema;
+import org.apache.pig.data.DataType;
+
+public class ABS extends EvalFunc&lt;Double&gt; {
+    public Double exec(Tuple input) throws IOException {
+        if (input == null || input.size() == 0)
+            return null;
+        Double d;
+        try{
+            d = DataType.toDouble(input.get(0));
+        } catch (NumberFormatException nfe){
+            System.err.println("Failed to process input; error - " + nfe.getMessage());
+            return null;
+        } catch (Exception e){
+            throw IOException("Caught exception processing input row ", e);
+        }
+        return Math.abs(d);
+    }
+    public List (FuncSpec) getArgToFuncMapping() throws FrontendException {
+        List (FuncSpec) funcList = new ArrayList (FuncSpec) ();
+        funcList.add(new FuncSpec(this.getClass().getName(), new Schema(new Schema.FieldSchema(null, DataType.BYTEARRAY))));
+        funcList.add(new FuncSpec(DoubleAbs.class.getName(),  new Schema(new Schema.FieldSchema(null, DataType.DOUBLE))));
+        funcList.add(new FuncSpec(FloatAbs.class.getName(),   new Schema(new Schema.FieldSchema(null, DataType.FLOAT))));
+        funcList.add(new FuncSpec(IntAbs.class.getName(),  new Schema(new Schema.FieldSchema(null, DataType.INTEGER))));
+        funcList.add(new FuncSpec(LongAbs.class.getName(),  new Schema(new Schema.FieldSchema(null, DataType.LONG))));
+        return funcList;
+    }
+}
+</pre>
+<p>The main thing to notice in this example is the <span class="codefrag">getArgToFuncMapping()</span> method. This method returns a list that contains a mapping from the input schema to the class that should be used to handle it. In this example the main class handles the <span class="codefrag">bytearray</span> input and outsources the rest of the work to other classes implemented in separate files in the same package. The example of one such class is below. This class handles integer input values. </p>
+<pre class="code">
+import java.io.IOException;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.data.Tuple;
+
+public class IntAbs extends EvalFunc&lt;Integer&gt; {
+    public Integer exec(Tuple input) throws IOException {
+        if (input == null || input.size() == 0)
+            return null;
+        Integer d;
+        try{
+            d = (Integer)input.get(0);
+        } catch (Exception e){
+            throw newIOException("Caught exception processing input row ", e);
+        }
+        return Math.abs(d);
+    }
+}
+</pre>
+<p>A note on error handling. The <span class="codefrag">ABS</span> class covers the case of the <span class="codefrag">bytearray</span> which means the data has not been converted yet to its actual type. This is why a null value is returned when <span class="codefrag">NumberFormatException</span> is encountered. However, the <span class="codefrag">IntAbs</span> function is only called if the data is already of type <span class="codefrag">Integer</span> which means it has already been converted to the real type and bad format has been dealt with. This is why an exception is thrown if the input can't be cast to <span class="codefrag">Integer</span>. </p>
+<p>The example above covers a reasonably simple case where the UDF only takes one parameter and there is a separate function for each parameter type. However, this will not always be the case. If Pig can't find an <span class="codefrag">exact&nbsp;match</span> it tries to do a <span class="codefrag">best&nbsp;match</span>. The rule for the best match is to find the most efficient function that can be used safely. This means that Pig must find the function that, for each input parameter, provides the smallest type that is equal to or greater than the input type. The type progression rules are: <span class="codefrag">int&gt;long&gt;float&gt;double</span>. </p>
+<p>For instance, let's consider function <span class="codefrag">MAX</span> which is part of the <span class="codefrag">piggybank</span> described later in this document. Given two values, the function returns the larger value. The function table for <span class="codefrag">MAX</span> looks like this: </p>
+<pre class="code">
+public List (FuncSpec) getArgToFuncMapping() throws FrontendException {
+    List (FuncSpec) funcList = new ArrayList (FuncSpec) ();
+    Util.addToFunctionList(funcList, IntMax.class.getName(), DataType.INTEGER);
+    Util.addToFunctionList(funcList, DoubleMax.class.getName(), DataType.DOUBLE);
+    Util.addToFunctionList(funcList, FloatMax.class.getName(), DataType.FLOAT);
+    Util.addToFunctionList(funcList, LongMax.class.getName(), DataType.LONG);
+
+    return funcList;
+}
+</pre>
+<p>The <span class="codefrag">Util.addToFunctionList</span> function is a helper function that adds an entry to the list as the first argument, with the key of the class name passed as the second argument, and the schema containing two fields of the same type as the third argument.  </p>
+<p>Let's now see how this function can be used in a Pig script: </p>
+<pre class="code">
+REGISTER piggybank.jar
+A = LOAD 'student_data' AS (name: chararray, gpa1: float, gpa2: double);
+B = FOREACH A GENERATE name, org.apache.pig.piggybank.evaluation.math.MAX(gpa1, gpa2);
+DUMP B;
+</pre>
+<p>In this example, the function gets one parameter of type <span class="codefrag">float</span> and another of type <span class="codefrag">double</span>. The best fit will be the function that takes two double values. Pig makes this choice on the user's behalf by inserting implicit casts for the parameters. Running the script above is equivalent to running the script below: </p>
+<pre class="code">
+A = LOAD 'student_data' AS (name: chararray, gpa1: float, gpa2: double);
+B = FOREACH A GENERATE name, org.apache.pig.piggybank.evaluation.math.MAX((double)gpa1, gpa2);
+DUMP B;
+</pre>
+<p>A special case of the <span class="codefrag">best&nbsp;fit</span> approach is handling data without a schema specified. The type for this data is interpreted as <span class="codefrag">bytearray</span>. Since the type of the data is not known, there is no way to choose a best fit version. The only time a cast is performed is when the function table contains only a single entry. This works well to maintain backward compatibility.  </p>
+<p>Let's revisit the <span class="codefrag">UPPER</span> function from our first example. As it is written now, it would only work if the data passed to it is of type <span class="codefrag">chararray</span>. To make it work with data whose type is not explicitly set, a function table with a single entry needs to be added: </p>
+<pre class="code">
+package myudfs;
+import java.io.IOException;
+import org.apache.pig.EvalFunc;
+import org.apache.pig.data.Tuple;
+
+public class UPPER extends EvalFunc&lt;String&gt;
+{
+    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){
+            System.err.println("WARN: UPPER: failed to process input; error - " + e.getMessage());
+            return null;
+        }
+    }
+    public List (FuncSpec) getArgToFuncMapping() throws FrontendException {
+        List (FuncSpec) funcList = new ArrayList (FuncSpec) ();
+        funcList.add(new FuncSpec(this.getClass().getName(), new Schema(new Schema.FieldSchema(null, DataType.CHARARRAY))));
+        return funcList;
+    }
+}
+</pre>
+<p>Now the following script will ran: </p>
+<pre class="code">
+-- this is myscript.pig
+REGISTER myudfs.jar;
+A = LOAD 'student_data' AS (name, age, gpa);
+B = FOREACH A GENERATE myudfs.UPPER(name);
+DUMP B;
+</pre>
+<a name="reporting-progress"></a>
+<h4>Reporting Progress</h4>
+<p>A challenge of running a large shared system is to make sure system resources are used efficiently. One aspect of this challenge is detecting runaway processes that are no longer making progress. Pig uses a heartbeat mechanism for this purpose. If any of the tasks stops sending a heartbeat, the system assumes that it is dead and kills it.   </p>
+<p>Most of the time, single-tuple processing within a UDF is very short and does not require a UDF to heartbeat. The same is true for aggregate functions that operate on large bags because bag iteration code takes care of it. However, if you have a function that performs a complex computation that can take an order of minutes to execute, you should add a progress indicator to your code. This is very easy to accomplish. The <span class="codefrag">EvalFunc</span> function provides a <span class="codefrag">progress</span> function that you need to call in your <span class="codefrag">exec</span> method. </p>
+<p>For instance, the <span class="codefrag">UPPER</span> function would now look as follows: </p>
+<pre class="code">
+public class UPPER extends EvalFunc&lt;String&gt;
+{
+        public String exec(Tuple input) throws IOException {
+                if (input == null || input.size() == 0)
+                return null;
+                try{
+                        reporter.progress();
+                        String str = (String)input.get(0);
+                        return str.toUpperCase();
+                }catch(Exception e){
+                    throw new OException("Caught exception processing input row ", e);
+                }
+        }
+}
+</pre>
+<a name="distributed-cache"></a>
+<h4>Using Distributed Cache</h4>
+<p>Use getCacheFiles, an EvalFunc method, to return a list of HDFS files that need to be shipped to distributed cache. Inside EvalFunc, you can assume that these files already exist in distributed cache. For example:</p>
+<pre class="code">
+public class Udfcachetest extends EvalFunc&lt;String&gt; { 
+
+    public String exec(Tuple input) throws IOException { 
+        FileReader fr = new FileReader("./smallfile"); 
+        BufferedReader d = new BufferedReader(fr); 
+        return d.readLine(); 
+    } 
+
+    public List&lt;String&gt; getCacheFiles() { 
+        List&lt;String&gt; list = new ArrayList&lt;String&gt;(1); 
+        list.add("/user/pig/tests/data/small#smallfile"); 
+        return list; 
+    } 
+} 
+
+a = load '1.txt'; 
+b = foreach a generate Udfcachetest(*); 
+dump b;
+</pre>
+<a name="import-lists"></a>
+<h4>Import Lists</h4>
+<p>An import list allows you to specify the package to which a UDF or a group of UDFs belong,
+ eliminating the need to qualify the UDF on every call. An import list can be specified via the udf.import.list Java 
+ property on the Pig command line: </p>
+<pre class="code">
+pig -Dudf.import.list=com.yahoo.yst.sds.ULT
+</pre>
+<p>You can supply multiple locations as well: </p>
+<pre class="code">
+pig -Dudf.import.list=com.yahoo.yst.sds.ULT:org.apache.pig.piggybank.evaluation
+</pre>
+<p>To make use of import scripts, do the following:</p>
+<pre class="code">
+myscript.pig:
+A = load '/data/SDS/data/searcg_US/20090820' using ULTLoader as (s, m, l);
+....
+
+command:
+pig -cp sds.jar -Dudf.import.list=com.yahoo.yst.sds.ULT myscript.pig 
+</pre>
+<a name="load-store-functions"></a>
+<h3 class="h4"> Load/Store Functions</h3>
+<p>The load/store UDFs 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. </p>
+<p>
+The Pig load/store API is aligned with Hadoop's InputFormat and OutputFormat classes.
+This enables you to create new LoadFunc and StoreFunc implementations based on existing Hadoop InputFormat and OutputFormat classes with minimal code. The complexity of reading the data and creating a record lies in the InputFormat while the complexity of writing the data lies in the OutputFormat. This enables Pig to easily read/write data in new storage formats as and when an Hadoop InputFormat and OutputFormat is available for them. </p>
+<p>
+
+<strong>Note:</strong> Both the LoadFunc and StoreFunc implementations should use the Hadoop 20 API based classes (InputFormat/OutputFormat and related classes) under the <strong>new</strong> org.apache.hadoop.mapreduce package instead of the old org.apache.hadoop.mapred package. 
+</p>
+<a name="load-functions"></a>
+<h4> Load Functions</h4>
+<a name="loadfunc"></a>
+<p id="loadfunc">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/LoadFunc.java?view=markup">LoadFunc</a> 
+abstract class has three main methods for loading data and for most use cases it would suffice to extend it. There are three other optional interfaces which can be implemented to achieve extended functionality: </p>
+<ul>
+
+<a name="LoadMetadata"></a>
+<li id="LoadMetadata">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/LoadMetadata.java?view=markup">LoadMetadata</a> 
+has methods to deal with metadata - most implementation of loaders don't need to implement this unless they interact with some metadata system. The getSchema() method in this interface provides a way for loader implementations to communicate the schema of the data back to pig. If a loader implementation returns data comprised of fields of real types (rather than DataByteArray fields), it should provide the schema describing the data returned through the getSchema() method. The other methods are concerned with other types of metadata like partition keys and statistics. Implementations can return null return values for these methods if they are not applicable for that implementation.</li>
+
+
+<a name="LoadPushDown"></a>
+<li id="LoadPushDown">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/LoadPushDown.java?view=markup">LoadPushDown</a> 
+has methods to push operations from Pig runtime into loader implementations. Currently only the pushProjection() method is called by Pig to communicate to the loader the exact fields that are required in the Pig script. The loader implementation can choose to honor the request (return only those fields required by Pig script) or not honor the request (return all fields in the data). If the loader implementation can efficiently honor the request, it should implement LoadPushDown to improve query performance. (Irrespective of whether the implementation can or cannot honor the request, if the implementation also implements getSchema(), the schema returned in getSchema() should describe the entire tuple of data.)
+<ul>
+	
+<a name="pushprojection"></a>
+<li id="pushprojection">pushProjection(): This method tells LoadFunc which fields are required in the Pig script, thus enabling LoadFunc to optimize performance by loading only those fields that are needed. pushProjection() takes a requiredFieldList. requiredFieldList is read only and cannot be changed by LoadFunc. requiredFieldList includes a list of requiredField: each requiredField indicates a field required by the Pig script; each requiredField includes index, alias, type (which is reserved for future use), and subFields. Pig will use the column index requiredField.index to communicate with the LoadFunc about the fields required by the Pig script. If the required field is a map, Pig will optionally pass requiredField.subFields which contains a list of keys that the Pig script needs for the map. For example, if the Pig script needs two keys for the map, "key1" and "key2", the subFields for that map will contain two requiredField; the alias field for the first RequiredFiel
 d will be "key1" and the alias for the second requiredField will be "key2". LoadFunc will use requiredFieldResponse.requiredFieldRequestHonored to indicate whether the pushProjection() request is honored.
+</li>
+
+</ul>
+
+</li>
+
+
+<a name="loadcaster"></a>
+<li id="loadcaster">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/LoadCaster.java?view=markup">LoadCaster</a> 
+has methods to convert byte arrays to specific types. A loader implementation should implement this if casts (implicit or explicit) from DataByteArray fields to other types need to be supported. </li>
+
+</ul>
+<p>The LoadFunc abstract class is the main class to extend for implementing a loader. The methods which need to be overridden are explained below:</p>
+<ul>
+ 
+<a name="getInputFormat"></a>
+<li id="getInputFormat">getInputFormat(): This method is called by Pig to get the InputFormat used by the loader. The methods in the InputFormat (and underlying RecordReader) are called by Pig in the same manner (and in the same context) as by Hadoop in a MapReduce java program. If the InputFormat is a Hadoop packaged one, the implementation should use the new API based one under org.apache.hadoop.mapreduce. If it is a custom InputFormat, it should be implemented using the new API in org.apache.hadoop.mapreduce.<br> 
+<br> 
+ 
+ If a custom loader using a text-based InputFormat or a file-based InputFormat would like to read files in all subdirectories under a given input directory recursively, then it should use the PigTextInputFormat and PigFileInputFormat classes provided in org.apache.pig.backend.hadoop.executionengine.mapReduceLayer. The Pig InputFormat classes work around a current limitation in the Hadoop TextInputFormat and FileInputFormat classes which only read one level down from the provided input directory. For example, if the input in the load statement is 'dir1' and there are subdirs 'dir2' and 'dir2/dir3' beneath dir1, the Hadoop TextInputFormat and FileInputFormat classes read the files under 'dir1' only. Using PigTextInputFormat or PigFileInputFormat (or by extending them), the files in all the directories can be read. </li>
+ 
+ 
+<a name="setLocation"></a>
+<li id="setLocation">setLocation(): This method is called by Pig to communicate the load location to the loader. The loader should use this method to communicate the same information to the underlying InputFormat. This method is called multiple times by pig - implementations should bear this in mind and should ensure there are no inconsistent side effects due to the multiple calls. </li>
+ 
+ 
+<a name="prepareToRead"></a>
+<li id="prepareToRead">prepareToRead(): Through this method the RecordReader associated with the InputFormat provided by the LoadFunc is passed to the LoadFunc. The RecordReader can then be used by the implementation in getNext() to return a tuple representing a record of data back to pig. </li>
+ 
+ 
+<a name="getnext"></a>
+<li id="getnext">getNext(): The meaning of getNext() has not changed and is called by Pig runtime to get the next tuple in the data - in this method the implementation should use the underlying RecordReader and construct the tuple to return. </li>
+ 
+</ul>
+<a name="loadfunc-default"></a>
+<p id="loadfunc-default">The following methods have default implementations in LoadFunc and should be overridden only if needed: </p>
+<ul>
+ 
+<a name="setUdfContextSignature"></a>
+<li id="setUdfContextSignature">setUdfContextSignature(): This method will be called by Pig both in the front end and back end to pass a unique signature to the Loader. The signature can be used to store into the UDFContext any information which the Loader needs to store between various method invocations in the front end and back end. A use case is to store RequiredFieldList passed to it in LoadPushDown.pushProjection(RequiredFieldList) for use in the back end before returning tuples in getNext(). The default implementation in LoadFunc has an empty body. This method will be called before other methods. </li>
+ 
+ 
+<a name="relativeToAbsolutePath"></a>
+<li id="relativeToAbsolutePath">relativeToAbsolutePath(): Pig runtime will call this method to allow the Loader to convert a relative load location to an absolute location. The default implementation provided in LoadFunc handles this for FileSystem locations. If the load source is something else, loader implementation may choose to override this.</li>
+ 
+</ul>
+<p>
+<strong>Example Implementation</strong>
+</p>
+<p>
+The loader implementation in the example is a loader for text data with line delimiter as '\n' and '\t' as default field delimiter (which can be overridden by passing a different field delimiter in the constructor) - this is similar to current PigStorage loader in Pig. The implementation uses an existing Hadoop supported Inputformat - TextInputFormat - as the underlying InputFormat.
+</p>
+<pre class="code">
+public class SimpleTextLoader extends LoadFunc {
+    protected RecordReader in = null;
+    private byte fieldDel = '\t';
+    private ArrayList&lt;Object&gt; mProtoTuple = null;
+    private TupleFactory mTupleFactory = TupleFactory.getInstance();
+    private static final int BUFFER_SIZE = 1024;
+
+    public SimpleTextLoader() {
+    }
+
+    /**
+     * Constructs a Pig loader that uses specified character as a field delimiter.
+     *
+     * @param delimiter
+     *            the single byte character that is used to separate fields.
+     *            ("\t" is the default.)
+     */
+    public SimpleTextLoader(String delimiter) {
+        this();
+        if (delimiter.length() == 1) {
+            this.fieldDel = (byte)delimiter.charAt(0);
+        } else if (delimiter.length() &gt;  1 &amp; &amp; delimiter.charAt(0) == '\\') {
+            switch (delimiter.charAt(1)) {
+            case 't':
+                this.fieldDel = (byte)'\t';
+                break;
+
+            case 'x':
+               fieldDel =
+                    Integer.valueOf(delimiter.substring(2), 16).byteValue();
+               break;
+
+            case 'u':
+                this.fieldDel =
+                    Integer.valueOf(delimiter.substring(2)).byteValue();
+                break;
+
+            default:
+                throw new RuntimeException("Unknown delimiter " + delimiter);
+            }
+        } else {
+            throw new RuntimeException("PigStorage delimeter must be a single character");
+        }
+    }
+
+    @Override
+    public Tuple getNext() throws IOException {
+        try {
+            boolean notDone = in.nextKeyValue();
+            if (notDone) {
+                return null;
+            }
+            Text value = (Text) in.getCurrentValue();
+            byte[] buf = value.getBytes();
+            int len = value.getLength();
+            int start = 0;
+
+            for (int i = 0; i &lt; len; i++) {
+                if (buf[i] == fieldDel) {
+                    readField(buf, start, i);
+                    start = i + 1;
+                }
+            }
+            // pick up the last field
+            readField(buf, start, len);
+
+            Tuple t =  mTupleFactory.newTupleNoCopy(mProtoTuple);
+            mProtoTuple = null;
+            return t;
+        } catch (InterruptedException e) {
+            int errCode = 6018;
+            String errMsg = "Error while reading input";
+            throw new ExecException(errMsg, errCode,
+                    PigException.REMOTE_ENVIRONMENT, e);
+        }
+
+    }
+
+    private void readField(byte[] buf, int start, int end) {
+        if (mProtoTuple == null) {
+            mProtoTuple = new ArrayList&lt;Object&gt;();
+        }
+
+        if (start == end) {
+            // NULL value
+            mProtoTuple.add(null);
+        } else {
+            mProtoTuple.add(new DataByteArray(buf, start, end));
+        }
+    }
+
+    @Override
+    public InputFormat getInputFormat() {
+        return new TextInputFormat();
+    }
+
+    @Override
+    public void prepareToRead(RecordReader reader, PigSplit split) {
+        in = reader;
+    }
+
+    @Override
+    public void setLocation(String location, Job job)
+            throws IOException {
+        FileInputFormat.setInputPaths(job, location);
+    }
+}
+</pre>
+<a name="store-functions"></a>
+<h4> Store Functions</h4>
+<a name="storefunc"></a>
+<p id="storefunc">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/StoreFunc.java?view=markup">StoreFunc</a> 
+abstract class has the main methods for storing data and for most use cases it should suffice to extend it. There is an optional interface which can be implemented to achieve extended functionality: </p>
+<ul>
+
+<a name="storemetadata"></a>
+<li id="storemetadata">
+<a href="http://svn.apache.org/viewvc/pig/trunk/src/org/apache/pig/StoreMetadata.java?view=markup">StoreMetadata:</a> 
+This interface has methods to interact with metadata systems to store schema and store statistics. This interface is optional and should only be implemented if metadata needs to stored. </li>
+
+</ul>
+<a name="storefunc-override"></a>
+<p id="storefunc-override">The methods which need to be overridden in StoreFunc are explained below: </p>
+<ul>
+
+<a name="getOutputFormat"></a>
+<li id="getOutputFormat">getOutputFormat(): This method will be called by Pig to get the OutputFormat used by the storer. The methods in the OutputFormat (and underlying RecordWriter and OutputCommitter) will be called by pig in the same manner (and in the same context) as by Hadoop in a map-reduce java program. If the OutputFormat is a hadoop packaged one, the implementation should use the new API based one under org.apache.hadoop.mapreduce. If it is a custom OutputFormat, it should be implemented using the new API under org.apache.hadoop.mapreduce. The checkOutputSpecs() method of the OutputFormat will be called by pig to check the output location up-front. This method will also be called as part of the Hadoop call sequence when the job is launched. So implementations should ensure that this method can be called multiple times without inconsistent side effects. </li>
+
+<a name="setStoreLocation"></a>
+<li id="setStoreLocation">setStoreLocation(): This method is called by Pig to communicate the store location to the storer. The storer should use this method to communicate the same information to the underlying OutputFormat. This method is called multiple times by pig - implementations should bear in mind that this method is called multiple times and should ensure there are no inconsistent side effects due to the multiple calls. </li>
+
+<a name="prepareToWrite"></a>
+<li id="prepareToWrite">prepareToWrite(): In the new API, writing of the data is through the OutputFormat provided by the StoreFunc. In prepareToWrite() the RecordWriter associated with the OutputFormat provided by the StoreFunc is passed to the StoreFunc. The RecordWriter can then be used by the implementation in putNext() to write a tuple representing a record of data in a manner expected by the RecordWriter. </li>
+
+<a name="putNext"></a>
+<li id="putNext">putNext(): The meaning of putNext() has not changed and is called by Pig runtime to write the next tuple of data - in the new API, this is the method wherein the implementation will use the underlying RecordWriter to write the Tuple out.</li>
+
+</ul>
+<a name="storefunc-default"></a>
+<p id="storefunc-default">The following methods have default implementations in StoreFunc and should be overridden only if necessary: </p>
+<ul>
+
+<a name="setStoreFuncUDFContextSignature"></a>
+<li id="setStoreFuncUDFContextSignature">setStoreFuncUDFContextSignature(): This method will be called by Pig both in the front end and back end to pass a unique signature to the Storer. The signature can be used to store into the UDFContext any information which the Storer needs to store between various method invocations in the front end and back end. The default implementation in StoreFunc has an empty body. This method will be called before other methods. 
+</li>
+
+<a name="relToAbsPathForStoreLocation"></a>
+<li id="relToAbsPathForStoreLocation">relToAbsPathForStoreLocation(): Pig runtime will call this method to allow the Storer to convert a relative store location to an absolute location. An implementation is provided in StoreFunc which handles this for FileSystem based locations. </li>
+
+<a name="checkschema"></a>
+<li id="checkschema">checkSchema(): A Store function should implement this function to check that a given schema describing the data to be written is acceptable to it. The default implementation in StoreFunc has an empty body. This method will be called before any calls to setStoreLocation(). </li>
+
+</ul>
+<p>
+<strong>Example Implementation</strong>
+</p>
+<p>
+The storer implementation in the example is a storer for text data with line delimiter as '\n' and '\t' as default field delimiter (which can be overridden by passing a different field delimiter in the constructor) - this is similar to current PigStorage storer in Pig. The implementation uses an existing Hadoop supported OutputFormat - TextOutputFormat as the underlying OutputFormat. 
+</p>
+<pre class="code">
+public class SimpleTextStorer extends StoreFunc {
+    protected RecordWriter writer = null;
+
+    private byte fieldDel = '\t';
+    private static final int BUFFER_SIZE = 1024;
+    private static final String UTF8 = "UTF-8";
+    public PigStorage() {
+    }
+
+    public PigStorage(String delimiter) {
+        this();
+        if (delimiter.length() == 1) {
+            this.fieldDel = (byte)delimiter.charAt(0);
+        } else if (delimiter.length() &gt; 1delimiter.charAt(0) == '\\') {
+            switch (delimiter.charAt(1)) {
+            case 't':
+                this.fieldDel = (byte)'\t';
+                break;
+
+            case 'x':
+               fieldDel =
+                    Integer.valueOf(delimiter.substring(2), 16).byteValue();
+               break;
+            case 'u':
+                this.fieldDel =
+                    Integer.valueOf(delimiter.substring(2)).byteValue();
+                break;
+
+            default:
+                throw new RuntimeException("Unknown delimiter " + delimiter);
+            }
+        } else {
+            throw new RuntimeException("PigStorage delimeter must be a single character");
+        }
+    }
+
+    ByteArrayOutputStream mOut = new ByteArrayOutputStream(BUFFER_SIZE);
+
+    @Override
+    public void putNext(Tuple f) throws IOException {
+        int sz = f.size();
+        for (int i = 0; i &lt; sz; i++) {
+            Object field;
+            try {
+                field = f.get(i);
+            } catch (ExecException ee) {
+                throw ee;
+            }
+
+            putField(field);
+
+            if (i != sz - 1) {
+                mOut.write(fieldDel);
+            }
+        }
+        Text text = new Text(mOut.toByteArray());
+        try {
+            writer.write(null, text);
+            mOut.reset();
+        } catch (InterruptedException e) {
+            throw new IOException(e);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void putField(Object field) throws IOException {
+        //string constants for each delimiter
+        String tupleBeginDelim = "(";
+        String tupleEndDelim = ")";
+        String bagBeginDelim = "{";
+        String bagEndDelim = "}";
+        String mapBeginDelim = "[";
+        String mapEndDelim = "]";
+        String fieldDelim = ",";
+        String mapKeyValueDelim = "#";
+
+        switch (DataType.findType(field)) {
+        case DataType.NULL:
+            break; // just leave it empty
+
+        case DataType.BOOLEAN:
+            mOut.write(((Boolean)field).toString().getBytes());
+            break;
+
+        case DataType.INTEGER:
+            mOut.write(((Integer)field).toString().getBytes());
+            break;
+
+        case DataType.LONG:
+            mOut.write(((Long)field).toString().getBytes());
+            break;
+
+        case DataType.FLOAT:
+            mOut.write(((Float)field).toString().getBytes());
+            break;
+
+        case DataType.DOUBLE:
+            mOut.write(((Double)field).toString().getBytes());
+            break;
+
+        case DataType.BYTEARRAY: {
+            byte[] b = ((DataByteArray)field).get();
+            mOut.write(b, 0, b.length);
+            break;
+                                 }
+
+        case DataType.CHARARRAY:
+            // oddly enough, writeBytes writes a string
+            mOut.write(((String)field).getBytes(UTF8));
+            break;
+
+        case DataType.MAP:
+            boolean mapHasNext = false;
+            Map&lt;String, Object&gt; m = (Map&lt;String, Object&gt;)field;
+            mOut.write(mapBeginDelim.getBytes(UTF8));
+            for(Map.Entry&lt;String, Object&gt; e: m.entrySet()) {
+                if(mapHasNext) {
+                    mOut.write(fieldDelim.getBytes(UTF8));
+                } else {
+                    mapHasNext = true;
+                }
+                putField(e.getKey());
+                mOut.write(mapKeyValueDelim.getBytes(UTF8));
+                putField(e.getValue());
+            }
+            mOut.write(mapEndDelim.getBytes(UTF8));
+            break;
+
+        case DataType.TUPLE:
+            boolean tupleHasNext = false;
+            Tuple t = (Tuple)field;
+            mOut.write(tupleBeginDelim.getBytes(UTF8));
+            for(int i = 0; i &lt; t.size(); ++i) {
+                if(tupleHasNext) {
+                    mOut.write(fieldDelim.getBytes(UTF8));
+                } else {
+                    tupleHasNext = true;
+                }
+                try {
+                    putField(t.get(i));
+                } catch (ExecException ee) {
+                    throw ee;
+                }
+            }
+            mOut.write(tupleEndDelim.getBytes(UTF8));
+            break;
+
+        case DataType.BAG:
+            boolean bagHasNext = false;
+            mOut.write(bagBeginDelim.getBytes(UTF8));
+            Iterator&lt;Tuple&gt; tupleIter = ((DataBag)field).iterator();
+            while(tupleIter.hasNext()) {
+                if(bagHasNext) {
+                    mOut.write(fieldDelim.getBytes(UTF8));
+                } else {
+                    bagHasNext = true;
+                }
+                putField((Object)tupleIter.next());
+            }
+            mOut.write(bagEndDelim.getBytes(UTF8));
+            break;
+
+        default: {
+            int errCode = 2108;
+            String msg = "Could not determine data type of field: " + field;
+            throw new ExecException(msg, errCode, PigException.BUG);
+        }
+
+        }
+    }
+
+    @Override
+    public OutputFormat getOutputFormat() {
+        return new TextOutputFormat&lt;WritableComparable, Text&gt;();
+    }
+
+    @Override
+    public void prepareToWrite(RecordWriter writer) {
+        this.writer = writer;
+    }
+
+    @Override
+    public void setStoreLocation(String location, Job job) throws IOException {
+        job.getConfiguration().set("mapred.textoutputformat.separator", "");
+        FileOutputFormat.setOutputPath(job, new Path(location));
+        if (location.endsWith(".bz2")) {
+            FileOutputFormat.setCompressOutput(job, true);
+            FileOutputFormat.setOutputCompressorClass(job,  BZip2Codec.class);
+        }  else if (location.endsWith(".gz")) {
+            FileOutputFormat.setCompressOutput(job, true);
+            FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
+        }
+    }
+}
+</pre>
+<a name="Advanced+Topics"></a>
+<h3 class="h4">Advanced Topics</h3>
+<a name="udf-interfaces"></a>
+<h4>UDF Interfaces</h4>
+<p>Java UDFs can be invoked multiple ways. The simplest UDF can just extend EvalFunc, which requires only the exec function to be implemented (see <a href="#eval-functions-write"> How to Write a Simple Eval Function</a>). Every eval UDF must implement this. Additionally, if a function is algebraic, it can implement <span class="codefrag">Algebraic</span> interface to significantly improve query performance in the cases when combiner can be used (see <a href="#Algebraic-Interface">Algebraic Interface</a>). Finally, a function that can process tuples in an incremental fashion can also implement the Accumulator interface to improve query memory consumption (see <a href="#Accumulator-Interface">Accumulator Interface</a>).
+</p>
+<p>The optimizer selects the exact method by which a UDF is invoked based on the UDF type and the query. Note that only a single interface is used at any given time. The optimizer tries to find the most efficient way to execute the function. If a combiner is used and the function implements the Algebraic interface then this interface will be used to invoke the function. If the combiner is not invoked but the accumulator can be used and the function implements Accumulator interface then that interface is used. If neither of the conditions is satisfied then the exec function is used to invoke the UDF. 
+</p>
+<a name="function-instantiation"></a>
+<h4>Function Instantiation</h4>
+<p>One problem that users run into is when they make assumption about how many times a constructor for their UDF is called. For instance, they might be creating side files in the store function and doing it in the constructor seems like a good idea. The problem with this approach is that in most cases Pig instantiates functions on the client side to, for instance, examine the schema of the data.  </p>
+<p>Users should not make assumptions about how many times a function is instantiated; instead, they should make their code resilient to multiple instantiations. For instance, they could check if the files exist before creating them. </p>
+<a name="udf-configurations"></a>
+<h4>Passing Configurations to UDFs</h4>
+<p>The singleton UDFContext class provides two features to UDF writers. First, on the backend, it allows UDFs to get access to the JobConf object, by calling getJobConf. This is only available on the backend (at run time) as the JobConf has not yet been constructed on the front end (during planning time).</p>
+<p>Second, it allows UDFs to pass configuration information between instantiations of the UDF on the front and backends. UDFs can store information in a configuration object when they are constructed on the front end, or during other front end calls such as describeSchema. They can then read that information on the backend when exec (for EvalFunc) or getNext (for LoadFunc) is called. Note that information will not be passed between instantiations of the function on the backend. The communication channel only works from front end to back end.</p>
+<p>To store information, the UDF calls getUDFProperties. This returns a Properties object which the UDF can record the information in or read the information from. To avoid name space conflicts UDFs are required to provide a signature when obtaining a Properties object. This can be done in two ways. The UDF can provide its Class object (via this.getClass()). In this case, every instantiation of the UDF will be given the same Properties object. The UDF can also provide its Class plus an array of Strings. The UDF can pass its constructor arguments, or some other identifying strings. This allows each instantiation of the UDF to have a different properties object thus avoiding name space collisions between instantiations of the UDF.</p>
+<a name="udf-monitoring"></a>
+<h4>Monitoring Long-Running UDFs</h4>
+<p>Sometimes one may discover that a UDF that executes very quickly in the vast majority of cases turns out to run exceedingly slowly on occasion. This can happen, for example, if a UDF uses complex regular expressions to parse free-form strings, or if a UDF uses some external service to communicate with. As of version 0.8, Pig provides a facility for monitoring the length of time a UDF is executing for every invocation, and terminating its execution if it runs too long. This facility can be turned on using a simple Java annotation:</p>
+<pre class="code">
+	import org.apache.pig.builtin.MonitoredUDF;
+	
+	@MonitoredUDF
+	public class MyUDF extends EvalFunc&lt;Integer&gt; {
+	  /* implementation goes here */
+	}
+</pre>
+<p>Simply annotating your UDF in this way will cause Pig to terminate the UDF's exec() method if it runs for more than 10 seconds, and return the default value of null. The duration of the timeout and the default value can be specified in the annotation, if desired:</p>
+<pre class="code">
+	import org.apache.pig.builtin.MonitoredUDF;
+	
+	@MonitoredUDF(timeUnit = TimeUnit.MILLISECONDS, duration = 100, intDefault = 10)
+	public class MyUDF extends EvalFunc&lt;Integer&gt; {
+	  /* implementation goes here */
+	}
+</pre>
+<p>intDefault, longDefault, doubleDefault, floatDefault, and stringDefault can be specified in the annotation; the correct default will be chosen based on the return type of the UDF. Custom defaults for tuples and bags are not supported at this time.</p>
+<p>If desired, custom logic can also be implemented for error handling by creating a subclass of MonitoredUDFExecutor.ErrorCallback, and overriding its handleError and/or handleTimeout methods. Both of those methods are static, and are passed in the instance of the EvalFunc that produced an exception, as well as an exception, so you may use any state you have in the UDF to process the errors as desired. The default behavior is to increment Hadoop counters every time an error is encountered. Once you have an implementation of the ErrorCallback that performs your custom logic, you can provide it in the annotation:</p>
+<pre class="code">
+	import org.apache.pig.builtin.MonitoredUDF;
+
+	@MonitoredUDF(errorCallback=MySpecialErrorCallback.class)
+	public class MyUDF extends EvalFunc&lt;Integer&gt; {
+	  /* implementation goes here */
+	}
+</pre>
+<p>Currently the MonitoredUDF annotation works with regular and Algebraic UDFs, but has no effect on UDFs that run in the Accumulator mode.</p>
+</div>
+
+
+<!-- =============================================================== -->
+
+<a name="python-udfs"></a>
+<h2 class="h3">Writing Python UDFs</h2>
+<div class="section">
+<a name="register-python"></a>
+<h3 class="h4">Registering the UDF</h3>
+<p>You can register a Python script as shown here. This example uses org.apache.pig.scripting.jython.JythonScriptEngine to interpret the Python script. You can develop and use custom script engines to support multiple programming languages and ways to interpret them. Currently, Pig identifies jython as a keyword and ships the required scriptengine (jython) to interpret it. </p>
+<pre class="code">
+Register 'test.py' using jython as myfuncs;
+</pre>
+<p>The following syntax is also supported, where myfuncs is the namespace created for all the functions inside test.py.</p>
+<pre class="code">
+register 'test.py' using org.apache.pig.scripting.jython.JythonScriptEngine as myfuncs;
+</pre>
+<p>A typical test.py looks like this:</p>
+<pre class="code">
+@outputSchema("word:chararray")
+def helloworld():  
+  return 'Hello, World'
+
+@outputSchema("word:chararray,num:long")
+def complex(word):
+  return str(word),len(word)
+
+@outputSchemaFunction("squareSchema")
+def square(num):
+  return ((num)*(num))
+
+@schemaFunction("squareSchema")
+def squareSchema(input):
+  return input
+
+# No decorator - bytearray
+def concat(str):
+  return str+str
+</pre>
+<p>The register statement above registers the Python functions defined in test.py in Pig&rsquo;s runtime within the defined namespace (myfuncs here). They can then be referred later on in the pig script as myfuncs.helloworld(), myfuncs.complex(), and myfuncs.square(). An example usage is:</p>
+<pre class="code">
+b = foreach a generate myfuncs.helloworld(), myfuncs.square(3);
+</pre>
+<a name="decorators"></a>
+<h3 class="h4">Decorators and Schemas</h3>
+<p>To annotate a Python script so that Pig can identify return types, use Python decorators to define output schema for the script UDF. </p>
+<ul>
+
+<a name="outputschema"></a>
+<li id="outputschema">outputSchema - Defines schema for a script UDF in a format that Pig understands and is able to parse. </li>
+
+<a name="outputfunctionschema"></a>
+<li id="outputfunctionschema">outputFunctionSchema - Defines a script delegate function that defines schema for this function depending upon the input type. This is needed for functions that can accept generic types and perform generic operations on these types. A simple example is square which can accept multiple types. SchemaFunction for this type is a simple identity function (same schema as input). </li>
+
+<a name="schemafunction"></a>
+<li id="schemafunction">schemaFunction - Defines delegate function and is not registered to Pig. </li>
+
+</ul>
+<p>When no decorator is specified, Pig assumes the output datatype as bytearray and converts the output generated by script function to bytearray. This is consistent with Pig's behavior in case of Java UDFs. </p>
+<p>Sample Schema String - y:{t:(word:chararray,num:long)}, variable names inside a schema string are not used anywhere, they just make the syntax identifiable to the parser. </p>
+<a name="Example+Scripts"></a>
+<h3 class="h4">Example Scripts</h3>
+<p>Simple tasks like string manipulation, mathematical computations, and reorganizing data types can be easily done using Python scripts without having to develop long and complex UDFs in Java. The overall overhead of using scripting language is much less and development cost is almost negligible. The following UDFs, developed in Python, can be used with Pig. </p>
+<pre class="code">
+ mySampleLib.py
+ ---------------------
+ #/usr/bin/python
+ 
+ ##################
+ # Math functions #
+ ##################
+ #Square - Square of a number of any data type
+ @outputSchemaFunction("squareSchema")
+ def square(num):
+   return ((num)*(num))
+ @schemaFunction("squareSchema")
+ def squareSchema(input):
+   return input
+ 
+ #Percent- Percentage
+ @outputSchema("percent:double")
+ def percent(num, total):
+   return num * 100 / total
+ 
+ ####################
+ # String Functions #
+ ####################
+ #commaFormat- format a number with commas, 12345-&gt; 12,345
+ @outputSchema("numformat:chararray")
+ def commaFormat(num):
+   return '{:,}'.format(num)
+ 
+ #concatMultiple- concat multiple words
+ @outputSchema("onestring:chararray")
+ def concatMult4(word1, word2, word3, word4):
+   return word1 word2 word3 word4
+ 
+ #######################
+ # Data Type Functions #
+ #######################

[... 510 lines stripped ...]