Friday, 18 December 2015

APACHE HIVE



APACHE HIVE

The Apache Hive data warehouse software facilitates querying and managing large datasets residing in distributed storage. Hive provides a mechanism to project structure onto this data and query the data using a SQL-like language called HiveQL. At the same time this language also allows traditional map/reduce programmers to plug in their custom mappers and reducers when it is inconvenient or inefficient to express this logic in HiveQL.


GETTING STARTED WITH HIVE

Here we will try to give a simple demonstration of how hive works.

SOURCE



Hue can be accessed from HortonWorks using url:  127.0.0.1:8000

Login ID: Hue
Password: 1111


UPLOAD DATA

Data can be uploaded into the directory user/hue from the HDFS file system. 

The steps are available on the previous blogs.


Once done with this step, we will get something like this:



Now click on the top left corner of the page and click on the 2nd icon -- Beeswax(Hive UI).


FEEDING QUERIES

Click on the query editor to go to the query page.


QUERIES

Create a temp_batting table with the query


create table temp_batting (col_value STRING);





In order to check the code has executed correctly or not , we can click on Tables and then see the temp_batting table. 

Then tick the checkbox next to it and click on View as per the screenshot below.




LOADING Batting.csv INTO temp_batting



Here we load the baseball scores in our temp table using the below mentioned queriy:

LOAD DATA INPATH '/user/admin/Batting.csv' OVERWRITE INTO TABLE temp_batting;





Once the data is loaded, we can check the samples that are recorded in temp_batting table using below query.

SELECT * FROM temp_batting LIMIT 100;





Once  we execute the query, we can see the result as given below:



Now we have tocreate a new table called BATTING that will contain three columns:

player_id
year
number of runs


create table batting (player_id STRING, year INT, runs INT);




TABLE BATTING



Now we have to extract the data that we want from temp_batting and copy it into batting.  

We do it using regexp pattern and build a multi line query.

First line will overwrite the blank data into the batting table. 

Next 3 lines will extract player_id, year and runs fields form the temp_batting table.

Here is the query


insert overwrite table batting SELECT regexp_extract(col_value, '^(?:([^,]*)\,?){1}', 1) player_id, regexp_extract(col_value, '^(?:([^,]*)\,?){2}', 1) year, regexp_extract(col_value, '^(?:([^,]*)\,?){9}', 1) run from temp_batting;


Once the query is executed we can see the job status by entering the below address in the web browser 127.0.0.1:8088 and  get the below status.




Now we group the data by year using the query given below:


SELECT year, max(runs) FROM batting GROUP BY year;




OUTPUT



Now we need to check which player has scored how many runs for that given year. 

We can do this using the below query.

SELECT a.year, a.player_id, a.runs from batting a JOIN (SELECT year, max(runs) runs FROM batting GROUP BY year ) b ON (a.year = b.year AND a.runs = b.runs) ;



FINAL OUTPUT





Hope this demonstration helps. Thank you










Sunday, 6 December 2015

Process Data with Apache Pig

What is Pig?

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

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


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

Lets take a look at how pig works using a problem statement.


Problem Statement

Compute the highest runs by a player for each year.


Data processing task

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

Batting.csv - will give player with highest runs
Mster.csv - will give the player's personal information (common element : palyer id)


Steps

  • Download the zip file and extract it to get the master.csv and batting.csv files




  • Upload these two files into file browser of hue.



  • Go to Pig script console and give title to the script

  • Steps to write the pig script : 
    • 1. Load the data

      2. Then we will filter the first row of the data

      3. We use FOREACH statement to iterate through the batting data object and generate selected fields and assgin them names. The new data object we are creating is named as runs.

      4. We use GROUP statement to group elements in runs by the year field.So, we created new data 
      object grp_data

      5. We will again use FOREACH statement to find maximum runs for each year.

      6. Now we have maximum runs. So, we join this with runs data object so we can pick up player Id.

      7. The result will be a dataset with "year","playerId" and "max 
      runs".

      8. At the end we use dump statement to generate the output.




                    We can check the progress of the job initiated in the job browser


                    The job is successfully completed



                    We have received the desired result.


                    We can check the history for confirmation.



                    Saturday, 21 November 2015

                    HANDLING HADOOP

                    What is Hadoop???

                    Hadoop is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.

                    Hadoop alone cannot do wonders. It requires its other components for better performance. This is where PIG, Hive, Scoop, MapReduce and HBase come into action.

                    So, lets talk about MapReduce (MapR)

                    MapReduce is the key algorithm that the Hadoop MapReduce engine uses to distribute work around a cluster. Its working is divided in two parts : The Map and The Reduce.

                    A map transform is provided to transform an input data row of key and value to an output key/value:

                    map(key1,value) -> list<key2,value2>

                    For an input it returns a list containing zero or more (key,value) pairs:

                    • The output can be a different key from the input
                    • The output can have multiple entries with the same key

                    • A reduce transform is provided to take all values for a specific key, and generate a new list of the reduced output.

                      reduce(key2, list<value2>) -> list<value3>

                      The key aspect of the MapReduce algorithm is that if every Map and Reduce is independent of all other ongoing Maps and Reduces, then the operation can be run in parallel on different keys and lists of data. On a large cluster of machines, we can go one step further, and run the Map operations on servers where the data lives. Rather than copy the data over the network to the program, we can push out the program to the machines. The output list can then be saved to the distributed filesystem, and the reducers run to merge the results. Again, it may be possible to run these in parallel, each reducing different keys.


                      • A distributed filesystem spreads multiple copies of the data across different machines. This not only offers reliability without the need for RAID-controlled disks, it offers multiple locations to run the mapping. If a machine with one copy of the data is busy or offline, another machine can be used.

                      • A job scheduler keeps track of which MR jobs are executing, schedules individual Maps, Reduces or intermediate merging operations to specific machines, monitors the success and failures of these individual Tasks, and works to complete the entire batch job.

                      • The filesystem and Job scheduler can somehow be accessed by the people and programs that wish to read and write data, and to submit and monitor MR jobs.

                        Apache Hadoop is such a MapReduce engine. It provides its own distributed filesystem and runs jobs on servers near the data stored on the filesystem -or any other supported filesystem, of which there is more than one.

                        Limitations of MapReduce

                        • For maximum parallelism, we need the Maps and Reduces to be stateless, to not depend on any data generated in the same MapReduce job. We cannot control the order in which the maps run, or the reductions.
                        • It is very inefficient if we are repeating similar searches again and again. A database with an index will always be faster than running an MR job over unindexed data. However, if that index needs to be regenerated whenever data is added, and data is being added continually, MR jobs may have an edge. That inefficiency can be measured in both CPU time and power consumed.
                        • In the Hadoop implementation Reduce operations do not take place until all the Maps are complete (or have failed and been skipped). As a result, we do not get any data back until the entire mapping has finished.
                        • There is a general assumption that the output of the reduce is smaller than the input to the Map i.e. we are taking a large datasource and generating smaller final values.

                        Installing Hadoop
                        Here we have used HortonWorks Sandbox with HDP 2.3 to demonstrate an example of how HADOOP works. I have used it through Orcale VM Virtual Box.   

                        System Requirements: Just like the current-gen games, at least 6Gb of RAM  and i-3 processor is needed to it run decently. Once we start the virtual machine it takes around 4-5 minutes for the machine to be ready to be used. I am using 8Gb RAM and i-5 second gen processor.

                        Accessing Hadoop


                        Once the system is ready, Hadoop can be accessed on the browser at the address 127.0.0.1:8888.

                        In this page we have to access the Secure Shell Client at 127.0.0.1:4200.  

                        Check the screenshot



                        After Logging into SSH Client through "http://127.0.0.1:4200" we have to enter the login credentials.
                        By default,
                        Login : root 
                        pwd : hadoop

                        Now, starts the main course of action.

                        In this example to will try to find out the word count using a JAVA program and run it on HADOOP.

                        The steps to need to follow are:


                        • First we have to get the WordCount program in JAVA.



                        • Once we are in the shell terminal, we have to create a new directory WCclasses with the command.
                                         mkdir WCclasses

                        • Once it is done we have to create three java files to run the WordCount program.
                        We have to use vi editor to create WordMapper.java, SumReducer.java and WordCount.java. 


                        Check the screenshots












                        • Now we have to compile them using javac compile command with the class files located in the WCclasses folder.

                        To  compile, we have to use:



                        • Now we have to create a jar file in the WCclasses directory



                        • Once the jar file is created we have to create the input directory in the hdfs file system using the below command.


                        hdfs dfs -mkdir /user/ru1
                        hdfs dfs -ls /user/ru1
                        hdfs dfs -mkdir /user/ru1/wc-inp
                        hdfs dfs -ls /user/ru1/wc-inp




                        • Upload the .txt files on hue


                        We can access HUE through 127.0.0.1:8000 to upload the .txt files. 


                        • Now we have to use the below code to run the HADOOP command.

                        hadoop jar WordCount.jar WordCount /user/ru1/wc-inp /user/ru1/wc-out41

                        • We can track the logs of all jobs at the address 127.0.0.1:8088.



                        • Finally, here is a sample of the output.


                        Troubles Faced

                        While working on this the troubles we faced are:
                        • While copying the java files to the vi editor. If any character goes missing, obviously it throws error. So, one has to tear his hair out if he is unaware of this problem.
                        • The next part is while compiling the java files because the version of the HortonWorks may vary. So, we have to be extra preventive while entering the path and the version.

                        Sunday, 9 August 2015

                        Play Python - Charts- Assignment 1

                        Let's learn how to use graphs and charts in Python. The first question is: Why do we need graphs and charts?? The answer- to visualize the data. Humans can understand the patterns and trends much more easily when presented with a graph or chart rather than dealing with the raw numbers.



                        Let's start with the graphs and charts in python.

                        code

                        Here is the simple code used to plot a graph of 7 numbers.
                        output







                        The output of the above code.












                        Let's try  with a different problem. The one I used in my previous blog. The problem is on radish survey from open tech school.

                        Here we have to plot a bar graph of the different variety of radishes present in the dataset.


                        code

                        I have used my previous code to load the data and count the votes for each variety of radishes.


                        Merged the code for the graph with it.

                        I have used two modules - 

                        One is "pyplot". It is used wit Matplotlib to plot the graph.
                        The other one is NumPy which  lots of numeric functions for Python.
                        Then I have used loop to process the dictionary into a format which is readable for matplotlib.

                        The next step is indexing of the X values in the graph. It is done with the help of the  dictionary "count", where each entry is read. It helps to spread the graph evenly across the X-axis.


                        The last step is to plot the graph. plot.xtics()  is used to to add labels to the X-axis like, the names of the varities of the radishes e.g. "White Icicle".
                        bar chart




                        So, from the chart, we can summarize all our findings easily without even looking at the raw numbers of the output. 












                        This is all what I have learnt about charts in python till now and will continue to explore and keep on learning.