๐Ÿ“Š Data Engineering

MapReduce

MapReduce

A distributed data processing programming model. Parallel processing with Map and Reduce functions.

Detailed Explanation

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.

MapReduce processing stages

  • Input Split: Split the input data into chunks
  • Map: Process each chunk to generate key-value pairs
  • Shuffle & Sort: Group the values with the same key
  • Reduce: Aggregate the grouped values to produce the final result
  • Output: Store the results in the file system

How MapReduce works

StageInputOutputDescription
Map(key1, value1)list(key2, value2)Data transformation and filtering
Shufflelist(key2, value2)(key2, list(value2))Grouping and sorting by key
Reduce(key2, list(value2))(key3, value3)Aggregation and result generation

MapReduce vs Spark

CharacteristicsMapReduceSpark
Processing methodDisk-basedIn-memory
SpeedSlow (disk I/O)Fast (10-100x)
Iterative processingInefficientEfficient
APILow-levelHigh-level (DataFrame, SQL)
StreamingNot supportedSupported

Code Example

Python WordCount (Hadoop Streaming)

# 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()

Run Hadoop Streaming

# 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 (traditional approach)

// 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 wrapper library)

# 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

Practical Conversation Example

Junior developer: "I need to analyze large logs. Should I use MapReduce?"
Senior developer: "These days people use Spark more. MapReduce is slow because it writes to disk at every stage. Spark is in-memory, so it's much faster for iterative work."
Junior developer: "So is MapReduce no longer used?"
Senior developer: "You should still know the concept. Spark also does Map/Reduce-like transformations internally. And it's still used in legacy systems and as an execution engine for Hive queries."
Junior developer: "I heard the Shuffle between Map and Reduce is a bottleneck?"
Senior developer: "Right. Shuffle is slow because of heavy network transfer. If you aggregate locally in the Map phase in advance with a Combiner, you can reduce the amount of Shuffle data."

Cautions

Performance optimization

  • Reduce Shuffle data volume by using a Combiner
  • Set an appropriate number of partitions (too many adds overhead)
  • Prevent data skew - check the key distribution

MapReduce limitations

  • Inefficient for iterative algorithms (ML) - disk I/O every time
  • No real-time processing - batch only
  • Difficult to implement complex DAG workflows

Development notes

  • Make sure the Reducer output key type = the Map output key type
  • The Iterator in a Reducer can only be traversed once
  • Test large data locally before running on the cluster

Related Terms

Learn More