Monday, June 19, 2017

Hive-conditionalTransformation

conditional transformation
--------------------------
if function
-----------
It is used to perform conditional transformatins.

if(condition,true val,false val)
1st argument is condition
2nd argument true val
3rd argument false val

[cloudera@quickstart ~]$ cat file1
200,300
100,200
200,100
700,800
700,400

hive> create table data(a int,b int)
    > row format delimited fields terminated by ',';

hive> load data local inpath 'file1' into table data;

hive>select *from data;

syntax
------
alter table tablename add columns(col1 type,col2 type,....);

hive>alter table data add columns(big int);

hive> insert overwrite table data
    > select a,b,if(a>b,a,b) from data;

Nested if functions
-------------------
cat > file1
100,200,300
400,200,500
700,500,100
900,400,1000

hive> select a,b,c,if(a>b,if(b>c,b,c),if(a>c,a,c)) from ifdata;

Wednesday, June 14, 2017

Hadoop-yarn and its execution flow.

Yarn
----
An   Yarn Architecture has 3 core components

i)ResourceManager
It handles  both resource management and scheduling in Hadoop
It replace JobTracker in hadoop2.

It has 2 core components
i)Application Manager
It manages running Application Masters in the cluster, i.e., it is responsible for starting application masters and for monitoring and restarting them on different nodes in case of failures.
It also manages resources

ii)Scheduler
Scheduler is responsible for allocating the resources to the running application.
Scheduler is pure scheduler it means that it performs no monitoring no tracking for the application.
The Scheduler has a pluggable policy plug-in,
The current Map-Reduce schedulers such as the CapacityScheduler and the FairScheduler are some examples

ii)NodeManager
It is the slave daemon of Yarn
NM  Manages containers.
It also keeps track of health.


iii)Application Master
One application master runs per application. It negotiates resources from the resource manager and works with the node manager.
It Manages the application life cycle.
The AM acquires containers from the RM’s Scheduler before contacting the corresponding NMs to start the application’s individual tasks.


Yarn Architecture Flow
-----------------------
1)User will submit a job to Resource Manager.

2)Resource Manager will issue a request to Application Manager to communicte with NodeManager and start Application Master.

3)In a yarn Architecture No of Node Managers is one per machine or System.

4)Number of Application Master running is equivalent to  no of Application's submitted by user i,e MapReduce,Apache Tez,Spark .

Here All MapReduce jobs are treated as MapReduce Application.

5)Each Node Manager is associated with 1 Application Master(s) i,e 1 per Application

MapReduce--1 App Master.
Spark--1 App Master.
Apache Tez--1 App Master.

6) An Application Master is by default in sleep mode(passive mode)

7)Whenever Resource Manager needs to Process a job then it instruct NodeManager to lauch Application Master which is in sleep mode.

8)Once Node Manager launch Application Master,AM will request for containers to the scheduler of Resource Manager.

9)Here Scheduler allocate Resources for containers.

10)A container is collection of (RAM,cpu,disk,Network) in which Application tasks are executed.

11)Once Resources are allocated by Scheduler,Application Master  will request NodeManager to launch Containers where the tasks are executed.

12)Node Manager will track and monitor the life cycle of containers and update the status to ResourceManger's Application Manager through Application Master.

13)Application Master acts a communication channel bewteen Nodemanger and ResourceManager.

14)Till 2.0 version there is a SPOF[single point of failure] for Resource Manager but from then it has a Stand By(Passive RM),if the active RM is down then the passive will become active immediately,this makes RM higly fault tolerant.

15)If any node is down where Node Manager and App master is running,then if the App Master is destroyed then the other  NodeManagers reporting to App master can directly communicate with RM.

16)To Clarify the above stament,An Application Master will requesr for containers where ever data is available,An Application Master running in one Node will communicate with other  NodeManager's running in other machine's,All these NodeManager's will report the status of Node to App Master and App Master will update the status to RM.

16)Here Application Master can Allocate containers in different Node's and Track the staus of Application through these NM as discussed above.

RM             <--->        APP Master<---->NM1
Scheduler                            
App Manager                           <--->NM2
                                      <--->NM3
                                     ..
                                     ..
17)Here Application Manager of RM will take care of Monitoring and Tracking the status of Node's through App Master as shown above.

18)NodeManagers will send heart beats consistently to App Master and App Master update the same to Application Manager of RM.

18)If Application Manager is not receiving heart beats for atleast 10 mins from a NodeManager through Application Master ,then the Resource Manager assumes the NodeManager is down and assigns the Job to some other NodeManager running in the cluster.


Monday, June 12, 2017

MapReduce-Intorduction-Step by Step analysis of Mapper,Reducer with complete execution flow

In hadoop every application is converted to MapReduce job.

It is data processing model which consists of 2 core components

i)Mapper
ii)Reducer

Execution flow of MapReduce Application
---------------------------------------
step1:
we give text file as input

abc.txt
-------
My Name is Manohar        
Iam born for Teaching
I love Teaching

step2
-----
FileInputFormat receives the input and covert the text file into key/value pairs as shown below

FileInputFormat-->Input splits

Note:Default InputFormat is TextInputFormat

key-->byteoffset
value--->Text(row)

split1
0,
My Name is Manohar        

split2
18,
Iam born for Teaching

split3
40,
I love Teaching

step3:
-----
The input splits are givena as input to Mapper
Mapper will receive the key/value pairs from FileInputFormat,here the key is byteoffset,value is text

Mapper will read the value which is Text and convert the text into key/value pairs as shown below

My,1
Name,1
is,1
Manohar,1

Iam,1
born,1
for,1
teaching,1

I,1
love,1
teaching,1

Here in the above Mapper output,key is word/text and for every mapper initializes one(1).so Mapper accepts a row as input and converts the text as output in the form of key/pairs as shown as above


step4:
sorting and shuffling
Here all the key/value pairs are sorted and shuffled according to alphabetical order.

born,1
for,1
..
...
..



step5:
The output generated by Mapper after sorting and shuffling it is given as input to Reducer.

Reducer takes ket/value pairs as input and perform aggregation and generate output as key/values as shown'


born,1
for,1
..
..
teaching,2

step1:
cat > file1
My Name is Manohar
I live for teaching
I die while teaching


step2:
we need 3 classes
i)Mapper class
ii)Reducer class
iii)Driver class

step2.1
-------
How to create a Mapper class
Mapper accpets key value pairs as input from  FileInputStream and converts the value received from FIS into key and value pairs as output

file1[FileInputStream]
----------------------
0  -->key
My Name is Manohar-->value

20 -->key
I live for teaching-->value

40-->key
I die while teaching-->value


MapReduce
---------
java datatypes[primitives] --->Mapreduce datatypes[Classes]
byte-->ByteWritable
int--IntWritable
long-->LongWritable
float-->FloatWritable
double-->DoubleWritable
String--->Text

A Writable consists of set() and get()
set()--sets a values to a avariable.
get()-->gets a value from a variable.


Mapper Logic
------------
Input-->key-->LongWritable
       value-->Text

0,
My Name is Manohar.

Mapper logic for wordcount
--------------------------
Read the Text value
-------------------
Text-->My Name is Manohar

splits the Text into key/value pairs

My-->key
value-->1

Name->key
value-->1

is-->key
value-->1

Manohar-->key
value-1

And finally Write key/value pair back as output.

steps to create Mapper
----------------------
step1:

Extend a class from a Mapper class available in org.pache.mapreduce.io.* package.

public class MyMapper extends  Mapper<LongWritable, Text, Text, IntWritable> {




}

Mapper<LongWritable, Text, Text, IntWritable> {
        k1            v1   k2       v2


k1,v1-->inputs coming from FileInputStream
K2,v2-->output generated by map() method


Mapper class has 4 methods
--------------------------
protected void cleanup(org.apache.hadoop.mapreduce.Mapper.Context context)

Called once at the end of the task.

protected void map(KEYIN key, VALUEIN value, Context context)

Called once for each key/value pair in the input split.

void run(org.apache.hadoop.mapreduce.Mapper.Context context)
Expert users can override this method for more complete control over the execution of the Mapper.

protected void setup(org.apache.hadoop.mapreduce.Mapper.Context context)

Called once at the beginning of the task.


step2:override map() method in Mapper class
-------------------------------------------
public void map(LongWritable k,Text v,Context context)
{


}


Reducer
-------
A Reducer is used to perform an aggregation on a key/value pair.

A Reducer accpets input as key/value pair and generate output as key/value pair.

Reducer logic
-------------
Input from Mapper
-----------------
My-->key
value-->1

Name-->key
value-->1

is-key
value-1

..
I-key
value-1

..

Teaching--key
value--1

..
I-key
value

..

Teaching--key
value--1


output
-------
My,1
name,1
is,1
Manohar,1
I,2
live,1
..
Teaching,2


steps to create Reducer class
-----------------------------
step1:Extend a class from Reducer

acessmodifier class ClassName extends Reducer<K1,V1,K2,V2>
{
}


K1,V1-->Input from Mapper
K2,V2-->output from Reducer

step2:
override reduce() method of Reducer in the sublcass

public void reduce(Text k, Iterable<IntWritable> list, Context       con) throws IOException, InterruptedException{
              ....
              ....
}

Mapper logic for wordcount
--------------------------
0,
My name is Manohar

0-->k[LongWritable]
My name is Manohar-->value[Text]

step1:
convert Text to String
----------------------
String str=value.toString();

step2:
split string into tokens

String s[]=str.split(" ");

My s[0]
Name s[1]
is s[2]
Manohar s[3]


step3:
Iterate String array and write each token/word with 1

for(int i=0;i<s.length();i++)
{
   context.write(new Text(s[i]),new IntWritable(1));
}











































































































Hive-Internal and external tables

Hive tables
-----------
Inner and external tables.
partitioned and Non partitioned tables.
Bucketd and Non bucketed tables.

inner vs external tables

when an inner table is dropped both metadata and data will be deleted.

when an external table is dropped only metadata is deleted.

From hive if we drop an inner table,the directory in hdfs is also deleted.

From hive if we drop an external table,the directory in hdfs is available.

if we drop inner table we loose both table and data where as if we drop external table we loose only table but not data and we can reuse the data if needed.

creating and testing external tables
---------------------------------
hive>cat > file1
AAAAA
AAAAA
^c

Note:By default each table is inner table.

creating external table.
--------------------
hive>create external table tab1(line string);

In hdfs /user/hive/warehouse/tab1 a directory is created.

hive>desc tab1;

loading data into table
-----------------------
syntax
------
load data local inpath 'filename' into table tablename;


hive>load data local inpath 'file1' into table tab1;

In hdfs
   /user/hive/warehouse/tab1/file1

file1 is copied into tab1 directory from local.

displaying data
---------------
hive>select *from tab1;
AAAA
AAAA
AAAA
AAAA

drop table tab1
---------------
drop table tab1;


Now hive starts reading data from all the tables.

cat>file2
BBBB
BBBB
^c

creating inner and external tables in custom hdfs location
----------------------------------------------------------
hive> create table mytab1(line string)
    > location '/guru/myloc';

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:Got exception: org.apache.hadoop.security.AccessControlException Permission denied: user=cloudera, access=WRITE, inode="/mano":hdfs:supergroup:drwxr-xr-x

How to handle issue
-------------------
create a supergroup and assign it to cloudera.

[cloudera@quickstart ~]$ sudo groupadd supergroup
[cloudera@quickstart ~]$ usermod -a -G supergroup cloudera
bash: /usr/sbin/usermod: Permission denied
[cloudera@quickstart ~]$ sudo usermod -a -G supergroup cloudera


$cat > abc.txt
aaaaa
bbbbb
ccccc
ddddd
eeeee

hive>load data local inpath 'abc.txt' into table mytab1;

In hdfs,
   /guru/myloc/abc.txt is available
   
hive>drop table tab1;

if it is inner table /guru/myloc  will be deleted otherwise it is available

Hive--Basic operations

Hive operations
---------------
[cloudera@quickstart ~]$ cat emp.txt
eno  name  sal    g dno
101,AAAAA,1000.00,m,11
102,BBBBB,2000.00,m,12
103,CCCCC,3000.00,f,13
104,DDDDD,4000.00,f,14
105,EEEEE,5000.00,m,15
106,FFFFF,6000.00,f,16
107,GGGGG,7000.00,m,17
108,HHHHH,8000.00,m,18
109,xxxxx,1000.00,f,11
110,yyyyy,2000.00,f,18
111,zzzzz,2000.00,f,15


hive> create table empdata(eno int,name string,sal double,gender string,dno int)
    > row format delimited fields terminated by ',';

hive>desc empdata;

hive>load data local inpath 'emp.txt'  into table empdata;

hive>select *from empdata;

Queries
-------
display all females
display all males
display all males whose dno=11,12
All females not in  dno 13,15
All rows of 11,14
Display all dno except dno 13,15.


hive> select *from empdata where gender='f';
hive> select *from empdata where gender='m';
hive> select *from empdata where (dno=11 or dno=12) and gender='m';
hive> select *from empdata where (dno!=13 and dno!=15) and  gender='f'
hive> select *from empdata where dno=11 or dno=14;
hive> select *from empdata where dno!=13 and dno!=14;


in operator
-----------
In is display rows within a given set.
hive> select *from empdata where dno in(11,12) and gender='m';
hive> select *from empdata where dno in(11,14);
hive> select *from empdata where dno not in(13,15) and gender='f';
hive> select *from empdata where dno not in(13,15);


between
-------
It is an operator used to display rows between given condition
display all employees whose sal is between 3000 and 7000

hive> select *from empdata where  sal>=3000  and sal<=7000;
hive> select *from empdata where  sal between   3000 and 7000;


Not between
-----------
display all employees whose sal is not between 3000 and 7000

hive> select *from empdata where  sal<3000 or sal>7000;
hive> select *from empdata where  sal not between   3000 and 7000;

displaying top rows
-------------------
limit
-----
display top n rows in a table.

syntax
------
hive>select *from tablename limit n;

ex:
hive>select *from  empdata limit  5;

sorting rows of a table
------------------------
order by
--------
we use order by clause to sort rows of a table.


syntax
------
select *from tablename order by colname asc;
or
select *from tablename order by colname desc;


hive> select *from empdata order by sal;
hive> select *from empdata order by sal desc;

Adding new column to a table
----------------------------
syntax
------
alter table tablename add columns(col1 type,col2 type,....);

ex:
hive> alter table empdata add columns(tax double);

hive> alter table empdata add columns(tax int);


updating a table
----------------
In hive we if we add a new col to a table or if we want to update a col of table we go for table to table copying.

hive> insert overwrite table empdata
    > select eno,name,sal,gender,dno,sal*0.2 from empdata;


like
----
create a table replica.


syntax
------
create table tablename like tablename2;

we copy data from table to table by using insert overwrite/insert into.

hive> create table staff like emp;

hive> insert overwrite table staff
    > select *from empdata;

hive> insert into table staff
    > select *from empdata;

Note1:insert overwrite ....;
     replace old records with new records.

Note2:insert into  ....;
      appends records to existing table.


deleting rows from a table
--------------------------
delete all female rows from a staff table but dont' use delete.

hive> insert overwrite table staff
    > select *from staff where gender='m';

Hive-collection datatypes

Array
-----
Array is collection of similar type of values.

we use datatype array to declare array in a hive table

syntax
------
colname array<type>



cat > courses.txt

1,satya,hadoop$c$cpp$java
2,aaaa,hadoop$c$cpp$java
3,bbbb,photo$animation

syntax
------
create table tablename(col1 type,col2 type,...)
row format delimited fields terminated by 'symbol'
collection items terminated by 'symbol'

ex:
hive> create table courses(id int,iname string,course array<string>)
    > row format delimited fields terminated by ','
    > collection items terminated by '$';

hive> load data local inpath 'courses.txt' into table courses;
hive> select *from courses;
1 satya ["hadoop","c","cpp","java"]
2 aaaa ["hadoop","c","cpp","java"]
3 bbbb ["photo","animation"]


Internal representation of array
---------------------------------
------
haoop|0
-----
c    |1
-----
cpp  |2
-----
java |3
-----

An array always starts with index 0 and ends with size-1

query1
------
Display id,courses from courses table
Display id,name,first 2 courses from array in a courses table
Display all courses whose id is 1
Display first  course from courses table whose id is 1
Display 3,4  courses from courses table whose id is 3


hive> select id,course from courses;
OK
1 ["hadoop","c","cpp","java"]
2 ["hadoop","c","cpp","java"]
3 ["photo","animation"]

hive> select id,iname,course[0],course[1] from courses;
1 satya hadoop c
2 aaaa hadoop c
3 bbbb photo animation

hive>select course from courses where id=1;
["hadoop","c","cpp","java"]

hive> select course[0] from courses where id=1;
hadoop

hive> select course[2],course[3] from courses where id=3;
NULL NULL

Note:if we try to get values from an array whose index does not exist then hive returns NULL values if the index is not found.

Map
---
A Map is a collection used to represent data in the form of key and value pairs.

key=value
key must be unique,values can be duplcated.
we use key to perform operations on a map.

ex:
1=manohar
2=sanjay

syntax
------
key1=val1<symbol>key2=val2<symbol>key3=val3......

cat>items.txt
1,more,1=soap#2=sampoo#3=perfume
2,spencer,1=choclate#2=gum#3=lays
3,reliance,1=cola#2=maggy#3=colgate

How to declare map in a hive
----------------------------
we represent map in hive table using map datatype

syntxa
------
colname  map<type1,type2>


while creating a table with map datatype we should specify 3 delimiters with
i)row format
ii)collection items
iii)Map keys

syntax
-----
create table tablename(colname type1,........)
row format delimited fields termianted by 'symbol'
collection items terminated by 'symbol'
map keys terminated by 'symbol';

ex:
hive> create table items(id int,name string,products map<int,string>)
    > row format delimited fields terminated by ','
    > collection items terminated by '#'
    > map keys terminated by '=';

hive>load data local inpath 'items.txt' into table items;

hive>select *from items;
1 more {1:"soap",2:"sampoo",3:"perfume"}
2 spencer {1:"choclate",2:"gum",3:"lays"}
3 reliance {1:"cola",2:"maggy",3:"colgate"}


How to access data from a map collection
---------------------------------
colname[key]


display a map collection whose id is 3,2
display a map collection whose key is 1,2
display a map collection whose key is 1,2 where id is 1
display a map collection whose key is 2,3 where id is 1,3
display a map collection whose key is 3 where id is 1,2,3

hive> select *from items where id=2 or  id=3;
hive> select products[1],products[2] from items;
hive> select products[1],products[2] from items where id=1;
hive> select products[1],products[2] from items where id=2 or id=3;


structure
---------
A structure is collection of different types of values.
we declare a strcuture in a hive table using the datatype struct.

syntax
------
colname struct<var1:type,var2:type,.....>

ex:
address struct<city:string,pin:int,stno:int>

How to represent struct in a dataset
-------------------------------------
emp.txt
-------
1,aaa,hyd$5002$43
2,bbb,bombay$5002$43
3,ccc,delhi$5002$43


Here we should we should use 2 delimiters  with
i)row format
ii)collection items

table syntax
------------
create table tablename(colname type1,........)
row format delimited fields termianted by 'symbol'
collection items terminated by 'symbol';


ex:
hive> create table emp_struct(id int,name string,addr struct<city:string,pin:int,stno:int>)
row format delimited fields termianted by ','
collection items terminated by '$';

hive>load data local inpath 'emp.txt' into table emp_struct;
hive>select *from emp_struct;

How to access data from a struct
--------------------------------
syntax
------
colname.varnamecut

ex:
address.city

display city,pin from table emp_struct
display eno,name,stno from emp
display eno,name,stno from emp where id is 1,2

hive> select addr.city,addr.pin from emp_struct;
hive> select id,name,addr.stno from emp_struct;
hive> select id,name,addr.stno from emp_struct where id=1 or id=2;

Note:hive  does not support union datatype.















































































































Hive-Processing temperature dataset in hive

$cat > temp1
xxxxx2009xxx27xxxx
xxxxx2010xxx39xxxx
xxxxx2015xxx45xxxx
xxxxx2016xxx49xxxx
xxxxx2020xxx55xxxx
xxxxx2012xxx43xxxx
xxxxx2006xxx40xxxx


create table raw_temp(line string);

load data local inpath 'temp1' into table raw_temp;

In the above dataset get year,temperature and display
-----------------------------------------------------
we get temperature and year from a row by using the method substr()

syntax
------
substr(colname,position,length)

position-->From where the substr starts.
length-->no of characters in the substring.

substr(line,6,4)-->returns year from the above dataset.
substr(line,13,2)-->returns temperature from the above dataset.


hive>select substr(line,6,4),substr(line,13,2) from raw_temp;

output
------
2009 27
2010 39
2015 45
2016 49
2020 55
2012 43
2006 40

hive>select substr(line,0,5) from raw_temp;

copying data from table to table
--------------------------------
syntax
------
insert overwrite table destinationtablename
select *from sourcetablename;

cat > file1
1,2
3,4
5,6

hive> create table tab9(a int,b int)
row format delimited fields terminated by ',';

hive>load data local inpath 'file1' into table tab9;

hive> create table tab10(a int,b int)
row format delimited fields terminated by ',';

hive>insert overwrite table tab10
select *from tab9;

copying data from table to table with different order
-----------------------------------------------------
create  table tab11(a int,b int);


insert overwrite table tab11
select a,b from tab8;

hive>select *from tab11;


Filtering year,temparture from temperature datset
-------------------------------------------------
create table year_temp(y int,t int);

insert overwrite table year_temp
select substr(line,6,2),substr(line,13,2) from raw_temp;

select *from year_temp;

Processing employee dataset
---------------------------
cat > employee.txt
1,abc,1000.00,m,11
2,bbb,2000.00,f,12
3,ccc,2000.00,f,12
4,ddd,3000.00,m,14
5,eee,4000.00,f,15


create table emp(eno int,name string,sal double,gender string,dno int);

load data local inpath 'employee.txt' into table emp;

select *from emp;

tabl22
------
create table emp2(eno int,name string,sal double,gender string,dno int);

insert overwrite table emp2
select *from emp;

select *from emp2;


emp with 3 cols
--------------
create table emp3(eno int,name string,sal double);

insert overwrite table emp3
select eno,name,sal from emp;

select *from emp3;


Appedning data to a table using insert command
----------------------------------------------
Remove overwrite and use insert into command for appending data to a destination table from a source table.

insert into table emp3
select eno,name,sal from emp2;

select *from emp3;
1,
2,
..
..
1,..
2,..

temperature dataset
-------------------
cat > temp1.txt
xxxxx2009xxx27xxxx
xxxxx2010xxx39xxxx
xxxxx2015xxx-45xxxx
xxxxx2016xxx49xxxx
xxxxx2020xxx-55xxxx
xxxxx2012xxx43xxxx
xxxxx2006xxx-40xxxx

create rawtemp1(line string);

load data local inpath 'temp1.txt' into table rawtemp1;

select *from rawtemp1;

case1:displaying +ve temperatures
---------------------------------


case2:displaying -ve temperatures
---------------------------------


case3:Merging both +ve and -ve temperatures
-------------------------------------------
Merging results of 2 subqueries is done by using the clause unionall

union is not supported in hive

syntax
------
select *from(sql_query1
union all
sql_query2) temp_table_name;