Thursday, March 31, 2016

Twitter analysis with Pig and elephant-bird

Twitter analysis has been one of the popular blog on this site. Flume has been used to gather the data and then Hive has been used to do some basic analytics.  Performing the same with Pig had been pending for quite some time, so here it is.

The JSONLoader which comes with Pig can be used with Pig to load the JSON data from Flume. But, the problem with the JSONLoader is that that the entire scheme has to be specified as shown below. In the case of the Twitter data, the scheme becomes really huge and complex.

students = LOAD 'students.json'  USING JsonLoader('name:chararray, school:chararray, age:int');

So, I started using elephant-bird for processing the JSON date. With the JsonLoader from elephant-bird, there is no need to specify the schema. The JsonLoader simply returns a Pig map datatype and fields can be accessed using the JSON property name as shown below.
REGISTER '/home/bigdata/Installations/pig-0.15.0/lib/elephantbird/json-simple-1.1.1.jar'
REGISTER '/home/bigdata/Installations/pig-0.15.0/lib/elephantbird/elephant-bird-pig-4.3.jar'
REGISTER '/home/bigdata/Installations/pig-0.15.0/lib/elephantbird/elephant-bird-hadoop-compat-4.3.jar'

tweets = LOAD '/user/bigdata/tweetsJSON/' USING com.twitter.elephantbird.pig.load.JsonLoader('-nestedLoad') as (json:map[]);
user_details = FOREACH tweets GENERATE json#'user' As tweetUser;
user_followers = FOREACH user_details GENERATE (chararray)tweetUser#'screen_name' As screenName, (int)tweetUser#'followers_count' As followersCount;
user_followers_distinct = DISTINCT user_followers;
user_followers_sorted = order user_followers_distinct by followersCount desc;

DUMP user_followers_sorted;
The above program got converted into a DAG of 3 MapReduce programs and took 1 min 6 sec to complete, which is not really that efficient. It should be possible to implement the same using two MapReduce programs. I am not sure if there is any way to optimize the above Pig script. Any feedback, please let me know in the comments and I will try it out and update the blog.

The same data was proceed using Hive with the JSONSerDe provided by Cloudera as mentioned in the original blog. only a single MapReduce program was generated and it took 21 seconds to process the data, a drastic improvement over Pig using the elephant-bird library.

In the coming blogs. we will look a few other ways of processing the JSON data which is a very common format.

Tuesday, March 29, 2016

Analyzing the airline dataset with MR/Java

In the previous blog I introduced the Airline data set. I plan to get the results (total and delayed flights from different airports) using different Big Data softwares like Hadoop(MR), Hive, Pig, Spark, Impala etc and also with different formats of the data like Avro and Parquet. This will help the followers of the blog appreciate the different distributing computing software and models.

As usual there can be more than one of performing a particular task and a more efficient way. I have written the programs in a short span of time and will try to optimize them over time. Also, I will include as many comments as possible in the code, so as to make the code self explanatory.

Recently I have assembled a high configuration computer, which I like to call as a server :) with the below configurations. Ubuntu 14.04 64 bit has been installed on it. All the processing would be done on this server. It was fun looking for the right parts and assembling the computer. Initially I planned to buy an SSD instead of a Hard Disk, but the SSD were too expensive beyond the budget I planned.

Processor - AMD FX-6300 (FD6300WMHKBOX)
Mother Board - GIGABYTE GA-990XA-UD3
RAM - G.skill 2 * GB F3-12800CL10D-16GBXL
Hard Disk - Seagate 3.5 Inches Desktop 2 TB Hard Drive (ST2000DX001)

So, here is the MR program for calculating the total flight departures and the number of flight delays for the 20 years for each of the airport. Initially I wrote two MR programs, one for calculating the total flights and another for calculating the total delayed flights. This approach is not really efficient as the input data is parsed twice. So, I revamped the the program into one MR program.

Here is the MR Driver Code.
package AirlineDelaySinglePass;


import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;

public class AirlineDelayByStartTime {

 public static void main(String[] args) throws IOException {

  // Check if the number of parameters passed to program is 2
  if (args.length != 2) {
     .println("Usage: AirlineDelayByStartTime <input path> <output path>");

  // Create the JobConf instance and specify the job name
  JobConf conf = new JobConf(AirlineDelayByStartTime.class);
  conf.setJobName("Airline Delay");

  // First and second arguments are input and output folder
  FileInputFormat.addInputPath(conf, new Path(args[0]));
  FileOutputFormat.setOutputPath(conf, new Path(args[1]));

  // Specify the mapper and the reducer class

  // Specify the output key and value of the entire job

  // Specify the number of reducers tasks to run at any instant on a
  // machine, defaults to one

  // Trigger the mapreduce program

Here is the Mapper Code.
package AirlineDelaySinglePass;


import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class AirlineDelayByStartTimeMapper extends MapReduceBase implements
  Mapper<LongWritable, Text, Text, IntWritable> {

 public void map(LongWritable key, Text value,
   OutputCollector<Text, IntWritable> output, Reporter reporter)
   throws IOException {

  // Split the input line based on comma
  String[] pieces = value.toString().split(",");

  // Delayed 0 for ontime or NA, 1 for delayed
  int delayed = 0;

  // Get the origin which is the 17 field in the input line
  String origin = pieces[16];

  if (StringUtils.isNumeric(pieces[4])
    && StringUtils.isNumeric(pieces[5])) {

   // 5 DepTime actual departure time (local, hhmm)
   // 6 CRSDepTime scheduled departure time (local, hhmm)
   int actualDepTime = Integer.parseInt(pieces[4]);
   int scheduledDepTime = Integer.parseInt(pieces[5]);

   // if the flight has been delated
   if (actualDepTime > scheduledDepTime) {
    delayed = 1;


  // Send the Origin and the delayed status to the reducer for aggregation
  // ex., (ORD, 1)
  output.collect(new Text(origin), new IntWritable(delayed));


Here is the Reducer Code
package AirlineDelaySinglePass;

import java.util.Iterator;

import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;

public class AirlineDelayByStartTimeReducer extends MapReduceBase implements
  Reducer<Text, IntWritable, Text, IntWritable> {

 private IntWritable value = new IntWritable();

 public void reduce(Text key, Iterator<IntWritable> values,
   OutputCollector<Text, IntWritable> output, Reporter reporter)
   throws IOException {

  // initialize the total flights and delayed flights
  int totalFlights = 0;
  int delayedFlights = 0;

  Text newKey = new Text();

  while (values.hasNext()) {

   // Delayed 0 for ontime or NA, 1 for delayed
   int delayed =;

   // Increment the totalFlights by 1
   totalFlights = totalFlights + 1;

   // Calculate the number of delayed flights
   delayedFlights = delayedFlights + delayed;


  // Create the key ex., ORD\t123
  newKey.set(key.toString() + "\t" + delayedFlights);

  // Create the value ex., 150

  // Pass the key and the value to Hadoop to write it to the final output
  output.collect(newKey, value);

Here is the output of the MR program. This data can be joined with the Airport details (lat, long, name etc) to make it more readable and interesting. I could have written another MR program to do the join, but the size of the data set is so small that it doesn't make sense to use another MR program. We can simply use a spread sheet program or a database for joining of the data sets depending on the level of comfort.

Here is the time taken to run on my single node server. Note that the size of the airline data set is close to 12 GB and the processing is simple.

In the next blog I will post the code for doing the same with Spark.

Friday, March 25, 2016

Flight departure delays

The airline dataset is one of the interesting dataset which I came across recently. For 20 (1987 to 2008) years it has the actual/scheduled arrival/departure code, carrier code, flight number and a lot of other details.

From this information we can glean some interesting information like what is the best airline to travel, best time to travel. We can also mash with the weather data set to find out what sort of weather conditions cause flights to get delayed.

In this post I will publish what are the best and worst airport based on the number of delayed flights by departure. Chicago O'Hare International has the maximum number of departure delays (31,21,184). May be the total flights from O'Hare is huge, so I calculated the percentage (49.52%) of the number of departure delays (31,21,184) with the total number of flights (63,02,546) taking of from O'Hare. There are lot of factors influencing the flight delays, but delays are delays and O'Hare is one of the worst airport with respect to delays.

I have used MR programs for figuring out the same, which I would be publishing in the next blog after cleansing them up. For those interested to find out how the airport which is closet to them compares to other airports here is the data.