-
Notifications
You must be signed in to change notification settings - Fork 487
/
Copy pathelasticsearch.go
197 lines (174 loc) · 4.88 KB
/
elasticsearch.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
package elastic
import (
"context"
"fmt"
"github.com/olivere/elastic"
"log"
"net/http"
"os"
"time"
"github.com/olivere/elastic/v7"
)
var client *esClient
type esClient struct {
*elastic.Client
ctx context.Context
}
const host = "http://127.0.0.1:9200"
// build the elasticSearch the client
func NewElasticSearchClient() error {
errLog := log.New(os.Stdout, "Elastic", log.LstdFlags)
tr := NewTransport(WithDebug(false))
httpCli := &http.Client{
Transport: tr,
}
esCli, err := elastic.NewClient(
elastic.SetErrorLog(errLog),
elastic.SetURL(host),
elastic.SetBasicAuth("elastic", "123456"),
elastic.SetHttpClient(httpCli),
elastic.SetHealthcheck(false),
)
if err != nil {
return err
}
client = &esClient{Client: esCli, ctx: context.Background()}
result, code, err := client.Ping(host).Do(context.Background())
if err != nil {
return err
}
log.Printf("Elasticsearch returned with code: %d and version: %s", code, result.Version.Number)
version, err := client.ElasticsearchVersion(host)
if err != nil {
return err
}
log.Printf("Elasticsearch version :%s", version)
return nil
}
// init the elastic search
func init() {
err := NewElasticSearchClient()
if err != nil {
fmt.Println(err.Error())
}
}
// insert a document to the index
// test http://ip/index
func (client *esClient) Insert(index string, value interface{}) (*elastic.IndexResponse, error) {
// access by the http://localhost:9700/pibigstar/employee/id
response, err := client.Index().
Index(index).
BodyJson(value).
Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}
// get the document by id
func (client *esClient) GetById(index string, id string) ([]byte, error) {
// id 必须存在,不然会报错,如果想查找请用search
result, err := client.Get().Index(index).Id(id).Do(client.ctx)
if err != nil && !result.Found {
return nil, err
}
if result.Found {
bytes, _ := result.Source.MarshalJSON()
return bytes, nil
}
return nil, nil
}
// search the result by query strings
func (client *esClient) Query(index, keyword string) (*elastic.SearchResult, error) {
// 根据名字查询
query := elastic.NewQueryStringQuery(keyword)
result, err := client.Search().Index(index).Query(query).Do(client.ctx)
return result, err
}
// Aggregate query
func (client *esClient) AggQuery(index, keyword string) (*elastic.SearchResult, error) {
agg := elastic.NewDateHistogramAggregation().
Field("@timestamp").
TimeZone("Asia/Shanghai").
MinDocCount(1).
Interval("1m")
// 查询一分钟前是否出现关键字keyword
boolQuery := elastic.NewBoolQuery().
Filter(elastic.NewRangeQuery("@timestamp").
Format("strict_date_optional_time").
Gte(time.Now().Add(time.Minute * -1).Format(time.RFC3339)).
Lte(time.Now().Format(time.RFC3339))).
Filter(elastic.NewMultiMatchQuery(keyword).
Type("best_fields").
Lenient(true))
result, err := client.Search().
Index(index).
Query(boolQuery).
Timeout("30000ms").
IgnoreUnavailable(true).
Size(500).
Aggregation("aggs", agg).
Version(true).
StoredFields("*").
Do(client.ctx)
return result, err
}
// delete the document by id
func (client *esClient) DeleteById(index, id string) (*elastic.DeleteResponse, error) {
response, err := client.Delete().Index(index).Id(id).Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}
// update the document by id
// values : map[string]interface{}{"age": 12}
func (client *esClient) UpdateById(index, id string, values map[string]interface{}) (*elastic.UpdateResponse, error) {
response, err := client.Update().
Index(index).
Id(id).
Doc(values).Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}
// 批量执行操作
func (client *esClient) MUpdate(index, id string, values map[string]interface{}) (*elastic.BulkResponse, error) {
response, err := client.Bulk().
Add(elastic.NewBulkUpdateRequest().Index(index).Id(id).Doc(values)).
Add(elastic.NewBulkDeleteRequest().Index(index).Id(id)).
Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}
// 批量获取
func (client *esClient) MGet(index string, ids []string) (*elastic.MgetResponse, error) {
var getItems []*elastic.MultiGetItem
for _, id := range ids {
getItems = append(getItems, elastic.NewMultiGetItem().Index(index).Id(id))
}
response, err := client.Mget().Add(getItems...).
Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}
// 批量搜索
func (client *esClient) MSearch(index string, ids []string) (*elastic.MultiSearchResult, error) {
var searchRequests []*elastic.SearchRequest
for _, id := range ids {
searchRequests = append(searchRequests,
elastic.NewSearchRequest().Index(index).Query(
elastic.NewBoolQuery().Must(elastic.NewTermQuery("id", id))))
}
response, err := client.MultiSearch().Add(searchRequests...).
Do(client.ctx)
if err != nil {
return nil, err
}
return response, nil
}