forked from pingcap/talent-plan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurltop10_example.go
83 lines (76 loc) · 2.07 KB
/
urltop10_example.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
78
79
80
81
82
83
package main
import (
"bytes"
"fmt"
"strconv"
"strings"
)
// ExampleURLTop10 generates RoundsArgs for getting the 10 most frequent URLs.
// There are two rounds in this approach.
// The first round will do url count.
// The second will sort results generated in the first round and
// get the 10 most frequent URLs.
func ExampleURLTop10(nWorkers int) RoundsArgs {
var args RoundsArgs
// round 1: do url count
args = append(args, RoundArgs{
MapFunc: ExampleURLCountMap,
ReduceFunc: ExampleURLCountReduce,
NReduce: nWorkers,
})
// round 2: sort and get the 10 most frequent URLs
args = append(args, RoundArgs{
MapFunc: ExampleURLTop10Map,
ReduceFunc: ExampleURLTop10Reduce,
NReduce: 1,
})
return args
}
// ExampleURLCountMap is the map function in the first round
func ExampleURLCountMap(filename string, contents string) []KeyValue {
lines := strings.Split(contents, "\n")
kvs := make([]KeyValue, 0, len(lines))
for _, l := range lines {
l = strings.TrimSpace(l)
if len(l) == 0 {
continue
}
kvs = append(kvs, KeyValue{Key: l})
}
return kvs
}
// ExampleURLCountReduce is the reduce function in the first round
func ExampleURLCountReduce(key string, values []string) string {
return fmt.Sprintf("%s %s\n", key, strconv.Itoa(len(values)))
}
// ExampleURLTop10Map is the map function in the second round
func ExampleURLTop10Map(filename string, contents string) []KeyValue {
lines := strings.Split(contents, "\n")
kvs := make([]KeyValue, 0, len(lines))
for _, l := range lines {
kvs = append(kvs, KeyValue{"", l})
}
return kvs
}
// ExampleURLTop10Reduce is the reduce function in the second round
func ExampleURLTop10Reduce(key string, values []string) string {
cnts := make(map[string]int, len(values))
for _, v := range values {
v := strings.TrimSpace(v)
if len(v) == 0 {
continue
}
tmp := strings.Split(v, " ")
n, err := strconv.Atoi(tmp[1])
if err != nil {
panic(err)
}
cnts[tmp[0]] = n
}
us, cs := TopN(cnts, 10)
buf := new(bytes.Buffer)
for i := range us {
fmt.Fprintf(buf, "%s: %d\n", us[i], cs[i])
}
return buf.String()
}