유령 데이터 변환 여정

HadoopBeginner
지금 연습하기

소개

이 랩에서는 Hadoop MapReduce 에서 데이터 처리를 효과적으로 수행하기 위해 출력 및 입력 형식을 사용자 정의하는 방법을 배우게 됩니다. Ghost Tutor 의 안내에 따라 다양한 유형의 데이터를 처리하고 Hadoop 생태계의 모든 잠재력을 활용하는 기술을 습득하게 됩니다. 초자연적인 영역에서 컴퓨팅 기술을 마스터하기 위한 흥미진진한 여정을 시작할 준비를 하세요!

매퍼 (Mapper) 및 리듀서 (Reducer) 작성

이 단계에서는 Hadoop MapReduce 의 핵심으로 들어가 자체 Mapper 및 Reducer 클래스를 생성합니다.

데이터 파일 탐색

먼저, su - hadoop 명령을 사용하여 신원을 전환합니다. 데이터 파일 data.txt는 HDFS 의 /user/hadoop/input 디렉토리에 저장되어 있으며, 이는 일부 사람들의 대화 내용을 저장합니다. 다음 명령을 사용하여 내용을 확인합니다.

hdfs dfs -cat /user/hadoop/input/data.txt

사용자 정의 Mapper

다음으로, Mapper를 확장하는 WordCountMapper라는 사용자 정의 Mapper 클래스를 생성합니다. 이 Mapper 는 입력 데이터를 처리하고 키 - 값 쌍을 내보냅니다. 처리되는 데이터는 사람들의 이름이 아닌 각 대화 줄의 내용임을 유의하십시오. /home/hadoop/ 아래의 WordCountMapper.java에서 map 메서드를 보완하려면 다음 예제를 참조하십시오.

@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    // Convert the Text object to a String
    String line = value.toString();
    // Tokenize the string using StringTokenizer
    StringTokenizer tokenizer = new StringTokenizer(line);
    // Iterate through each token and write it to the context
    while (tokenizer.hasMoreTokens()) {
        // Set the current word
        word.set(tokenizer.nextToken().trim());
        // Write the word and its count to the context
        context.write(word, one);
    }
}

그런 다음 다음 명령을 사용하여 java 8 버전으로 코드를 컴파일합니다.

javac -source 8 -target 8 -cp $HADOOP_HOME/share/hadoop/common/hadoop-common-3.3.6.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-3.3.6.jar:. WordCountMapper.java

사용자 정의 Reducer

마지막으로, Reducer를 확장하는 WordCountReducer라는 사용자 정의 Reducer 클래스를 생성합니다. 이 Reducer 는 각 키에 대한 값을 집계하고 최종 결과를 내보냅니다. /home/hadoop/ 아래의 WordCountReducer.java에서 reduce 메서드를 다음 예제로 보완합니다.

@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context)
        throws IOException, InterruptedException {
    // Initialize a variable to store the sum of counts for each word
    int sum = 0;
    // Iterate through all counts for the current word and calculate the total sum
    for (IntWritable value : values) {
        sum += value.get();
    }
    // Set the final count for the current word
    result.set(sum);
    // Write the word and its final count to the context
    context.write(key, result);
}

그런 다음 다음 명령을 사용하여 java 8 버전으로 코드를 컴파일합니다.

javac -source 8 -target 8 -cp $HADOOP_HOME/share/hadoop/common/hadoop-common-3.3.6.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-3.3.6.jar:. WordCountReducer.java

사용자 정의 입력 및 출력 형식 작성

이 단계에서는 MapReduce 작업에 대한 입력 및 출력 형식을 지정합니다.

사용자 정의 입력 형식

먼저, 특정 소스에서 데이터를 읽기 위한 사용자 정의 입력 형식을 생성해 보겠습니다. TextInputFormat을 확장하고 getCurrentValue 메서드를 재정의하여 입력 형식을 처리하는 PersonInputFormat이라는 클래스를 정의합니다. /home/hadoop/ 아래의 PersonInputFormat.java에서 getCurrentValue 메서드를 다음 예제로 보완합니다.

@Override
public synchronized Text getCurrentValue() {
    // Return the value of the current record, split it according to ":", remove the first and last blanks and set it to the Text object.
    Text value = new Text();
    Text line = super.getCurrentValue();
    String[] parts = line.toString().split(":");
    if (parts.length == 2) {
        value.set(parts[1].trim());
    }
    return value;
}

그런 다음 다음 명령을 사용하여 java 8 버전으로 코드를 컴파일합니다.

javac -source 8 -target 8 -cp $HADOOP_HOME/share/hadoop/common/hadoop-common-3.3.6.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-3.3.6.jar:. PersonInputFormat.java

사용자 정의 출력 형식

다음으로, 사용자 정의 출력 형식을 생성해 보겠습니다. TextOutputFormat을 확장하는 CSVOutputFormat이라는 클래스를 정의합니다. /home/hadoop/ 아래의 CSVOutputFormat.java에서 write 메서드를 다음 예제로 보완합니다.

// Write the key-value pair to the output stream in CSV format
@Override
public void write(Text key, IntWritable value) throws IOException, InterruptedException {
    out.writeBytes(key.toString() + "," + value.toString() + "\n");
}

그런 다음 다음 명령을 사용하여 java 8 버전으로 코드를 컴파일합니다.

javac -source 8 -target 8 -cp $HADOOP_HOME/share/hadoop/common/hadoop-common-3.3.6.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-3.3.6.jar:. CSVOutputFormat.java

드라이버 (Driver) 통합

이 마지막 단계에서는 이전에 생성한 사용자 정의 입력 및 출력 형식을 활용하도록 WordCountDriver 클래스를 수정합니다.

사용자 정의 드라이버

/home/hadoop/ 아래의 WordCountDriver.java에서 main 함수를 다음 예제로 보완합니다.

// Set Mapper and Reducer classes
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);

// Set input format class to custom input format PersonInputFormat
job.setInputFormatClass(PersonInputFormat.class);

// Set output format class to custom output format CSVOutputFormat
job.setOutputFormatClass(CSVOutputFormat.class);

작업 실행

사용자 정의 입력 및 출력 형식을 사용하여 Hadoop MapReduce 작업을 실행하려면 다음 단계를 따르십시오.

  1. 적절한 Hadoop 종속성을 사용하여 WordCountDriver.java 를 컴파일합니다.

    javac -source 8 -target 8 -cp $HADOOP_HOME/share/hadoop/common/hadoop-common-3.3.6.jar:$HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-client-core-3.3.6.jar:. WordCountDriver.java
  2. 컴파일된 클래스를 포함하는 JAR 파일을 생성합니다.

    jar -cvf mywordcount.jar *.class
  3. 적절한 입력 및 출력 경로를 사용하여 WordCountDriver 클래스를 실행합니다. 출력 경로가 이전에 존재하지 않는지 확인하십시오.

    hadoop jar ./mywordcount.jar WordCountDriver /user/hadoop/input /output

이 명령은 정의한 사용자 정의 입력 및 출력 형식을 사용하여 Hadoop MapReduce 작업을 실행합니다.

출력 결과 보기

결과 파일이 성공적으로 생성되었는지 확인하려면 다음 명령을 사용하십시오.

hdfs dfs -ls /output
hdfs dfs -cat /output/part.csv

요약

축하합니다! 이 랩에서는 Ghost Tutor 의 안내에 따라 Hadoop MapReduce 의 복잡성을 성공적으로 탐구하고 출력 및 입력 형식 사용자 정의를 마스터했습니다. 매퍼 (mapper) 및 리듀서 (reducer) 클래스 생성부터 분할할 수 없는 입력 파일 처리와 같은 문제 극복에 이르기까지 귀중한 통찰력을 얻었습니다. 실습을 통해 Hadoop MapReduce 기능에 대한 이해를 심화시켰으며 이제 데이터 문제를 자신 있게 해결할 수 있습니다. 이 여정은 기술적 기술을 향상시켰을 뿐만 아니라 빅 데이터 처리에서 Hadoop MapReduce 의 잠재력에 대한 시야를 넓혔습니다.