Hadoop Inverted Index 실습
이 글에서는 Hadoop Fully Distributed Mode 환경에서 Inverted Index를 만드는 실습을 진행합니다. Inverted Index는 검색 엔진에서 핵심적으로 사용되는 자료구조로, 각 단어가 어떤 문서에 등장했는지를 저장합니다.
이 실습에 앞서 HDFS가 구축이 돼야 합니다.
https://konkukcodekat.tistory.com/252
[Hadoop] 하둡 HDFS 실습 환경 설정 (Fully Distributed 모드)
Hadoop Fully Distributed Mode + HDFS Setup 가이드1. Hadoop 실행 모드 소개Standalone Mode모든 프로세스를 단일 JVM에서 실행하며, HDFS를 사용하지 않음개발 및 테스트에 적합core-site.xml, mapred-site.xml, hdfs-site.xml
konkukcodekat.tistory.com
1. Inverted Index란?
- Inverted Index(역 인덱스)는 문서 안의 단어들을 기준으로, 어떤 단어가 어떤 문서에 포함되어 있는지를 빠르게 검색할 수 있게 해주는 자료구조이다.
정방향 인덱스 예시:
문서1 -> [단어 A, 단어 B, 단어 C]
문서2 -> [단어 B, 단어 D]
문서3 -> [단어 A, 단어 C, 단어 E]
역방향 인덱스 예시:
단어 A -> [문서1, 문서3]
단어 B -> [문서1, 문서2]
단어 C -> [문서1, 문서3]
단어 D -> [문서2]
2. Inverted Index를 구현할 Hadoop MapReduce 구조
- Map 단계: 문서ID와 단어 쌍을 출력 (단어, 문서ID)
- Shuffle & Sort 단계: 같은 키(단어)끼리 정렬 및 그룹화
- Reduce 단계: 단어별 문서ID 목록을 모아, 문서별 등장 횟수 집계 후 문자열로 결합하여 출력
3. 예제 입력 파일 작성
아래와 같이 탭(Tab) 문자를 기준으로 문서 ID와 본문 내용을 나눠 작성해야 한다.
test1.txt
202572271 Hello This is Text File for Hadoop
test2.txt
202572272 Hadoop is designed for Big Data Processing and Storage
# input 디렉토리 생성 및 파일 작성
cd ~/hadoop/input
sudo vi test1.txt
sudo vi test2.txt
4. MyInvertedIndex.java 코드 작성
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class MyInvertedIndex {
public static class TokenizerMapper extends Mapper<Object, Text, Text, Text> {
private Text word = new Text();
private Text documentId = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
int tabIndex = line.indexOf('\t');
if (tabIndex == -1) {
System.err.println("Skipping line without tab delimiter: " + line);
return;
}
String docId = line.substring(0, tabIndex).trim();
String content = line.substring(tabIndex + 1).trim();
documentId.set(docId);
String[] words = content.split("\\s+");
for (String w : words) {
word.set(w.toLowerCase());
context.write(word, documentId);
}
}
}
public static class InvertedIndexReducer extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
Map<String, Integer> countMap = new HashMap<>();
for (Text val : values) {
String docId = val.toString();
countMap.put(docId, countMap.getOrDefault(docId, 0) + 1);
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
if (!first) sb.append(" ");
sb.append(entry.getKey()).append(":" + entry.getValue());
first = false;
}
context.write(key, new Text(sb.toString()));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "inverted index");
job.setJarByClass(MyInvertedIndex.class);
job.setMapperClass(TokenizerMapper.class);
job.setReducerClass(InvertedIndexReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
5. 컴파일 및 실행 절차
# 컴파일
hadoop com.sun.tools.javac.Main MyInvertedIndex.java
# JAR 파일 생성
jar cf MyInvertedIndex.jar MyInvertedIndex*.class
# HDFS 입력 디렉토리 생성 및 파일 업로드
hdfs dfs -mkdir /input
hdfs dfs -put ~/hadoop/input/test1.txt /input/
hdfs dfs -put ~/hadoop/input/test2.txt /input/
# 실행
hadoop jar MyInvertedIndex.jar MyInvertedIndex /input /output
# 결과 확인
hdfs dfs -cat /output/*
출력 예시는 아래와 같을 수 있다:
hadoop 202572271:1 202572272:1
hello 202572271:1
big 202572272:1
이로써 Hadoop 기반의 Inverted Index 구현 실습을 마쳤다.
WordCount 예제와 달리 문서 식별자를 포함해 각 단어가 어떤 문서에서 얼마나 등장했는지까지 추적 가능한 형태로 구현된다.
반응형
'Server-side 개발 & 트러블 슈팅 > 🐘 Hadoop (하둡)' 카테고리의 다른 글
[hadoop] 하둡 PageRank 알고리즘 개념과 MapReduce를 이용한 실습 (1) | 2025.04.20 |
---|---|
[Hadoop] 하둡 MapReduce 기본 실습 가이드 (Fully Distributed 모드) (0) | 2025.04.14 |
[Hadoop] 하둡 HDFS 실습 환경 설정 (Fully Distributed 모드) (0) | 2025.04.14 |
[Hadoop] 하둡 설치 및 MapReduce 기본 예제 실습 (Standalone 모드) (0) | 2025.04.14 |
[Hadoop] 하둡 실습을 위한 VM 환경 세팅 (virtual box, VMware Fusion) (0) | 2025.04.14 |
댓글