Bda Lab Manual - Cse 8 Sem - Compl
Bda Lab Manual - Cse 8 Sem - Compl
ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT
Bachelor of Technology
A Practical File on
Subject Code-LC-CSE-421G
ROLL NO.:
St. Andrews Institute of Technology &
Management, Gurugram
Department of……………………………
2 Develop a MapReduce CO 1
program to calculate the
frequency of a given
word in a given file.
3 Develop a MapReduce CO 4
program to find the
maximum temperature
in each year.
4 Develop a MapReduce CO 4
program to find the
grades of students.
5 Develop a MapReduce CO 2
program to implement
Matrix Multiplication.
6 Develop a MapReduce CO 2
to find the maximum
electrical consumption
in each year given
electrical consumption
for each month in each
year.
7 Develop a MapReduce CO 2
to analyze weather data
set and print whether
the day is shinny or cool
day.
8 Develop a program to CO 4
calculate the maximum
recorded temperature by
yearwise for the
weather dataset in Pig
Latin
9 Develop a program to CO 2
implement Pig Latin
Modes, Programs.
10 Develop a Java CO 4
application to find the
maximum temperature
using Spark.
Average Marks
(Faculty Sign.)
PROGRAM NO - 1
Install Apache Hadoop
Hadoop is a Java-based programming framework that supports the processing and storage of
extremely large datasets on a cluster of inexpensive machines. It was the first major open source
project in the big data playing field and is sponsored by the Apache Software Foundation. Hadoop-
2.7.3 is comprised of four main layers:
Hadoop Common is the collection of utilities and libraries that support other Hadoop modules.
HDFS, which stands for Hadoop Distributed File System, is responsible for persisting data to disk.
YARN, short for Yet Another Resource Negotiator, is the "operating system" for HDFS.
MapReduce is the original processing model for Hadoop clusters. It distributes work within the
cluster or map, then organizes and reduces the results from the nodes into a response to a query.
Many other processing models are available for the 2.x version of Hadoop.
Hadoop clusters are relatively complex to set up, so the project includes a stand-alone mode which
is suitable for learning about Hadoop, performing simple operations, and debugging.
Procedure:
we'll install Hadoop in stand-alone mode and run one of the example example MapReduce programs it
includes to verify the installation.
Prerequisites:
If Apache Hadoop 3.3.6 is not already installed then follow the post Build, Install, Configure
and Run Apache Hadoop 3.3.6 in MAC OS.
2. Start HDFS (Namenode and Datanode) and YARN (Resource Manager and Node Manager)
Result: We've installed Hadoop in stand-alone mode and verified it by running an example
program it provided.
PROGRAM 2
Develop a MapReduce program to calculate the frequency of a given word in a given
file.
AIM: To Develop a MapReduce program to calculate the frequency of a given word in agiven file
Map Function – It takes a set of data and converts it into another set of data, where individual
elements are broken down into tuples (Key-Value pair).
Input
Set of data
Bus, Car, bus, car, train, car, bus, car, train, bus, TRAIN,BUS, buS, caR, CAR, car, BUS, TRAIN
Output
Convert into another set of data
(Key,Value)
(Bus,1), (Car,1), (bus,1), (car,1), (train,1), (car,1), (bus,1), (car,1), (train,1), (bus,1),
(TRAIN,1),(BUS,1), (buS,1), (caR,1), (CAR,1), (car,1), (BUS,1), (TRAIN,1)
Reduce Function – Takes the output from Map as an input and combines those data tuples into
a smaller set of tuples.
Example – (Reduce function in Word Count)
Input Set of Tuples
(output of Map function)
(Bus,1), (Car,1), (bus,1), (car,1), (train,1), (car,1), (bus,1), (car,1), (train,1), (bus,1),
(TRAIN,1),(BUS,1),
Make sure that Hadoop is installed on your system with java idk
Steps to follow
Step 1. Open Eclipse> File > New > Java Project > (Name it – MRProgramsDemo)
> Finish
Step 2. Right Click > New > Package ( Name it - PackageDemo) > Finish
Step 3. Right Click on Package > New > Class (Name it - WordCount) Step 4.
Add Following Reference Libraries –
AIM: To Develop a MapReduce program to find the maximum temperature in each year.
Description: MapReduce is a programming model designed for processing large volumes of data
in parallel by dividing the work into a set of independent tasks.Our previous traversal has given an
introduction about MapReduce This traversal explains how to design a MapReduce program. The
aim of the program is to find the Maximum temperature recorded for each year of NCDC data.
The input for our program is weather data files for each year This weather data is collected by
National Climatic Data Center – NCDC from weather sensors at all over the world. You can find
weather data for each year from ftp://ftp.ncdc.noaa.gov/pub/data/noaa/.All files are zipped by year
and the weather station. For each year, there are multiple files for different weather stations. Here
is an example for 1990 (ftp://ftp.ncdc.noaa.gov/pub/data/noaa/1901/).
• 010080-99999-1990.gz • 010100-99999-1990.gz
• 010150-99999-1990.gz
• …………………………………
MapReduce is based on set of key value pairs. So first we have to decide on the types for the
key/value pairs for the input.
Map Phase: The input for Map phase is set of weather data files as shown in snap shot. The types
of input key value pairs are LongWritable and Text and the types of output key value pairs are
Text and IntWritable. Each Map task extracts the temperature data from the given year file. The
output of the map phase is set of key value pairs. Set of keys are the years. Values are the
temperature of each year.
Reduce Phase: Reduce phase takes all the values associated with a particular key. That is all the
temperature values belong to a particular year is fed to a same reducer. Then each reducer finds
the highest recorded temperature for each year. The types of output key value pairs in Map phase
is same for the types of input key value pairs in reduce phase (Text and IntWritable). The types of
output key value pairs in reduce phase is too Text and IntWritable. So, in this example we write
three java classes:
• HighestMapper.java
• HighestReducer.java
• HighestDriver.java
Program: HighestMapper.java
HighestReducer.java
import java.io.IOException; import
java.util.Iterator; import
org.apache.hadoop.io.*; import
org.apache.hadoop.mapred.*;
public class HighestReducer extends MapReduceBase implements Reducer<Text, IntWritable,
Text, IntWritable>
{
public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable>
output, Reporter reporter) throws IOException
{
int max_temp = 0;
;
while (values.hasNext())
{
int current=values.next().get();
if ( max_temp < current)
max_temp = current;
}
output.collect(key, new IntWritable(max_temp/10));
}
HighestDriver.java
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class HighestDriver extends Configured implements Tool{ public
int run(String[] args) throws Exception
{
JobConf conf = new JobConf(getConf(), HighestDriver.class);
conf.setJobName("HighestDriver");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(HighestMapper.class);
conf.setReducerClass(HighestReducer.class);
Path inp = new Path(args[0]);
Path out = new Path(args[1]);
FileInputFormat.addInputPath(conf, inp);
FileOutputFormat.setOutputPath(conf, out);
JobClient.runJob(conf);
return 0; }
public static void main(String[] args) throws Exception
{
int res = ToolRunner.run(new Configuration(), new HighestDriver(),args);
System.exit(res);
}
}
2005 90
2006 100
2007 100
PROGRAM 4
Develop a MapReduce program to find the grades of students.
18
System.out.print("C");
} else
{
System.out.print("D");
}
}
}
Output:
a. for each element mij of M do produce (key,value) pairs as ((i,k), (M,j,mij), for
k=1,2,3,.. upto the number of columns of N
b. for each element njk of N do produce (key,value) pairs as ((i,k),(N,j,Njk), for i
= 1,2,3,.. Upto the number of rows of M.
c. return Set of (key,value) pairs that each key (i,k), has list with values (M,j,mij)
and (N, j,njk) for all possible values of j.
Algorithm for Reduce Function.
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path; import
org.apache.hadoop.io.DoubleWritable; import
org.apache.hadoop.io.IntWritable; import
org.apache.hadoop.io.Text; import
org.apache.hadoop.io.Writable; import
org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.*;
import
org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.ReflectionUtils;
@Override
public void map(Object key, Text value, Context context) throws
IOException, InterruptedException {
String readLine = value.toString();
String[] stringTokens = readLine.split(",");
if (tempElement.tag == 0) {
M.add(tempElement);
} else if(tempElement.tag == 1) {
N.add(tempElement);
}
}
for(int i=0;i<M.size();i++) { for(int
j=0;j<N.size();j++) {
job2.setMapperClass(MapMxN.class);
job2.setReducerClass(ReduceMxN.class);
job2.setMapOutputKeyClass(Pair.class);
job2.setMapOutputValueClass(DoubleWritable.class);
job2.setOutputKeyClass(Pair.class);
job2.setOutputValueClass(DoubleWritable.class);
job2.setInputFormatClass(TextInputFormat.class);
job2.setOutputFormatClass(TextOutputFormat.class);
#!/bin/bash
rm -rf multiply.jar classes
module load
hadoop/3.3.6
echo "end"
stop-yarn.sh
stop-dfs.sh myhadoop-cleanup.sh
27
Data set:M
M,1,2,10
M,3,2,9
M,6,3,9
Data set:N
N,2,2,9
N,6,7,8
N,8,8,10
Command for execution: hadoop com.sun.tools.javac.Main *.java jar cf mm.jar *.class hadoop fs -
mkdir -p /user/hadoop/mm/input/ hadoop fs -put -f M /user/hadoop/mm/input hadoop fs -put -f N/
/user/hadoop/mm/input hadoop fs -ls /user/hadoop/mm/input/ hadoop fs -cat /user/hadoop/mm/input/M
hadoop fs -cat /user/hadoop/mm/input/N hadoop jar mm.jar /user/hadoop/mm/input
/user/hadoop/mm/output hadoop fs -cat /user/hadoop/mm/output/part-r-0000
Output:
999,970,493.0 999,971,586.0
999,972,763.0
999,973,717.0
999,974,236.0
999,975,532.0
PROGRAM 6
Develop a MapReduce to find the maximum electrical consumption in each year
given electrical consumption for each month in each year.
AIM: To Develop a MapReduce to find the maximum electrical consumption in each year
given electrical consumption for each month in each year.
Given below is the data regarding the electrical consumption of an organization. It contains the
monthly electrical consumption and the annual average for various years.
If the above data is given as input, we have to write applications to process it and produce results
such as finding the year of maximum usage, year of minimum usage, and so on. This is a walkover
for the programmers with finite number of records. They will simply write the logic to produce
the required output, and pass the data to the application written.
But, think of the data representing the electrical consumption of all the largescale industries of a
particular state, since its formation.
When we write applications to process such bulk data,
• They will take a lot of time to execute.
• There will be a heavy network traffic when we move data from source to network server and
so on.
To solve these problems, we have the MapReduce framework
Input Data
The above data is saved as sample.txt and given as input. The input file looks as shown below.
1979 23 23 2 43 24 25 26 26 26 26 25 26 25
1980 26 27 28 28 28 30 31 31 31 30 30 30 29
1981 31 32 32 32 33 34 35 36 36 34 34 34 34
1984 39 38 39 39 39 41 42 43 40 39 38 38 40
1985 38 39 39 39 39 41 41 41 00 40 39 39 45
Source code:
import java.util.*; import
java.io.IOException; import
java.io.IOException; import
org.apache.hadoop.fs.Path; import
org.apache.hadoop.conf.*; import
org.apache.hadoop.io.*; import
org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class ProcessUnits
{
//Mapper class
public static class E_EMapper extends MapReduceBase implements
Mapper<LongWritable ,/*Input key Type */ Text, /*Input value Type*/
Text, /*Output key Type*/ IntWritable> /*Output value Type*/
{
//Map function
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException
{
String line = value.toString(); String lasttoken = null;
StringTokenizer s = new StringTokenizer(line,"\t");
String year = s.nextToken();
while(s.hasMoreTokens())
{
lasttoken=s.nextToken();
}
int avgprice = Integer.parseInt(lasttoken);
output.collect(new Text(year), new IntWritable(avgprice));
}
}
//Reducer class
public static class E_EReduce extends MapReduceBase implements
Reducer< Text, IntWritable, Text, IntWritable >
{
//Reduce function
public void reduce( Text key, Iterator <IntWritable> values, OutputCollector<Text,
IntWritable> output, Reporter reporter) throws
IOException
{
int maxavg=30; int
val=Integer.MIN_VALUE;
while (values.hasNext())
{
if((val=values.next().get())>maxavg)
{
output.collect(key, new IntWritable(val));
}
}
}
}
//Main function
public static void main(String args[])throws Exception
{
JobConf conf = new JobConf(ProcessUnits.class);
conf.setJobName("max_eletricityunits");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(E_EMapper.class);
conf.setCombinerClass(E_EReduce.class);
conf.setReducerClass(E_EReduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
Output:
Kolkata,56
Jaipur,45
Delhi,43
Mumbai,34
Goa,45
Kolkata,35
Jaipur,34
Delhi,32
Output:
Kolkata 56
Jaipur 45
Delhi 43
Mumbai 34
PROGRAM 7
Develop a MapReduce to analyze weather data set and print whether the day is
shinny or cool day.
* Now leaving the first five tokens,it takes 6th token is taken as temp_max and
* 7th token is taken as temp_min. Now temp_max > 35 and temp_min < 10 are passed to the
reducer.
*/ @Override public void map(LongWritable arg0, Text Value, Context 2 context)
throws IOException, InterruptedException {
//Converting the record (single line) to String and storing it in a String variable line
String line = Value.toString();
//Checking if the line is not empty if
(!(line.length() == 0)) {
//date
String date = line.substring(6, 14);
//maximum temperature float temp_Max =
Float parseFloat(line.substring(39, 45).trim());
//minimum temperature float
temp_Min = Float
parseFloat(line.substring(47, 53).trim());
//if maximum temperature is greater than 35 , its a hot day
Text(String.valueOf(temp_Min)));
}
}
}
}
//Reducer
*MaxTemperatureReducer class is static and extends Reducer abstract having four hadoop
Text> { public void reduce (Text Key, Iterator<Text> Values, Context context) throws
IOException,
Interrupted Exception {
String temperature = Values.next().toString();
context.write(Key, new Text(temperature));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = new Job(conf, "weather example");
job.setJarByClass(MyMaxMin.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class); job.setMapperClass(MaxTemperatureMapper.class);
job.setReducerClass(MaxTemperatureReducer.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class); Path
OutputPath.getFileSystem(conf).delete(OutputPath);
System.exit(job.waitForCompletion(true) ? 0 : 1);
Import the project in eclipse IDE in the same way it was told in earlier guide and
change the jar paths with the jar files present in the lib directory of this project.
When the project is not having any error, we will export it as a jar file, same as we
did in wordcount mapreduce guide. Right Click on the Project file and click on
Export. Select jar file.
AIM: To Develop a program to calculate the maximum recorded temperature by year wise for the
weather dataset in Pig Latin
Description:
The National Climatic Data Center (NCDC) is the world's largest active archive of weather data. I
downloaded the NCDC data for year 1930 and loaded it in HDFS system. I implemented MapReduce
program and Pig, Hove scripts to findd the Min, Max, avg temparature for diffrent stations.
Copy the output file to local hdfs dfs -copyToLocal /home/student3/Project_output111/part-r- 00000
PIG Script
Hive Script
CREATE TABLE w_hd9467(year STRING, temperature INT) ROW FORMAT DELIMITED FIELDS
TERMINATED BY ‘\t’;
Query to find average temperature SELECT year, AVG(temperature) FROM w_hd9467 GROUP BY
year;
MaxTemperature.java
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;
job.setMapperClass(MaxTemperatureMapper.class);
job.setReducerClass(MaxTemperatureReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
System.exit(job.waitForCompletion(true) ? 0 : 1); }
}
MaxTemperatureMapper.java
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;
@Override
public void map(LongWritable key, Text value, Context context) throws IOException,
InterruptedException {
String line = value.toString(); String year = line.substring(15, 19); int
airTemperature; if (line.charAt(87) == '+') { // parseInt doesn't like
leading plus signs
airTemperature = Integer.parseInt(line.substring(88, 92));
} else { airTemperature =
Integer.parseInt(line.substring(87, 92));
}
String quality = line.substring(92, 93);
if (airTemperature != MISSING && quality.matches("[01459]")) {
context.write(new Text(year), new IntWritable(airTemperature)); }
}
}
MaxTemperatureReducer.java
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer; public
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context
context)
throws IOException, InterruptedException {
Output:
1921 -
222
1921 -
144
1921 -
122
1921 -
139
1921 -
122
1921 -89
1921 -72
1921 -61
1921 -56
1921 -44
1921 -61
1921 -72
1921 -67
1921 -78
1921 -78
1921 -
133
1921 -
189
1921 -
250
1921 -
200
1921 -
150
1921 -
156
1921 -
144
1921 -
133
1921 -
139
1921 -
161
1921 -
233
1921 -
139
1921 -
94
1921 -
89
1921 -
122
1921 -
100
1921 -
100
1921 -
106
1921 -
117
1921 -
144
1921 -
128
1921 -
139
1921 -
106
1921 -
100
1921 -
94
1921 -
83
1921 -
83
1921 -
106
1921 -
150
1921 -
200
1921 -
178
1921 -
72
1921 -
156
PROGRAM 9
OBJECTIVE:
PROGRAM LOGIC:
Run the Pig Latin Scripts to find a max temp for each and every year
OUTPUT:
(1950,0,1)
(1950,22,1)
(1950,-11,1)
(1949,111,1)
(1949,78,1)
PROGRAM 10
Develop a Java application to find the maximum temperature using Spark.
AIM: To Develop a Java application to find the maximum temperature using Spark.
Sourcecode: