-
Notifications
You must be signed in to change notification settings - Fork 1
/
es.go
201 lines (191 loc) · 5.64 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
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"io"
"log"
"net"
"net/http"
"time"
)
func NewElasticsearchClient() (*elasticsearch.Client, error) {
cfg := elasticsearch.Config{
Addresses: Config.ElasticsearchHosts,
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
return nil, fmt.Errorf("failed to connect to Elasticsearch: %w", err)
}
return es, nil
}
func getMappings(es *elasticsearch.Client) (map[string]interface{}, error) {
ctx := context.Background()
res, err := es.Indices.GetMapping(
es.Indices.GetMapping.WithIndex(Config.ElasticsearchIndexIncludePattern),
es.Indices.GetMapping.WithContext(ctx),
)
if err != nil {
return nil, fmt.Errorf("failed to get index mappings: %w", err)
}
if res.IsError() {
return nil, fmt.Errorf(res.String())
}
data := map[string]interface{}{}
if err = json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, fmt.Errorf("failed to decode mappings from response: %w", err)
}
return data, nil
}
func buildQueryFromArgs(args map[string]interface{}) map[string]interface{} {
q := map[string]interface{}{
"query": map[string]interface{}{
"bool": map[string]interface{}{},
},
}
// TODO: refactor boolean query parsing and add validation
if boolQuery, exists := args["boolean_query"]; exists {
for clause := range boolQuery.(map[string]interface{}) {
for field := range boolQuery.(map[string]interface{})[clause].(map[string]interface{}) {
for termLevel := range boolQuery.(map[string]interface{})[clause].(map[string]interface{})[field].(map[string]interface{}) {
sq, ok := q["query"].(map[string]interface{})
if !ok {
continue
}
sq["bool"] = map[string]interface{}{
clause: map[string]interface{}{
termLevel: map[string]interface{}{
getOriginalName(field): boolQuery.(map[string]interface{})[clause].(map[string]interface{})[field].(map[string]interface{})[termLevel],
},
},
}
}
}
}
}
return q
}
func query(ctx context.Context, es *elasticsearch.Client, index string, size int, selectedFields []string, args map[string]interface{}) ([]interface{}, error) {
q := buildQueryFromArgs(args)
buf := bytes.Buffer{}
if err := json.NewEncoder(&buf).Encode(q); err != nil {
return nil, err
}
if Config.EnableQueryLogging {
log.Print(buf.String())
}
// TODO: consolidate common logic between queries
res, err := es.Search(
es.Search.WithSource(selectedFields...),
es.Search.WithContext(ctx),
es.Search.WithIndex(index),
es.Search.WithSize(size),
es.Search.WithBody(&buf),
)
if err != nil {
return nil, err
}
data, err := parseQueryResponse(res)
if err != nil {
return nil, err
}
return data["hits"].(map[string]interface{})["hits"].([]interface{}), nil
}
func queryByID(ctx context.Context, es *elasticsearch.Client, index, id string, selectedFields []string) (map[string]interface{}, error) {
res, err := es.Get(index, id,
es.Get.WithSource(selectedFields...),
es.Get.WithContext(ctx),
)
if err != nil {
return nil, err
}
return parseQueryResponse(res)
}
func queryAggregation(ctx context.Context, es *elasticsearch.Client, index string, selectedFields []string, args map[string]interface{}, aggregationType AggregationType) (map[string]interface{}, error) {
// TODO: refactor aggregation query parsing and add validation
q := buildQueryFromArgs(args)
q["aggs"] = map[string]interface{}{}
for _, field := range selectedFields {
sq := map[string]map[string]interface{}{
string(aggregationType): {
"field": field,
},
}
if aggregationType == AggregationTypePercentiles {
sq[string(aggregationType)]["keyed"] = false
}
q["aggs"].(map[string]interface{})[fmt.Sprintf("%v_%s", aggregationType, field)] = sq
}
buf := bytes.Buffer{}
if err := json.NewEncoder(&buf).Encode(q); err != nil {
return nil, err
}
if Config.EnableQueryLogging {
log.Print(buf.String())
}
res, err := es.Search(
es.Search.WithSource(selectedFields...),
es.Search.WithContext(ctx),
es.Search.WithIndex(index),
es.Search.WithSize(0),
es.Search.WithBody(&buf),
)
if err != nil {
return nil, err
}
data, err := parseQueryResponse(res)
if err != nil {
return nil, err
}
// TODO: refactor aggregation parsing and add error handling
results := make(map[string]interface{})
for _, field := range selectedFields {
v, ok := data["aggregations"].(map[string]interface{})[fmt.Sprintf("%v_%s", aggregationType, field)].(map[string]interface{})
if !ok {
continue
}
if value, ok := v["value"]; ok {
results[field] = value
continue
}
if values, ok := v["values"]; ok {
results[field] = values
continue
}
}
return results, nil
}
func parseQueryResponse(res *esapi.Response) (map[string]interface{}, error) {
defer res.Body.Close()
if res.IsError() {
return nil, parseQueryError(res)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if Config.EnableQueryResultLogging {
log.Print(string(body))
}
data := map[string]interface{}{}
if err = json.Unmarshal(body, &data); err != nil {
return nil, err
}
return data, nil
}
func parseQueryError(res *esapi.Response) error {
data := map[string]interface{}{}
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return fmt.Errorf("failed to parse response body: %w", err)
}
errData := data["error"].(map[string]interface{})
return fmt.Errorf("query failed: %s %s: %s", res.Status(), errData["type"], errData["reason"])
}