PIG


PIG

Pig is a high level scripting language that is used with Apache Hadoop. Pig enables data workers to write complex data transformations without knowing Java. Pig’s simple SQL-like scripting language is called Pig Latin, and appeals to developers already familiar with scripting languages and SQL.

Pig is complete, so you can do all required data manipulations in Apache Hadoop with Pig. Through the User Defined Functions(UDF) facility in Pig, Pig can invoke code in many languages like JRuby, Jython and Java. You can also embed Pig scripts in other languages. The result is that you can use Pig as a component to build larger and more complex applications that tackle real business problems.

Pig works with data from many sources, including structured and unstructured data, and store the results into the Hadoop Data File System. Pig scripts are translated into a series of MapReduce jobs that are run on the Apache Hadoop cluster.

Introduction to Apache Pig

Apache Pig is a platform, used to analyze large data sets representing them as data flows. It is designed to provide an abstraction over MapReduce, reducing the complexities of writing a MapReduce program. We can perform data manipulation operations very easily in Hadoop using Apache Pig.



The features of Apache pig are:
  • Pig enables programmers to write complex data transformations without knowing Java.
  • Apache Pig has two main components – the Pig Latin language and the Pig Run-time Environment, in which Pig Latin programs are executed.
  • For Big Data Analytics, Pig gives a simple data flow language known as Pig Latin which has functionalities similar to SQL like join, filter, limit etc.
  • Developers who are working with scripting languages and SQL, leverages Pig Latin. This gives developers ease of programming with Apache Pig. Pig Latin provides various built-in operators like join, sort, filter, etc to read, write, and process large data sets. Thus it is evident, Pig has a rich set of operators.
  • Programmers write scripts using Pig Latin to analyze data and these scripts are internally converted to Map and Reduce tasks by Pig MapReduce Engine. Before Pig, writing MapReduce tasks was the only way to process the data stored in HDFS.
  • If a programmer wants to write custom functions which is unavailable in Pig, Pig allows them to write User Defined Functions (UDF) in any language of their choice like Java, Python, Ruby, Jython, JRuby etc. and embed them in Pig script. This provides extensibility to Apache Pig.
  • Pig can process any kind of data, i.e. structured, semi-structured or unstructured data, coming from various sources. Apache Pig handles all kinds of data.
  • Approximately, 10 lines of pig code is equal to 200 lines of MapReduce code.
  • It can handle inconsistent schema (in case of unstructured data).
  • Apache Pig extracts the data, performs operations on that data and dumps the data in the required format in HDFS i.e. ETL (Extract Transform Load).
  • Apache Pig automatically optimizes the tasks before execution, i.e. automatic optimization.
  • It allows programmers and developers to concentrate upon the whole operation irrespective of creating mapper and reducer functions separately.


A = LOAD '/user/piginput/Student.csv' USING PigStorage(',') AS (name:chararray, no:int, tot:float);

$0=name
$1=no
$2=tot
X = FOREACH A GENERATE name,$2;

out=GROUP A BY desg;

OP= LOAD '/user/piginput/Demodate.csv' USING PigStorage(',') AS (id:chararray, date:chararray, status:int);
out=GROUP OP BY status;
age exp

ag=LOAD '/user/piginput/Operatordetails.csv' USING PigStorage(',') AS (name:chararray, age:int, dept:chararray);

Operatordetails.csv

agegroup= GROUP ag BY age;


agefilt = FILTER ag BY (age==8) 

co-group
A = LOAD '/user/piginput/Student_new.csv' USING PigStorage(',') AS (name:chararray, no:int, year:float);
B = LOAD '/user/piginput/Student.csv'USING PigStorage(',') AS (name: chararray, age: int, donation: float);
C = COGROUP A BY name, B BY name;

genarate 



Filter 
A = LOAD ;
B = FILTER A BY $1>'5';


Oreder by 

X = ORDER A BY a3 DESC;

store 

date 

STORE B INTO '/user/pigoutput/out/$date' USING PigStorage (',');

Union 
X = UNION A, B;




cat data;
(3,8,9)
(1,4,7)
(2,5,8)

A = LOAD 'data' AS (T: tuple (f1:int, f2:int, f3:int));
A = LOAD 'data' AS (T: (f1:int, f2:int, f3:int));

DESCRIBE A;
A: {T: (f1: int,f2: int,f3: int)}

DUMP A;
((3,8,9))
((1,4,7))
((2,5,8))
In this example the schema defines two tuples.

cat data;
(3,8,9) (mary,19)
(1,4,7) (john,18)
(2,5,8) (joe,18)

A = LOAD data AS (F:tuple(f1:int,f2:int,f3:int),T:tuple(t1:chararray,t2:int));

DESCRIBE A;
A: {F: (f1: int,f2: int,f3: int),T: (t1: chararray,t2: int)}

DUMP A;
((3,8,9),(mary,19))
((1,4,7),(john,18))
((2,5,8),(joe,18))
Bag Schema
A bag is a collection of tuples.

Syntax
alias[:bag] {tuple}

Terms
alias

The name assigned to the bag.

:bag

(Optional) The data type, bag (case insensitive).

{ }

The designation for a bag, a set of curly brackets.

tuple

A tuple (see Tuple Schema).

Examples
In this example the schema defines a bag. The two load statements are equivalent.

cat data;
{(3,8,9)}
{(1,4,7)}
{(2,5,8)}

A = LOAD 'data' AS (B: bag {T: tuple(t1:int, t2:int, t3:int)});
A = LOAD 'data' AS (B: {T: (t1:int, t2:int, t3:int)});

DESCRIBE A:
A: {B: {T: (t1: int,t2: int,t3: int)}}

DUMP A;
({(3,8,9)})
({(1,4,7)})
({(2,5,8)})
Map Schema
A map is a set of key value pairs.

Syntax (where <> means optional)
alias<:map> [ ]

Terms
alias

The name assigned to the map.

:map

(Optional) The data type, map (case insensitive).

[ ]  

The designation for a map, a set of straight brackets [ ].

Example
In this example the schema defines a map. The load statements are equivalent.

cat data;
[open#apache]
[apache#hadoop]

A = LOAD 'data' AS (M:map []);
A = LOAD 'data' AS (M:[]);

DESCRIBE A;
a: {M: map[ ]}

DUMP A;
([open#apache])
([apache#hadoop])
Schemas for Multiple Types
You can define schemas for data that includes multiple types.

Example
In this example the schema defines a tuple, bag, and map.

A = LOAD 'mydata' AS (T1:tuple(f1:int, f2:int), B:bag{T2:tuple(t1:float,t2:float)}, M:map[] );

A = LOAD 'mydata' AS (T1:(f1:int, f2:int), B:{T2:(t1:float,t2:float)}, M:[] );






Split Example :

A = LOAD '/user/piginput/sampledata.csv' using PigStorage(',') AS (name:chararray,age:int,desg:chararray);

SPLIT A INTO B IF (name is not null), igv IF (age >27 ); 


UDF 

B = FOREACH A GENERATE Upper.Upper(name);

Distinct 

A = LOAD '/user/piginput/sampledata.csv' using PigStorage(',') AS (name:chararray,age:int,desg:chararray);

D = DISTINCT A ;
FILTER X BY age >25 ;
Filter 

A = LOAD '/user/piginput/sampledata.csv' using PigStorage(',') AS (name:chararray,age:int,desg:chararray);
X = FILTER A BY age >= 25 and age < 40;
X = FILTER A BY age == 25;
X = FILTER A BY (f1 == 8) OR (NOT (f2+f3 > f1));


 A = LOAD 'allresults' USING PigStorage() AS (tcid:int, tpid:int, date:chararray, result:chararray, tsid:int, tag:chararray);
 B = GROUP A BY (tcid, tpid); 
 
 FLATERN
 

 group 
A = load 'employee' AS (name:chararray,age:int,desig:chararray);
B = GROUP A BY age;

DESCRIBE A;
DESCRIBE B;
ILLUSTRATE B;
cogroup 



join 

A = LOAD 'data1' AS (name:chararray,age:int,desig:chararray);
B = LOAD 'data2' AS (usercode:chararray,name:chararray);

X = JOIN A BY name, B BY name;

C = JOIN A by $0 LEFT OUTER, B BY $0;

C = JOIN A BY $0 FULL, B BY $0;


ORDER 


A = LOAD 'data' AS (a1:int,a2:int,a3:int);

X = ORDER A BY a3 DESC;


UNIOn

A = LOAD 'data' AS (a1:int,a2:int,a3:int);

DUMP A;
B = LOAD 'data' AS (b1:int,b2:int);

DUMP A;

X = UNION A, B;

DUMP X;



 
UDF 
REGISTER Upper.jar;
A = LOAD '/user/piginput/Student.csv' using PigStorage(',') AS (name:chararray,age:int,desg:chararray);
B = FOREACH A GENERATE Upper(name);
 
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.util.WrappedIOException;

public class UPPER extends EvalFunc<String>
{
    public String exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0)
            return null;
        try{
            String str = (String)input.get(0);
            return str.toUpperCase();
        }catch(Exception e){
            throw WrappedIOException.wrap("Caught exception processing input row ", e);
        }
    }
}

B = FOREACH A GENERATE Upper.Upper(name);


How to process XML in Hadoop


To process XMLs in Pig, piggybank.jar is essential. This jar contains a UDF called XMLLoader() that will be used to read the XML document.  

Below is the flow diagram to describe the complete flow from extraction to analysis.

processing XML in Hadoop image 2

File Name :- books.xml

<CATALOG>
<BOOK>
<TITLE>Hadoop Defnitive Guide</TITLE>
<AUTHOR>Tom White</AUTHOR>
<COUNTRY>US</COUNTRY>
<COMPANY>CLOUDERA</COMPANY>
<PRICE>24.90</PRICE>
<YEAR>2012</YEAR>
</BOOK>
<BOOK>
<TITLE>Programming Pig</TITLE>
<AUTHOR>Alan Gates</AUTHOR>
<COUNTRY>USA</COUNTRY>
<COMPANY>Horton Works</COMPANY>
<PRICE>30.90</PRICE>
<YEAR>2013</YEAR>
</BOOK>
</CATALOG>
There are two approaches to parse an XML file in PIG.
1. Using Regular Expression
2. Using XPath
Lets discuss one by one.
Using Regular Expression : Here using the XMLLoader() in piggy bank UDF to load the xml, so ensure that Piggy Bank UDF is registered.  Then I am using regular expression to parse the XML.  

REGISTER piggybank.jar
register '/home/training/Desktop/data/pig_data/piggybank.jar';

A = load '/home/training/Desktop/data/pig_data/books.xml' using org.apache.pig.piggybank.storage.XMLLoader('BOOK') as(x:chararray);
 dump A;
(<BOOK>
<TITLE>Hadoop Defnitive Guide</TITLE>
<AUTHOR>Tom White</AUTHOR>
<COUNTRY>US</COUNTRY>
<COMPANY>CLOUDERA</COMPANY>
<PRICE>24.90</PRICE>
<YEAR>2012</YEAR>
</BOOK>)
(<BOOK>
<TITLE>Programming Pig</TITLE>
<AUTHOR>Alan Gates</AUTHOR>
<COUNTRY>USA</COUNTRY>
<COMPANY>Horton Works</COMPANY>
<PRICE>30.90</PRICE>
<YEAR>2013</YEAR>
</BOOK>)

B = foreach A GENERATE FLATTEN(REGEX_EXTRACT_ALL(x,'<BOOK>\\s*<TITLE>(.*)</TITLE>\\s*<AUTHOR>(.*)</AUTHOR>\\s*<COUNTRY>(.*)</COUNTRY>\\s*<COMPANY>(.*)</COMPANY>\\s*<PRICE>(.*)</PRICE>\\s*<YEAR>(.*)</YEAR>\\s*</BOOK>'));
dump B;
Output:-
(Hadoop Defnitive Guide,Tom White,US,CLOUDERA,24.90,2012)
(Programming Pig,Alan Gates,USA,Horton Works,30.90,2013)

Using XPath : It is second approach to solve xml parsing problem through Pig. XPath is a function that allows text extraction from xml. Starting PIG 0.13 , Piggy bank UDF comes with XPath support. It eases the XML parsing in PIG scripts.

A sample script using XPath is as shown below.
REGISTER piggybank.jar
DEFINE XPath org.apache.pig.piggybank.evaluation.xml.XPath();

A = load '/home/training/Desktop/data/pig_data/books.xml' using org.apache.pig.piggybank.storage.XMLLoader('BOOK') as(x:chararray);

B = FOREACH A GENERATE XPath(x, 'BOOK/AUTHOR'), XPath(x, 'BOOK/PRICE');

dump B;
Output:
(Tom White,24.90)
(Alan Gates,30.90)





No comments:

Post a Comment