[hadoop][mapreduce][csv file]

Hadoop & Mapreduce Examples: Create First Program in Java

In this tutorial, you will learn to use Hadoop with MapReduce Examples. The input data used is SalesJan2009.csv. It contains Sales related information like Product name, price, payment mode, city, country of client etc. The goal is to Find out Number of Products Sold in Each Country.

In this tutorial, you will learn-

First Hadoop MapReduce Program

Now in this MapReduce tutorial, we will create our first Java MapReduce program:

 

Hadoop & Mapreduce Example

 

Data of SalesJan2009

Ensure you have Hadoop installed. Before you start with the actual process, change user to 'hduser' (id used while Hadoop configuration, you can switch to the userid used during your Hadoop programming config ).

 

su - hduser_

Hadoop & Mapreduce Examples: Create your First Program

 

Step 1)

Create a new directory with name MapReduceTutorial as shwon in the below MapReduce example

 

Primis Player Placeholder

 

 

 

sudo mkdir MapReduceTutorial

Hadoop & Mapreduce Examples: Create your First Program

 

Give permissions

 

sudo chmod -R 777 MapReduceTutorial

Hadoop & Mapreduce Examples: Create your First Program

 

SalesMapper.java 

 

package SalesCountry;

 

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.mapred.*;

 

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

private final static IntWritable one = new IntWritable(1);

 

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

 

String valueString = value.toString();

String[] SingleCountryData = valueString.split(",");

output.collect(new Text(SingleCountryData[7]), one);

}

}

SalesCountryReducer.java 

 

package SalesCountry;

 

import java.io.IOException;

import java.util.*;

 

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapred.*;

 

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

 

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

Text key = t_key;

int frequencyForCountry = 0;

while (values.hasNext()) {

// replace type of value with the actual type of our value

IntWritable value = (IntWritable) values.next();

frequencyForCountry += value.get();

 

}

output.collect(key, new IntWritable(frequencyForCountry));

}

}

 

SalesCountryDriver.java 

 

package SalesCountry;

 

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.*;

import org.apache.hadoop.mapred.*;

 

public class SalesCountryDriver {

    public static void main(String[] args) {

        JobClient my_client = new JobClient();

        // Create a configuration object for the job

        JobConf job_conf = new JobConf(SalesCountryDriver.class);

 

        // Set a name of the Job

        job_conf.setJobName("SalePerCountry");

 

        // Specify data type of output key and value

        job_conf.setOutputKeyClass(Text.class);

        job_conf.setOutputValueClass(IntWritable.class);

 

        // Specify names of Mapper and Reducer Class

        job_conf.setMapperClass(SalesCountry.SalesMapper.class);

        job_conf.setReducerClass(SalesCountry.SalesCountryReducer.class);

 

        // Specify formats of the data type of Input and output

        job_conf.setInputFormat(TextInputFormat.class);

        job_conf.setOutputFormat(TextOutputFormat.class);

 

        // Set input and output directories using command line arguments, 

        //arg[0] = name of input directory on HDFS, and arg[1] =  name of output directory to be created to store the output file.

 

        FileInputFormat.setInputPaths(job_conf, new Path(args[0]));

        FileOutputFormat.setOutputPath(job_conf, new Path(args[1]));

 

        my_client.setConf(job_conf);

        try {

            // Run the job 

            JobClient.runJob(job_conf);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Download Files Here

 

Hadoop & Mapreduce Examples: Create your First Program

 

Check the file permissions of all these files

 

Hadoop & Mapreduce Examples: Create your First Program

 

and if 'read' permissions are missing then grant the same-

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

Hadoop & Mapreduce Examples: Create your First Program

 

Step 2)

Export classpath as shown in the below Hadoop example

 

export CLASSPATH="$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.2.0.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-common-2.2.0.jar:$HADOOP_HOME/share/hadoop/common/hadoop-common-2.2.0.jar:~/MapReduceTutorial/SalesCountry/*:$HADOOP_HOME/lib/*"

Hadoop & Mapreduce Examples: Create your First Program

 

Step 3)

Compile Java files (these files are present in directory Final-MapReduceHandsOn). Its class files will be put in the package directory

 

javac -d . SalesMapper.java SalesCountryReducer.java SalesCountryDriver.java

Hadoop & Mapreduce Examples: Create your First Program

 

This warning can be safely ignored.

 

This compilation will create a directory in a current directory named with package name specified in the java source file (i.e. SalesCountry in our case) and put all compiled class files in it.

 

Hadoop & Mapreduce Examples: Create your First Program

 

Step 4)

Create a new file Manifest.txt

 

sudo gedit Manifest.txt

add following lines to it,

 

Main-Class: SalesCountry.SalesCountryDriver

Hadoop & Mapreduce Examples: Create your First Program

 

SalesCountry.SalesCountryDriver is the name of main class. Please note that you have to hit enter key at end of this line.

 

Step 5)

Create a Jar file

 

jar cfm ProductSalePerCountry.jar Manifest.txt SalesCountry/*.class

Hadoop & Mapreduce Examples: Create your First Program

 

Check that the jar file is created

 

Hadoop & Mapreduce Examples: Create your First Program

 

Step 6)

Start Hadoop

$HADOOP_HOME/sbin/start-dfs.sh
$HADOOP_HOME/sbin/start-yarn.sh

Step 7)

Copy the File SalesJan2009.csv into ~/inputMapReduce

Now Use below command to copy ~/inputMapReduce to HDFS.

$HADOOP_HOME/bin/hdfs dfs -copyFromLocal ~/inputMapReduce /

Hadoop & Mapreduce Examples: Create your First Program

We can safely ignore this warning.

Verify whether a file is actually copied or not.

$HADOOP_HOME/bin/hdfs dfs -ls /inputMapReduce

Hadoop & Mapreduce Examples: Create your First Program

Step 8)

Run MapReduce job

$HADOOP_HOME/bin/hadoop jar ProductSalePerCountry.jar /inputMapReduce /mapreduce_output_sales

Hadoop & Mapreduce Examples: Create your First Program

This will create an output directory named mapreduce_output_sales on HDFS. Contents of this directory will be a file containing product sales per country.

Step 9)

The result can be seen through command interface as,

$HADOOP_HOME/bin/hdfs dfs -cat /mapreduce_output_sales/part-00000

Hadoop & Mapreduce Examples: Create your First Program

Results can also be seen via a web interface as-

Open r in a web browser.

Hadoop & Mapreduce Examples: Create your First Program

Now select 'Browse the filesystem' and navigate to /mapreduce_output_sales

Hadoop & Mapreduce Examples: Create your First Program

Open part-r-00000

Hadoop & Mapreduce Examples: Create your First Program

 

Explanation of SalesMapper Class

In this section, we will understand the implementation of SalesMapper class.

1. We begin by specifying a name of package for our class. SalesCountry is a name of our package. Please note that output of compilation, SalesMapper.class will go into a directory named by this package name: SalesCountry.

Followed by this, we import library packages.

Below snapshot shows an implementation of SalesMapper class-

Hadoop & Mapreduce Examples: Create your First Program

Sample Code Explanation:

1. SalesMapper Class Definition-

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

Every mapper class must be extended from MapReduceBase class and it must implement Mapper interface.

2. Defining 'map' function-

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

The main part of Mapper class is a 'map()' method which accepts four arguments.

At every call to 'map()' method, a key-value pair ('key' and 'value' in this code) is passed.

'map()' method begins by splitting input text which is received as an argument. It uses the tokenizer to split these lines into words.        

String valueString = value.toString();
String[] SingleCountryData = valueString.split(",");

Here, ',' is used as a delimiter.

After this, a pair is formed using a record at 7th index of array 'SingleCountryData' and a value '1'.

        output.collect(new Text(SingleCountryData[7]), one);

We are choosing record at 7th index because we need Country data and it is located at 7th index in array 'SingleCountryData'.

Please note that our input data is in the below format (where Country is at 7th index, with 0 as a starting index)-

Transaction_date,Product,Price,Payment_Type,Name,City,State,Country,Account_Created,Last_Login,Latitude,Longitude

An output of mapper is again a key-value pair which is outputted using 'collect()' method of 'OutputCollector'.

Explanation of SalesCountryReducer Class

In this section, we will understand the implementation of SalesCountryReducer class.

1. We begin by specifying a name of the package for our class. SalesCountry is a name of out package. Please note that output of compilation, SalesCountryReducer.class will go into a directory named by this package name: SalesCountry.

Followed by this, we import library packages.

Below snapshot shows an implementation of SalesCountryReducer class-

Hadoop & Mapreduce Examples: Create your First Program

Code Explanation:

1. SalesCountryReducer Class Definition-

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

Here, the first two data types, 'Text' and 'IntWritable' are data type of input key-value to the reducer.

Output of mapper is in the form of <CountryName1, 1>, <CountryName2, 1>. This output of mapper becomes input to the reducer. So, to align with its data type, Text and IntWritable are used as data type here.

The last two data types, 'Text' and 'IntWritable' are data type of output generated by reducer in the form of key-value pair.

Every reducer class must be extended from MapReduceBase class and it must implement Reducer interface.

2. Defining 'reduce' function-

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

An input to the reduce() method is a key with a list of multiple values.

For example, in our case, it will be-

<United Arab Emirates, 1>, <United Arab Emirates, 1>, <United Arab Emirates, 1>,<United Arab Emirates, 1>, <United Arab Emirates, 1>, <United Arab Emirates, 1>.

This is given to reducer as <United Arab Emirates, {1,1,1,1,1,1}>

So, to accept arguments of this form, first two data types are used, viz., Text and Iterator<IntWritable>Text is a data type of key and Iterator<IntWritable> is a data type for list of values for that key.

The next argument is of type OutputCollector<Text,IntWritable> which collects the output of reducer phase.

reduce() method begins by copying key value and initializing frequency count to 0.

        Text key = t_key;
        int frequencyForCountry = 0;

Then, using 'while' loop, we iterate through the list of values associated with the key and calculate the final frequency by summing up all the values.

       

 while (values.hasNext()) {
            // replace type of value with the actual type of our value
            IntWritable value = (IntWritable) values.next();
            frequencyForCountry += value.get();
            
        }

Now, we push the result to the output collector in the form of key and obtained frequency count.

Below code does this-

output.collect(key, new IntWritable(frequencyForCountry));

Explanation of SalesCountryDriver Class

In this section, we will understand the implementation of SalesCountryDriver class

1. We begin by specifying a name of package for our class. SalesCountry is a name of out package. Please note that output of compilation, SalesCountryDriver.class will go into directory named by this package name: SalesCountry.

Here is a line specifying package name followed by code to import library packages.

Hadoop & Mapreduce Examples: Create your First Program

2. Define a driver class which will create a new client job, configuration object and advertise Mapper and Reducer classes.

The driver class is responsible for setting our MapReduce job to run in Hadoop. In this class, we specify job name, data type of input/output and names of mapper and reducer classes.Hadoop & Mapreduce Examples: Create your First Program

3. In below code snippet, we set input and output directories which are used to consume input dataset and produce output, respectively.

arg[0] and arg[1] are the command-line arguments passed with a command given in MapReduce hands-on, i.e.,

$HADOOP_HOME/bin/hadoop jar ProductSalePerCountry.jar /inputMapReduce /mapreduce_output_sales

Hadoop & Mapreduce Examples: Create your First Program

4. Trigger our job

Below code start execution of MapReduce job-

try {
    // Run the job 
    JobClient.runJob(job_conf);
} catch (Exception e) {
    e.printStackTrace();
}

 [출처] https://www.guru99.com/create-your-first-hadoop-program.html

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86135
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78636
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95362
904 [spark] Spark 튜닝하기 file 졸리운_곰 2021.03.06 1291
903 [spark] PySpark와 pandas 데이터 프레임 간의 변환 최적화 file 졸리운_곰 2021.03.04 1673
902 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 779
901 [hadoop] Python으로 Hive 연결하기 졸리운_곰 2021.03.04 1502
900 Data Engineering - Apache Spark Dataframe 10분만에 훑어보기 졸리운_곰 2021.03.04 1867
899 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1191
898 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1031
897 [hadoop][java][MapReduce] 맵리듀스 원리와 그 과정 졸리운_곰 2021.02.28 1652
896 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1588
895 [spark] pyspark 설치하기 (windows 10) file 졸리운_곰 2021.02.26 1661
894 [hadoop][mapreduce][csv file] [Reference] : Hadoop MapReduce Join & Counter with Example file 졸리운_곰 2021.02.23 1534
» [hadoop][mapreduce][csv file] Hadoop & Mapreduce Examples: Create First Program in Java file 졸리운_곰 2021.02.23 1855
892 [mongodb , 몽고디비] How to Use MongoDB Comparison Query Operators in Java 졸리운_곰 2021.02.19 1508
891 Apache Spark란? 졸리운_곰 2021.02.19 1508
890 [apache spark] [Spark Programming]1. Apache Spark 개요 및 설치 file 졸리운_곰 2021.02.19 19627
889 [Oracle, 오라클 데이터베이스] java.sql.SQLException: ORA-00911: 문자가 부적합합니다. file 졸리운_곰 2021.02.19 1063
888 [mongodb, 몽고디비] How do you query for “is not null” in Mongo? 졸리운_곰 2021.02.19 1268
887 스파크 Spark - 윈도우10에서 빅데이터 실습 세팅 및 시작하기 file 졸리운_곰 2021.02.17 1313
886 스파크(Spark) 3.0.0 설치 on Windows 10 file 졸리운_곰 2021.02.17 1598
885 [oracle, 오라클] 오라클 MERGE INTO 문으로 있으면 UPDATE 없으면 INSERT 한번에 수행하기 졸리운_곰 2021.02.16 1044
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED