Friday, 12 June 2015

Big Data In Railways...

RailYatri, the train travel portal, is adding a new track to its services with the newly introduced insights section. The insight platform has data and tools that will help train passengers make an informed decision.
Globally, there are platforms like Insight, Think Digital Travel, Think with Google, and Sojern to name a few that are bringing intelligence and big data to travel. With its insights platform, Rail Yatri aims to bring big data analytics to the Indian Railways.
Rail Yatri believes that the demand for rail tickets is set to become exponentially higher than its supply.  Big data is used world-wide to help travellers, but is not as popular in India. “We believe that this is a one of its kind platform where people can look at data and analyse one of the biggest travel networks in the world,” says Manish Rathi, Founder of RailYatri.
yourstory-Rail-Yatri

Understanding the needs of train travellers
From the time of its inception RailYatri has been adding several features to simplify the process of train travel. One of these is the ‘Seat Availability Forecast,’ which suggests the best train to take from point A to point B, depending on the time and day of travel.
While, there are several other platforms like Trainman and ConfirmTkt that give information on seat availability. RailYatri is adding another layer to this, with the Insights Platform.
yourstory-Rail-Yatri-InsideArticle1
The recently launched ‘RailYatri Insights’ provides users with intelligent and intuitive data-led predictions such as: where are people travelling to, the busiest train routes,mobile network coverage on routes, and train delays.“We believe when it comes to train travel, nothing is enough,” adds Manish.
The insights platform uses Google Maps to make the data relevant to train travellers according to their locations. The detailed information on both long distance and local trains also includes information on restaurants near railway stations. A traveller can hire a taxi through the website and the mobile app, in over 30 cities across the country.
The platform currently claims to have over two million monthly active users and has had over a million downloads in less than a year.
How does it work?
The insights platform collects information from data that is spread across several different meta-data fields that have been captured by Rail Yatri for over a year. Working on the information gathered, theinsights platform has several algorithms that answer questions like – the probability of a train reaching its destination on time, frequency of a particular train, and also information like what is the likelihood of getting a confirmed seat.
Apart from information on train schedules and behaviour, this insights platform also provides information on which side to enter a platform from, whether the station has a retiring room, and other such smaller wisdoms.  “These wisdoms are added by our users, so the insights platform essentially acts as a crowd sourced platform as well,” says Manish.
yourstory-Rail-Yatri-InsideArticle2While you might get schedules and other details on any website or travel portal, the intelligence associated with informing one if a train will arrive on time is relatively new in India. It is the huge data bank that has been gathered for over more than a year, which helps the platform feed in the relevant and intelligent information.
Evolution of the space
Today’s train traveler has access to information and does not want to be bothered with apps supplying the same information. “Train travelers don’t shy away from spending on travel-related services as long as quality is assured. In fact, some of our features were introduced after repeated requests from our users,” says Manish.
The team believes that the modern train traveler increasingly resembles the airplane traveler in terms of travel preferences, consumption profile, awareness, and information needs.“With RailYatri insights we aim to simplify train travel in India. The only way a traveller can make an informed decision is through insights and intelligence. We believe that is a useful and powerful tool for train travellers,” concludes Manish.

Wednesday, 10 June 2015

MapReduce Hello World Program...

In this post, we will discuss the following with regards to MapReduce framework :-
  1. Motivation for a parallel processing framework
  2. What is MapReduce?
  3. How MapReduce solves a problem?
  4. MapReduce in detail
    1. Map Phase
    2. Shuffle & Sort Phase
    3. Reduce Phase

Motivation for a parallel processing framework

As you know we are living in the age of Data. Today the size of internet is almost 40+ billion web pages.  If we assume that each page has 20Kb of data, we looking at somewhere close to 800+ terabyte of data. With the reading speed of 100 Mbps, it will take a computer more than 4 months to read the web. And just to store such huge data, we will need 1000’s of computers. 
Clearly we need a mechanism to divide such huge work among various computers. If we give the same work of reading 400+ terabytes of data to say 1000 computers, it can be done in less than 3 hours.
But our task is not limited to reading data. We need also need to process such massive data. Clearly consolidating the data from the nodes and transferring it to the compute nodes will take a lot of time. We therefore need a programming framework that allows for distributing the computation task and running them in parallel.

What is MapReduce?

MapReduce is one such programming model designed for processing large volumes of data in parallel by dividing the work into a set of independent tasks.1  Each of these tasks are then run on individual node in a cluster. The advantage of MapReduce framework is that, it not only divides the work but also also abstracts the programmer from all the issues that come with distributed computing such as communication and coordination, recovering from machine failure, status reporting, debugging, optimization and data locality.

How MapReduce solves a problem?

A typical problem solved by MapReduce can be broken down into the following steps :-
  1. Read a lot of data
  2. Extract something you are interested in from every record
  3. Shuffle and sort the intermediate results
  4. Aggregate (filter, sort or transform) the intermediate result
  5. Write out the result

MapReduce in detail

The figure below will give you an overview of MapReduce. In MapReduce everything is in terms of key-value pairs. The phases of the MapReduce task are Map, Sort & Shuffle and Reduce.
The two Daemons associated with MapReduce are JobTracker and TaskTracker. The Client submits the job to the master node which runs the JobTracker. The JobTracker then assigns Map and Reduce tasks to other nodes in the cluster. These nodes run the TaskTracker daemons that starts the Map and Reduce tasks on the nodes and send the progress report to the JobTracker. So basically JobTracker is the MasterNode and TaskTrackers are the slaves.
Overview of MapReduce
Overview of MapReduce

Map Phase

One of the major advantages of using Hadoop is Data Locality. Hadoop always tries to take the computation to the data rather than to transfer data to the computation node. In other words a node is made the Mapper that is closest to the data (if possible the same node that has the data is made the mapper). This greatly reduces the network traffic and the time to transfer data from one node to another.
If you can see the figure above, multiple mappers run the Map tasks in parallel, each processing a portion if the input data. The Mappers receives the input interms of key-value pairs. It then emits a list of intermediate key and value pair (zero of more).
map(key, value) -> (intermediate_key, intermediate_value)
Map is essentially a function that takes a key-value pair as input and emits intermediate key-value pair. Let us concrete our understanding by taking an example of “word frequency” Mapper. Here our goal is to find the frequency of the words in a document. The key here is the offset of the word (where the word is found in the document) and the value is the word itself. When this is passed to the Mapper, it emits the word as key and 1 as the value.
For instance, let the document be “to be or not to be”.
So the Map function would look something like,
map(k, v) = (v, 1)
map(offest1, 'to') = ('to', 1)
map(offest2, 'be') = ('be', 1) 
map(offest3, 'or') = ('or', 1)
map(offest4, 'not') = ('not', 1)
map(offest5, 'to') = ('to', 1)
map(offest6, 'be') = ('be', 1)

Sort & Shuffle phase

After all the Map phases are complete, every pair has an intermediate key and value. Now all the values that have the same key are combined together and then they are sorted. This is the sort and shuffle phase of MapReduce. It is important to note that the output of the Map phase is stored on the local hard disk and not on the HDFS.
Continuing with our example, the output after Sort & Shuffle phase will be,
('to', [1, 1]), ('be', [1, 1]), ('or', [1]), ('not', [1])

Reduce Phase

After the Sort & Shuffle phase, the intermediate lists of key-value pair is fed to the Reducer, where it is subjected to the Reduce function. The Reducer emits zero/more final key value pair. Usually, a reducer will emit one key value pair for every intermediate key. The output of the Reducer is written on to the HDFS.
The Reduce function here will be to add all the intermediate values associated with a particular key. So the final output will be,
('to', 2), ('be', 2), ('or', 1)
As you see, the Reducer will give us the required output (which is the word frequency in the document).
To conclude, I reiterate that MapReduce is a great abstraction that allows programmers to focus only on the problem rather that all the messy details that need to be looked into while programming for large scale distributed development.


Its finally time to attempt our first MapReduce program. As with any programming language the first program you try is “Hello World”. We execute “Hello World” because it the easiest and we test whether the everything is perfectly installed and configured.
The easiest problem in MapReduce is the word count problem and is therefore called MapReduce’s “Hello World” by many people. So let us dive into it.
In the word count problem, we need to find the number of occurrences of each word in the entire document. I already explained how the map, shuffle & sort and reduce phases of MapReduce taking this example.
We will use eclipse provided with the Cloudera’s Demo VM to code MapReduce.
Step 1: Create a new project – Open eclipse. Add a new Java Project and name it as “wordCount”.
Step 2: Setup the Library – Right click on the newly created wordCount project and click on “Properties”. Select “Java Build Path” from the left panel. Click “Add external JARs..”.
  • Add all the JARs from /usr/lib/hadoop/client-0.20
  • Add “hadoop-annotations.jar”, “hadoop-auth.jar” and “hadoop-common.jar” from /usr/lib/hadoop
  • Add “hadoop-httpclient-3.1.jar” from /usr/lib/hadoop/lib
Step 3: Code the Mapper – To run MapReduce jobs we need three things: Map function, Reduce function & some code to run the job (also known as driver). For Map function we will write a Mapper class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.IOException;
 
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
 
 
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>
{  
    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException
    {
        String line = value.toString();
        
        //Split the line into words
        for(String word: line.split("\\W+"))
        {
            //Make sure that the word is legitimate
            if(word.length() > 0)
            {
                //Emit the word as you see it
                context.write(new Text(word), new IntWritable(1));
            }
        }
    }
}
As you see the WordCountMapper extends the Mapper Class. The class expects four parameters. The first two parameters are the input key-value pair type and the next two are the intermediate output key-value pair type. Also we override the default map implementation, because the default map function is an identity function.
In the program, we convert each line (value) to string and break it into words. And then for each word we send an intermediate key-value pair of the form (word, 1) to the next phase.
The intermediate key-value pairs now to the shuffle and sort phase where all the pairs with same key are grouped under one key and the values are put in the list. In our case, we get all the key-value pairs in (word, 1) form. So in shuffle & sort phase, we will get (word1, [1, 1, …]), (word2, [1, …]) and so on.
Another thing to note here is that Hadoop has its own basic data types such as Text (for String) and IntWritable (for int). Hadoop provides these data types for optimized serilization.
Step 4: Code the Reducer – The Reducer will take the intermediate key-value pair as input. And for each key-value pair the reduce funtion will be executed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.IOException;
 
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
 
 
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
 
    @Override
    public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException
    {
        //Initializing the word count to 0 for every key
        int count=0;
        
        for(IntWritable value: values)
        {
            //Adding the word count counter to count
            count += value.get();
        }
        
        //Finally write the word and its count
        context.write(key, new IntWritable(count));
    }
}
In the overridden reduce function, we add all the 1’s for every key(word). And for every word, we output the word itself and its count.
Step 5: Code the Driver – We need code to manage the MapReduce job. We call it the driver. The task of the driver is to configure the Job. Job defines the way in which MapReduce is run.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
 
 
public class WordCount {
    public static void main(String args[]) throws Exception
    {
        //Check the correctness of the entered command
        if(args.length != 2)
        {
            System.err.println("Inavlid Command!");
            System.err.println("Usage: WordCount <input path> <output path>");
            System.exit(0);
        }
        
        //Instantiate the job object for configuring your job
        Job job = new Job();
        
        //Specify the class that hadoop needs to look in the JAR file
        //This Jar file is then sent to all the machines in the cluster
        job.setJarByClass(WordCount.class);
        
        //Set a meaningful name to the job
        job.setJobName("Word Count");
        
        //Add the apth from where the file input is to be taken
        FileInputFormat.addInputPath(job, new Path(args[0]));
        
        //Set the path where the output must be stored
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        
        //Set the Mapper and the Reducer class
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        
        //Set the type of the key and value of Mapper and reducer
        /*
         * If the Mapper output type and Reducer output type are not the same then
         * also include setMapOutputKeyClass() and setMapOutputKeyValue()
         */
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        
        //Start the job and wait for it to finish. And exit the program based on
        //the success of the program
        System.exit(job.waitForCompletion(true)?0:1);
    }
}
As you see, we instantiate the Job object and specify the following:
  • Class which will be called to run the job
  • Input directory
  • Location where the output should get stored
  • Mapper and Reduce class
  • Type information of the output key-value pairs of Mapper and Reducer
On successful completion, we exit the code.
Step 6: Run the code – To run the MapReduce job, you must have the input files in the HDFS.
The command to the run the Hadoop Job is as follows:
$:~ hadoop jar <jar_filename.jar> <driver_classname> <input_path> <output_path>
You will get the output similar to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
hadoop jar wordCount.jar WordCount input/les_miserables wordCount
13/08/20 17:07:49 WARN mapred.JobClient: Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.
13/08/20 17:07:49 INFO input.FileInputFormat: Total input paths to process : 1
13/08/20 17:07:50 INFO mapred.JobClient: Running job: job_201308201538_0002
13/08/20 17:07:51 INFO mapred.JobClient:  map 0% reduce 0%
13/08/20 17:08:04 INFO mapred.JobClient:  map 100% reduce 0%
13/08/20 17:08:13 INFO mapred.JobClient:  map 100% reduce 100%
13/08/20 17:08:15 INFO mapred.JobClient: Job complete: job_201308201538_0002
13/08/20 17:08:15 INFO mapred.JobClient: Counters: 32
13/08/20 17:08:15 INFO mapred.JobClient:   File System Counters
13/08/20 17:08:15 INFO mapred.JobClient:     FILE: Number of bytes read=1284228
13/08/20 17:08:15 INFO mapred.JobClient:     FILE: Number of bytes written=2126389
13/08/20 17:08:15 INFO mapred.JobClient:     FILE: Number of read operations=0
13/08/20 17:08:15 INFO mapred.JobClient:     FILE: Number of large read operations=0
13/08/20 17:08:15 INFO mapred.JobClient:     FILE: Number of write operations=0
13/08/20 17:08:15 INFO mapred.JobClient:     HDFS: Number of bytes read=3322799
13/08/20 17:08:15 INFO mapred.JobClient:     HDFS: Number of bytes written=281178
13/08/20 17:08:15 INFO mapred.JobClient:     HDFS: Number of read operations=2
13/08/20 17:08:15 INFO mapred.JobClient:     HDFS: Number of large read operations=0
13/08/20 17:08:15 INFO mapred.JobClient:     HDFS: Number of write operations=1
13/08/20 17:08:15 INFO mapred.JobClient:   Job Counters
13/08/20 17:08:15 INFO mapred.JobClient:     Launched map tasks=1
13/08/20 17:08:15 INFO mapred.JobClient:     Launched reduce tasks=1
13/08/20 17:08:15 INFO mapred.JobClient:     Data-local map tasks=1
13/08/20 17:08:15 INFO mapred.JobClient:     Total time spent by all maps in occupied slots (ms)=14105
13/08/20 17:08:15 INFO mapred.JobClient:     Total time spent by all reduces in occupied slots (ms)=7600
13/08/20 17:08:15 INFO mapred.JobClient:     Total time spent by all maps waiting after reserving slots (ms)=0
13/08/20 17:08:15 INFO mapred.JobClient:     Total time spent by all reduces waiting after reserving slots (ms)=0
13/08/20 17:08:15 INFO mapred.JobClient:   Map-Reduce Framework
13/08/20 17:08:15 INFO mapred.JobClient:     Map input records=68116
13/08/20 17:08:15 INFO mapred.JobClient:     Map output records=577599
13/08/20 17:08:15 INFO mapred.JobClient:     Map output bytes=5422971
13/08/20 17:08:15 INFO mapred.JobClient:     Input split bytes=152
13/08/20 17:08:15 INFO mapred.JobClient:     Combine input records=0
13/08/20 17:08:15 INFO mapred.JobClient:     Combine output records=0
13/08/20 17:08:15 INFO mapred.JobClient:     Reduce input groups=26763
13/08/20 17:08:15 INFO mapred.JobClient:     Reduce shuffle bytes=524076
13/08/20 17:08:15 INFO mapred.JobClient:     Reduce input records=577599
13/08/20 17:08:15 INFO mapred.JobClient:     Reduce output records=26763
13/08/20 17:08:15 INFO mapred.JobClient:     Spilled Records=1732797
13/08/20 17:08:15 INFO mapred.JobClient:     CPU time spent (ms)=4840
13/08/20 17:08:15 INFO mapred.JobClient:     Physical memory (bytes) snapshot=289259520
13/08/20 17:08:15 INFO mapred.JobClient:     Virtual memory (bytes) snapshot=1410568192
13/08/20 17:08:15 INFO mapred.JobClient:     Total committed heap usage (bytes)=
Step 7: View the output – In the output directory you will see _logs, _SUCCESS and part-r-00000. The output gets stored in part-r-00000 file.
1
2
3
4
5
6
7
8
9
10
11
12
[cloudera@localhost ~]$ hadoop fs -cat wordCount/part-r-00000
000 7
1   76
10  6
100 4
105th   2
1098    1
10th    7
11  3
1140    1
1148    1
....
You can also copy the output to your local disk. To do so, execute the command:
1
[cloudera@localhost ~]$ hadoop fs -get wordCount ~/Desktop