-
Notifications
You must be signed in to change notification settings - Fork 40
/
common.go
227 lines (211 loc) · 5.36 KB
/
common.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package esbulk
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
)
// Application Version
const Version = "0.3.9"
var ErrParseCannotServerAddr = errors.New("cannot parse server address")
// Options represents bulk indexing options
type Options struct {
Host string
Port int
Index string
DocType string
BatchSize int
Verbose bool
IDField string
// http or https
Scheme string
}
func (o *Options) SetServer(s string) error {
u, err := url.Parse(s)
if err != nil {
return err
}
o.Scheme = u.Scheme
parts := strings.Split(u.Host, ":")
switch len(parts) {
case 1:
log.Println(s, u.Host, parts)
// assume port, like https://:9200
port, err := strconv.Atoi(parts[0])
if err != nil {
return err
}
o.Port = port
case 2:
o.Host = parts[0]
port, err := strconv.Atoi(parts[1])
if err != nil {
return err
}
o.Port = port
default:
return ErrParseCannotServerAddr
}
return nil
}
// BulkIndex takes a set of documents as strings and indexes them into elasticsearch
func BulkIndex(docs []string, options Options) error {
if len(docs) == 0 {
return nil
}
link := fmt.Sprintf("%s://%s:%d/%s/%s/_bulk", options.Scheme, options.Host, options.Port, options.Index, options.DocType)
var lines []string
for _, doc := range docs {
if len(strings.TrimSpace(doc)) == 0 {
continue
}
header := fmt.Sprintf(`{"index": {"_index": "%s", "_type": "%s"}}`, options.Index, options.DocType)
// If an "-id" is given, peek into the document to extract the ID and
// use it in the header.
if options.IDField != "" {
var docmap map[string]interface{}
dec := json.NewDecoder(strings.NewReader(doc))
dec.UseNumber()
if err := dec.Decode(&docmap); err != nil {
return err
}
// Find ID in the document.
id, ok := docmap[options.IDField]
if !ok {
return fmt.Errorf("document has no ID field (%s): %s", options.IDField, doc)
}
// ID can be any type at this point, try to find a string reprentation or bail out.
var idstr string
switch t := id.(type) {
case string:
idstr = t
case fmt.Stringer:
idstr = t.String()
case json.Number:
idstr = t.String()
default:
return fmt.Errorf("cannot convert %T id value to string: %v", id, id)
}
header = fmt.Sprintf(`{"index": {"_index": "%s", "_type": "%s", "_id": "%s"}}`,
options.Index, options.DocType, idstr)
// Remove the IDField if it is accidentally named '_id', since
// Field [_id] is a metadata field and cannot be added inside a
// document.
if options.IDField == "_id" {
delete(docmap, "_id")
b, err := json.Marshal(docmap)
if err != nil {
return err
}
doc = string(b)
}
}
lines = append(lines, header)
lines = append(lines, doc)
}
body := fmt.Sprintf("%s\n", strings.Join(lines, "\n"))
response, err := http.Post(link, "application/json", strings.NewReader(body))
if err != nil {
return err
}
if response.StatusCode >= 400 {
return fmt.Errorf("indexing failed with %d %s", response.StatusCode, http.StatusText(response.StatusCode))
}
return response.Body.Close()
}
// Worker will batch index documents that come in on the lines channel
func Worker(id string, options Options, lines chan string, wg *sync.WaitGroup) {
defer wg.Done()
var docs []string
counter := 0
for s := range lines {
docs = append(docs, s)
counter++
if counter%options.BatchSize == 0 {
err := BulkIndex(docs, options)
if err != nil {
log.Fatal(err)
}
if options.Verbose {
log.Printf("[%s] @%d\n", id, counter)
}
docs = docs[:0]
}
}
err := BulkIndex(docs, options)
if err != nil {
log.Fatal(err)
}
if options.Verbose {
log.Printf("[%s] @%d\n", id, counter)
}
}
// PutMapping reads and applies a mapping from a reader.
func PutMapping(options Options, body io.Reader) error {
link := fmt.Sprintf("%s://%s:%d/%s/_mapping/%s", options.Scheme, options.Host, options.Port, options.Index, options.DocType)
req, err := http.NewRequest("PUT", link, body)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if options.Verbose {
log.Printf("applied mapping: %s", resp.Status)
}
return resp.Body.Close()
}
// CreateIndex creates a new index.
func CreateIndex(options Options) error {
resp, err := http.Get(fmt.Sprintf("%s://%s:%d/%s", options.Scheme, options.Host, options.Port, options.Index))
if err != nil {
return err
}
if resp.StatusCode == 200 {
return nil
}
req, err := http.NewRequest("PUT", fmt.Sprintf("%s://%s:%d/%s/", options.Scheme, options.Host, options.Port, options.Index), nil)
if err != nil {
return err
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 400 {
msg, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return errors.New(string(msg))
}
if options.Verbose {
log.Printf("created index: %s\n", resp.Status)
}
return nil
}
// DeleteIndex removes an index.
func DeleteIndex(options Options) error {
link := fmt.Sprintf("%s://%s:%d/%s", options.Scheme, options.Host, options.Port, options.Index)
req, err := http.NewRequest("DELETE", link, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if options.Verbose {
log.Printf("purged index: %s", resp.Status)
}
return resp.Body.Close()
}