본문 바로가기

[Data Engineering]/[Hadoop]

[Hadoop/기록] 7. Hadoop map-reduce (WordCount / Java)

728x90
 

Apache Hadoop 3.3.1 – MapReduce Tutorial

 

[map-reduce 예제 실행과정]

1. Hadoop home을 기준으로, 데이터를 넣을 input 폴더를 생성하고, 폴더안에 리눅스 시스템에 있던 아무 텍스트파일이나 집어넣는다.  예제는 wordcount이므로, 나는 NOTICE.txt 파일을 사용했다. 

 

2. 하둡 폴더에는 share/hadoop/mapreduce 폴더로 들어가면 다음과 같이 다양한 예제파일들, 정확히는 Jar 실행파일 들을 확인할 수 있다. 그중에서 hadoop-mapreduce-examples-3.2.2 파일을 실행시켜보자. 커맨드는 다음과 같다. 

 

그러면 내부에 Source-Code는 어떻게 되어있을까?  튜토리얼에서 가져온 해당 jar파일의 소스코드는 다음과 같다.

 

Apache Hadoop 3.3.1 – MapReduce Tutorial

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

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

    // mapper 부분
    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
        // 각 라인을 읽어들여서 토큰화 한다.
      StringTokenizer itr = new StringTokenizer(value.toString());
      // 출력 객체에 해당하는 context에 각각의 토큰-value 값을 토큰 - 1(숫자) 값으로 매핑해서 집어넣는다.
      // 중복되는 토큰이 있으면 다른 토큰 취급하여 새롭게 집어넣는다. 
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  // reducer 부분
  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
        // 정렬이 끝난 상태에서의 리듀스 작업을 진행한다. 
        // 각각의 키에 대한 value값들이 하나로 합쳐지고 쓰여진다.
      int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);
    }
  }

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class); // mapper 와 reducer 사이에 combiner 함수가 실행된다.
                                               // combiner 함수는 중복된 키들의 value 값을 하나로 모아준다.
                                               // 이후에는 셔플, 파티셔닝, 정렬과정을 거쳐 reducer로 넘어간다.
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

 

 

3. 성공적으로 map-reduce 작업이 끝나고 나면 다음과 같이 output폴더에 (기존에 없었다면 새로 생성된다) 결과값이 들어있는 것을 볼 수 있다.  이어서 하둡 cat 명령어로 결과값을 찍어보면 다음과 같이 word count가 잘 이루어진 것을 볼 수 있다. 

 

[브라우저로 확인해보기]

1. 8088포트에서 클러스터 작업상태, 완료여부를 확인해 볼 수 있다.

 

2. 9870포트에서는 데이터 노드의 상태를 확인할 수 있다. -> utilities -> browse file system에 들어간다.

 

3. 브라우져에서 하둡과 동일하게 /user/lsy1206/output 폴더에 들어가면 결과파일에 대한 Block ID, Pool, size와 함께 파일내용도 일부 확인할 수 있다.

728x90