-
Notifications
You must be signed in to change notification settings - Fork 0
/
es.go
82 lines (73 loc) · 1.83 KB
/
es.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
package v8
import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/hopeio/cherry/utils/io/reader"
"net/http"
)
type SearchResponse[T any] struct {
Took int `json:"took"`
TimedOut bool `json:"timed_out"`
Shards Shards `json:"_shards"`
Hits Hits[T] `json:"hits"`
}
type Shards struct {
Total int `json:"total"`
Successful int `json:"successful"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
}
type Hits[T any] struct {
Total Total `json:"total"`
MaxScore any `json:"max_score"`
Hits []Hit[T] `json:"hits"`
}
type Hit[T any] struct {
Index string `json:"_index"`
Id string `json:"_id"`
Score interface{} `json:"_score"`
Source T `json:"_source"`
Sort []int `json:"sort"`
}
type Total struct {
Value int `json:"value"`
Relation string `json:"relation"`
}
func GetResponseData[T any](response *esapi.Response, err error) (*T, error) {
if err != nil {
return nil, err
}
bytes, err := reader.ReadCloser(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
return nil, errors.New(string(bytes))
}
var res T
err = json.Unmarshal(bytes, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func GetSearchResponseData[T any](response *esapi.Response, err error) (*SearchResponse[T], error) {
return GetResponseData[SearchResponse[T]](response, err)
}
func CreateDocument[T any](ctx context.Context, es *elasticsearch.Client, index, id string, obj T) error {
body, _ := json.Marshal(obj)
esreq := esapi.CreateRequest{
Index: index,
DocumentID: id,
Body: bytes.NewReader(body),
}
resp, err := esreq.Do(ctx, es)
if err != nil {
return err
}
return resp.Body.Close()
}