๐ Data Engineering
MapReduce
MapReduce
A distributed data processing programming model. Parallel processing with Map and Reduce functions.
MapReduce
A distributed data processing programming model. Parallel processing with Map and Reduce functions.
MapReduce is a distributed data processing programming model published by Google that allows large datasets to be processed in parallel across many computers. It consists of two phases, Map and Reduce, and is used as Hadoop's core processing engine.
| Stage | Input | Output | Description |
|---|---|---|---|
| Map | (key1, value1) | list(key2, value2) | Data transformation and filtering |
| Shuffle | list(key2, value2) | (key2, list(value2)) | Grouping and sorting by key |
| Reduce | (key2, list(value2)) | (key3, value3) | Aggregation and result generation |
| Characteristics | MapReduce | Spark |
|---|---|---|
| Processing method | Disk-based | In-memory |
| Speed | Slow (disk I/O) | Fast (10-100x) |
| Iterative processing | Inefficient | Efficient |
| API | Low-level | High-level (DataFrame, SQL) |
| Streaming | Not supported | Supported |
# mapper.py - Map ๋จ๊ณ
#!/usr/bin/env python3
"""
WordCount Mapper
์
๋ ฅ: ํ
์คํธ ๋ผ์ธ
์ถ๋ ฅ: (๋จ์ด, 1) ์
"""
import sys
import re
def mapper():
for line in sys.stdin:
# ์๋ฌธ์ ๋ณํ ๋ฐ ํน์๋ฌธ์ ์ ๊ฑฐ
line = line.strip().lower()
words = re.findall(r'\b[a-z]+\b', line)
for word in words:
# ํญ์ผ๋ก ๊ตฌ๋ถ๋ ํค-๊ฐ ์ถ๋ ฅ
print(f"{word}\t1")
if __name__ == "__main__":
mapper()
# reducer.py - Reduce ๋จ๊ณ
#!/usr/bin/env python3
"""
WordCount Reducer
์
๋ ฅ: ์ ๋ ฌ๋ (๋จ์ด, 1) ์
์ถ๋ ฅ: (๋จ์ด, ์ด ์นด์ดํธ)
"""
import sys
def reducer():
current_word = None
current_count = 0
for line in sys.stdin:
line = line.strip()
try:
word, count = line.split('\t')
count = int(count)
except ValueError:
continue
# ๊ฐ์ ๋จ์ด๋ฉด ์นด์ดํธ ๋์
if current_word == word:
current_count += count
else:
# ์ด์ ๋จ์ด ๊ฒฐ๊ณผ ์ถ๋ ฅ
if current_word:
print(f"{current_word}\t{current_count}")
current_word = word
current_count = count
# ๋ง์ง๋ง ๋จ์ด ์ถ๋ ฅ
if current_word:
print(f"{current_word}\t{current_count}")
if __name__ == "__main__":
reducer()
# Hadoop Streaming์ผ๋ก MapReduce ์์
์คํ
# ์
๋ ฅ ๋ฐ์ดํฐ HDFS์ ์
๋ก๋
hdfs dfs -mkdir -p /input/wordcount
hdfs dfs -put sample_text.txt /input/wordcount/
# MapReduce ์์
์คํ
hadoop jar $HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-*.jar \
-files mapper.py,reducer.py \
-mapper "python3 mapper.py" \
-reducer "python3 reducer.py" \
-input /input/wordcount/ \
-output /output/wordcount
# ๊ฒฐ๊ณผ ํ์ธ
hdfs dfs -cat /output/wordcount/part-00000 | head -20
# ๋ก์ปฌ ํ
์คํธ (Unix ํ์ดํ๋ผ์ธ)
cat sample_text.txt | python3 mapper.py | sort | python3 reducer.py
// Java MapReduce WordCount
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 {
// Mapper ํด๋์ค
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
// ๋จ์ด ํ ํฐํ
StringTokenizer itr = new StringTokenizer(
value.toString().toLowerCase()
);
while (itr.hasMoreTokens()) {
word.set(itr.nextToken().replaceAll("[^a-z]", ""));
if (word.getLength() > 0) {
context.write(word, one);
}
}
}
}
// Combiner/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 {
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); // ๋ก์ปฌ ์ง๊ณ
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);
}
}
# MRJob์ ์ฌ์ฉํ Python MapReduce
from mrjob.job import MRJob
from mrjob.step import MRStep
import re
class WordCount(MRJob):
"""MRJob์ผ๋ก ๊ตฌํํ WordCount"""
# ์ ๊ท์ ํจํด
WORD_RE = re.compile(r"[a-z]+")
def mapper(self, _, line):
"""Map: ๋ผ์ธ์ ๋จ์ด๋ก ๋ถํ """
for word in self.WORD_RE.findall(line.lower()):
yield word, 1
def combiner(self, word, counts):
"""Combiner: ๋ก์ปฌ ์ง๊ณ (์ ํ์ )"""
yield word, sum(counts)
def reducer(self, word, counts):
"""Reduce: ์ต์ข
์ง๊ณ"""
yield word, sum(counts)
class TopNWords(MRJob):
"""์์ N๊ฐ ๋จ์ด ์ฐพ๊ธฐ (๋ค๋จ๊ณ MapReduce)"""
def steps(self):
return [
MRStep(mapper=self.mapper_get_words,
combiner=self.combiner_count_words,
reducer=self.reducer_count_words),
MRStep(reducer=self.reducer_find_top_n)
]
def mapper_get_words(self, _, line):
for word in re.findall(r'[a-z]+', line.lower()):
yield word, 1
def combiner_count_words(self, word, counts):
yield word, sum(counts)
def reducer_count_words(self, word, counts):
# ๋ชจ๋ ๊ฒฐ๊ณผ๋ฅผ ํ๋์ Reducer๋ก
yield None, (sum(counts), word)
def reducer_find_top_n(self, _, word_count_pairs):
# ์์ 10๊ฐ ์ถ์ถ
top_n = sorted(word_count_pairs, reverse=True)[:10]
for count, word in top_n:
yield word, count
if __name__ == '__main__':
WordCount.run()
# ์คํ ๋ฐฉ๋ฒ
# ๋ก์ปฌ: python wordcount.py input.txt
# Hadoop: python wordcount.py -r hadoop hdfs:///input/text.txt