-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathcommon_reduce.go
77 lines (61 loc) · 1.57 KB
/
common_reduce.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package mapreduce
import (
"os"
"log"
"encoding/json"
"sort"
)
// doReduce does the job of a reduce worker: it reads the intermediate
// key/value pairs (produced by the map phase) for this task, sorts the
// intermediate key/value pairs by key, calls the user-defined reduce function
// (reduceF) for each key, and writes the output to disk.
func doReduce(
jobName string, // the name of the whole MapReduce job
reduceTaskNumber int, // which reduce task this is
nMap int, // the number of map tasks that were run ("M" in the paper)
reduceF func(key string, values []string) string,
) {
// file.Close()
//setp 1,read map generator file ,same key merge put map[string][]string
kvs := make(map[string][]string)
for i := 0; i < nMap; i++ {
fileName := reduceName(jobName, i, reduceTaskNumber)
file, err := os.Open(fileName)
if err != nil {
log.Fatal("doReduce1: ", err)
}
dec := json.NewDecoder(file)
for {
var kv KeyValue
err = dec.Decode(&kv)
if err != nil {
break
}
_, ok := kvs[kv.Key]
if !ok {
kvs[kv.Key] = []string{}
}
kvs[kv.Key] = append(kvs[kv.Key], kv.Value)
}
file.Close()
}
var keys []string
for k := range kvs {
keys = append(keys, k)
}
//setp 2 sort by keys
sort.Strings(keys)
//setp 3 create result file
p := mergeName(jobName, reduceTaskNumber)
file, err := os.Create(p)
if err != nil {
log.Fatal("doReduce2: ceate ", err)
}
enc := json.NewEncoder(file)
//setp 4 call user reduce each key of kvs
for _, k := range keys {
res := reduceF(k, kvs[k])
enc.Encode(KeyValue{k, res})
}
file.Close()
}