[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,167 @@
|
||||
id: wiki-2026-0508-mapreduce
|
||||
title: MapReduce
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-MARE-001]
|
||||
aliases: [맵리듀스, Hadoop MR, Map-Reduce]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.94
|
||||
tags: [auto-reinforced, mapreduce, Distributed-Computing, Big-Data, Parallel-Processing, cluster-computing]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [distributed, big-data, parallel, hadoop, batch]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: hadoop-spark
|
||||
---
|
||||
|
||||
# [[MapReduce|MapReduce]]
|
||||
# MapReduce
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "거대한 데이터를 작게 쪼개어 정복하라: 혼자서는 감당 못 할 방대한 데이터를 수천 대의 컴퓨터에 나누어 준 뒤(Map), 각자 계산한 결과들 중에서 필요한 것만 뽑아 다시 하나로 합치는(Reduce) 분산 처리의 표준 문법."
|
||||
## 매 한 줄
|
||||
> **"매 split → map → shuffle → reduce"**. MapReduce (Dean & Ghemawat, Google 2004) 는 대규모 batch 처리 의 functional programming 모델. 2026 perspective 에서 raw Hadoop MR 은 legacy, Spark / Flink / BigQuery / Beam 이 후속 표준.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
맵리듀스(MapReduce)는 대규모 데이터 세트를 병렬로 처리하기 위한 프로그래밍 모델이자 프레임워크입니다. (구글에 의해 대중화)
|
||||
## 매 핵심
|
||||
|
||||
1. **두 단계의 마법**:
|
||||
* **Map Step**: 입력 데이터를 (Key, Value) 쌍으로 변환하여 작은 작업들로 분산.
|
||||
* **Reduce Step**: 같은 Key를 가진 결과를 합산(Aggregating)하여 최종 결과 생성.
|
||||
2. **장점**:
|
||||
* **[[Scalability|Scalability]]**: 컴퓨터를 추가할수록 처리 능력이 선형적으로 증가. (Scalability와 연결)
|
||||
* **[[Fault-Tolerance|Fault-Tolerance]]**: 한 대의 컴퓨터가 고장 나도 다른 컴퓨터가 작업을 대신 수행. (Fault-Tolerance와 연결)
|
||||
### 매 4 phase
|
||||
- **Split**: input → fixed-size shards (HDFS block 64-128MB).
|
||||
- **Map**: (k1, v1) → list[(k2, v2)]. Stateless, parallelizable.
|
||||
- **Shuffle/Sort**: same k2 grouped to same reducer.
|
||||
- **Reduce**: (k2, list[v2]) → list[(k3, v3)].
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 모든 빅데이터 처리를 맵리듀스 정책으로 해결하려 했으나, 현대 정책은 디스크 기반의 느린 맵리듀스보다 메모리 기반의 빠른 'Apache Spark 정책'이나 '실시간 스트리밍 처리 정책'을 선호함(RL Update).
|
||||
- **정책 변화(RL Update)**: 단순히 데이터를 세는 정책을 넘어, 분산 환경에서 거대 인공지능 모델을 학습시키는 '분산 딥러닝 정책'으로 그 개념적 토대가 확장되어 계승됨. ([[High-Performance Computing (HPC)|High-Performance Computing (HPC)]]와 연결)
|
||||
### 매 design principles
|
||||
- **Data locality**: code → data, not data → code.
|
||||
- **Fault tolerance**: re-execute failed tasks (idempotent map/reduce).
|
||||
- **Speculative execution**: slow tasks 의 backup copy.
|
||||
- **Immutable inputs**: re-runnable.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Scalability|Scalability]], [[Fault-Tolerance|Fault-Tolerance]], [[High-Performance Computing (HPC)|High-Performance Computing (HPC)]], [[Analysis|Analysis]], [[Information-Society|Information-Society]]
|
||||
- **Modern Tech/Tools**: Hadoop (HDFS), Apache Spark, Google File[[_system|system]] (GFS), Hive.
|
||||
---
|
||||
### 매 응용
|
||||
1. Log analysis / web indexing (original use case).
|
||||
2. ETL pipelines.
|
||||
3. ML feature aggregation.
|
||||
4. Data warehouse build.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Word count (canonical)
|
||||
```python
|
||||
from collections import defaultdict
|
||||
from itertools import groupby
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
def map_phase(doc_id, text):
|
||||
for word in text.split():
|
||||
yield (word.lower(), 1)
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
def reduce_phase(word, counts):
|
||||
yield (word, sum(counts))
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def mapreduce(docs):
|
||||
# Map
|
||||
pairs = [kv for did, t in docs for kv in map_phase(did, t)]
|
||||
# Shuffle
|
||||
pairs.sort(key=lambda x: x[0])
|
||||
grouped = {k: [v for _, v in g] for k, g in groupby(pairs, key=lambda x: x[0])}
|
||||
# Reduce
|
||||
return dict(kv for k, vs in grouped.items() for kv in reduce_phase(k, vs))
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Combiner (local reduce)
|
||||
```python
|
||||
def map_with_combiner(doc_id, text):
|
||||
local = defaultdict(int)
|
||||
for word in text.split():
|
||||
local[word.lower()] += 1
|
||||
for w, c in local.items():
|
||||
yield (w, c)
|
||||
# 매 network shuffle 양 감소
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Spark RDD equivalent
|
||||
```python
|
||||
from pyspark import SparkContext
|
||||
sc = SparkContext()
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
counts = (sc.textFile("hdfs:///logs/*.txt")
|
||||
.flatMap(lambda line: line.split())
|
||||
.map(lambda w: (w.lower(), 1))
|
||||
.reduceByKey(lambda a, b: a + b))
|
||||
counts.saveAsTextFile("hdfs:///out/wc")
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Inverted index
|
||||
```python
|
||||
def map_idx(doc_id, text):
|
||||
for word in set(text.split()):
|
||||
yield (word.lower(), doc_id)
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def reduce_idx(word, doc_ids):
|
||||
yield (word, sorted(set(doc_ids)))
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Secondary sort
|
||||
```python
|
||||
# Composite key for sort-within-group
|
||||
def map_temp(line):
|
||||
parts = line.split(",")
|
||||
year, temp = parts[0], int(parts[1])
|
||||
yield ((year, temp), None) # negative temp for desc
|
||||
|
||||
def partitioner(key):
|
||||
return hash(key[0]) % num_reducers # group by year only
|
||||
|
||||
def grouping_comparator(a, b):
|
||||
return (a[0] > b[0]) - (a[0] < b[0]) # year only
|
||||
```
|
||||
|
||||
### Join (reduce-side)
|
||||
```python
|
||||
def map_users(row):
|
||||
yield (row["user_id"], ("user", row))
|
||||
|
||||
def map_orders(row):
|
||||
yield (row["user_id"], ("order", row))
|
||||
|
||||
def reduce_join(uid, tagged):
|
||||
user = next(r for tag, r in tagged if tag == "user")
|
||||
for tag, r in tagged:
|
||||
if tag == "order":
|
||||
yield {**user, **r}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Batch ETL on TB+ | Spark (Hadoop MR 은 legacy) |
|
||||
| Streaming | Flink / Spark Structured Streaming |
|
||||
| SQL-shaped query | BigQuery / Athena / Presto |
|
||||
| Cross-cloud portability | Apache Beam |
|
||||
| Educational | Raw MR pseudocode |
|
||||
|
||||
**기본값**: Spark for new projects; Hadoop MR 은 legacy 유지보수만.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed Systems]] · [[Parallel-Computing]]
|
||||
- 변형: [[Spark]] · [[Apache Flink]] · [[Apache Beam]]
|
||||
- 응용: [[Data Pipeline]] · [[ETL]]
|
||||
- Adjacent: [[HDFS]] · [[Hadoop YARN]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: pipeline design review, Spark migration 가이드, query optimization.
|
||||
**언제 X**: real-time low-latency — wrong paradigm.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Many small files**: HDFS namenode 폭발. 매 compaction 필수.
|
||||
- **Skewed keys**: 한 reducer 가 hotspot — salting / combiner 로 완화.
|
||||
- **Stateful map**: 매 idempotency 깨짐 → fault recovery 실패.
|
||||
- **Re-implementing SQL**: 매 BigQuery / Spark SQL 사용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Dean & Ghemawat OSDI 2004, Spark NSDI 2012, Hadoop docs 3.x).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — word-count + Spark + secondary-sort + join 패턴 |
|
||||
|
||||
Reference in New Issue
Block a user