-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.go
60 lines (46 loc) · 1.01 KB
/
document.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
package index
import (
"bytes"
"context"
"encoding/json"
"errors"
es "github.com/elastic/go-elasticsearch/v7"
esapi "github.com/elastic/go-elasticsearch/v7/esapi"
"io"
"io/ioutil"
)
func IndexDocument(ctx context.Context, es_client *es.Client, es_index string, doc_id string, doc interface{}) error {
b, err := json.Marshal(doc)
if err != nil {
return err
}
fh := bytes.NewReader(b)
return IndexDocumentWithReader(ctx, es_client, es_index, doc_id, fh)
}
func IndexDocumentWithReader(ctx context.Context, es_client *es.Client, es_index string, doc_id string, fh io.Reader) error {
select {
case <-ctx.Done():
return nil
default:
// pass
}
req := esapi.IndexRequest{
Index: es_index,
DocumentID: doc_id,
Body: fh,
Refresh: "true",
}
rsp, err := req.Do(ctx, es_client)
if err != nil {
return err
}
defer rsp.Body.Close()
switch rsp.StatusCode {
case 200, 201:
// pass
default:
body, _ := ioutil.ReadAll(rsp.Body)
return errors.New(string(body))
}
return nil
}