forked from jcoene/riago
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmapred.go
74 lines (66 loc) · 1.71 KB
/
mapred.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
package riago
import (
"bytes"
)
// Perform a Riak Map Reduce request. Returns multiple map-reduce responses.
func (c *Conn) MapRed(req *RpbMapRedReq) ([]*RpbMapRedResp, error) {
var resps []*RpbMapRedResp
if err := c.request(MsgRpbMapRedReq, req); err != nil {
return nil, err
}
for {
resp := new(RpbMapRedResp)
if err := c.response(resp); err != nil {
return nil, err
}
resps = append(resps, resp)
if resp.GetDone() {
break
}
}
return resps, nil
}
// GetMany is a convenience method that uses map-reduce with
// Riak built-in erlang functions to get many documents at once.
//
// Warning: If you specify an empty list of keys, it will do a full
// map-reduce on the bucket (usually not a good idea).
func (c *Conn) GetMany(bucket string, keys []string) ([][]byte, error) {
var res [][]byte
req := &RpbMapRedReq{
Request: setUnionQuery(bucket, keys),
ContentType: []byte("application/json"),
}
resps, err := c.MapRed(req)
if err != nil {
return nil, err
}
for _, resp := range resps {
if resp.Response == nil {
continue
}
res = append(res, resp.GetResponse())
}
return res, nil
}
func setUnionQuery(bucket string, keys []string) []byte {
b := bytes.NewBuffer([]byte(`{"inputs":`))
if len(keys) == 0 {
b.WriteRune('"')
b.WriteString(bucket)
b.WriteRune('"')
} else {
b.WriteRune('[')
for i, key := range keys {
if i > 0 {
b.WriteRune(',')
}
b.Write([]byte(`["` + bucket + `","` + key + `"]`))
}
b.WriteRune(']')
}
b.Write([]byte(`,"query":[` +
`{"map":{"language":"erlang","module":"riak_kv_mapreduce","function":"map_object_value"}},` +
`{"reduce":{"language":"erlang","module":"riak_kv_mapreduce","function":"reduce_set_union"}}]}`))
return b.Bytes()
}