-
Notifications
You must be signed in to change notification settings - Fork 0
/
elasticsearch.go
168 lines (149 loc) · 4.12 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
package client
import (
"context"
"encoding/json"
cfg "github.com/XC-Zero/yinwan/pkg/config"
_interface "github.com/XC-Zero/yinwan/pkg/interface"
"github.com/XC-Zero/yinwan/pkg/utils/logger"
"github.com/olivere/elastic/v7"
"github.com/pkg/errors"
"log"
"strings"
)
const (
PRE_TAG = "<hl>"
POST_TAG = "</hl>"
)
// InitElasticsearch ...
func InitElasticsearch(config cfg.ESConfig) (*elastic.Client, error) {
esClient, err := elastic.NewClient(
elastic.SetSniff(false),
elastic.SetURL(config.Host),
elastic.SetBasicAuth(config.User, config.Password),
)
if err != nil {
panic(err)
}
info, code, err := esClient.Ping(config.Host).Do(context.Background())
if err != nil {
panic(err)
}
log.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
// Getting the ES version number is quite common, so there's a shortcut
esVersion, err := esClient.ElasticsearchVersion(config.Host)
if err != nil {
// Handle error
panic(err)
}
log.Printf("Elasticsearch version %s\n", esVersion)
return esClient, nil
}
func CreateIndex(model _interface.EsTabler) error {
exists, err := ESClient.IndexExists(model.TableName()).Do(context.Background())
if err != nil {
return err
}
if !exists {
_, err := ESClient.CreateIndex(model.TableName()).
BodyJson(model.Mapping()).
Do(context.Background())
if err != nil {
return err
}
}
return nil
}
// PutIntoIndex 添加数据
func PutIntoIndex(tabler _interface.EsTabler) error {
_, err := ESClient.Index().
Index(tabler.TableName()).
BodyJson(tabler.ToESDoc()).
Do(context.Background())
if err != nil {
return err
}
_, err = ESClient.Flush().Index(tabler.TableName()).Do(context.Background())
if err != nil {
return err
}
return nil
}
// GetFromIndex 获取数据, 所有字段均带高亮(指定字段失败)
func GetFromIndex(tabler _interface.EsTabler, query elastic.Query, from, size int) (list []interface{}, count int64, err error) {
highlight := elastic.NewHighlight()
highlight = highlight.Field("*").PreTags(PRE_TAG).PostTags(POST_TAG)
log.Println(highlight.Source())
res, err := ESClient.Search().
Index(tabler.TableName()).
From(from).Size(size).
Highlight(highlight).
Query(query).
RestTotalHitsAsInt(true).
Pretty(true).
Do(context.Background())
if err != nil {
return nil, 0, err
}
count = res.TotalHits()
//l := res.Each(reflect.TypeOf(tabler))
//log.Printf("%+v", l)
hit := res.Hits.Hits
for i := range hit {
var m map[string]interface{}
hl := hit[i].Highlight
err = json.Unmarshal(hit[i].Source, &m)
if err != nil {
logger.Error(errors.WithStack(err), "Unmarshal Error! ")
continue
}
for s, strList := range hl {
m[s] = strings.Join(strList, "")
}
list = append(list, m)
}
return
}
// DeleteFromIndex 删除数据
func DeleteFromIndex(tabler _interface.EsTabler, recID *int, ctx context.Context) error {
bookName := ctx.Value("book_name").(string)
b, ok := ReadBookMap(bookName)
if !ok {
return errors.New("There is no book name!")
}
if recID == nil || b.StorageName == "" {
return errors.New("缺少主键!")
}
do, err := ESClient.DeleteByQuery(tabler.TableName()).Query(elastic.NewTermQuery("rec_id", recID)).Do(context.Background())
if err != nil {
return err
}
log.Println(do.Total)
return nil
}
// DeleteIndex 删除索引!!! 谨慎使用
func DeleteIndex(tabler _interface.EsTabler) bool {
do, err := ESClient.DeleteIndex(tabler.TableName()).Do(context.Background())
if err != nil {
return false
}
return do.Acknowledged
}
// UpdateIntoIndex 更新内容
func UpdateIntoIndex(tabler _interface.EsTabler, recID *int, ctx context.Context, script *elastic.Script) error {
bookName := ctx.Value("book_name").(string)
b, ok := ReadBookMap(bookName)
if !ok {
return errors.New("There is no book name!")
}
if recID == nil || b.StorageName == "" {
return errors.New("缺少主键!")
}
if recID == nil {
return errors.New("缺少主键!")
}
_, err := ESClient.UpdateByQuery(tabler.TableName()).Query(elastic.NewTermQuery("rec_id", recID)).Script(script).Refresh("true").Do(context.Background())
if err != nil {
return err
}
return nil
}