/
esswrapper.go
233 lines (200 loc) · 5.39 KB
/
esswrapper.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package esswrapper
import (
"encoding/json"
"fmt"
log "github.com/golang/glog"
elastigo "github.com/mattbaird/elastigo/lib"
"io/ioutil"
"os"
"strconv"
"strings"
)
type EssWrapper struct {
conn *elastigo.Conn
Index string
}
/*
Create the index if it does not exist.
Optionally apply a mapping if mapping file is supplied.
*/
func NewEssWrapper(esshost string, essport int, index string, mappingfile ...string) (*EssWrapper, error) {
ed := EssWrapper{conn: elastigo.NewConn(), Index: index}
ed.conn.Domain = esshost
ed.conn.Port = fmt.Sprintf("%d", essport)
if !ed.IndexExists() {
if len(mappingfile) > 0 {
log.V(9).Infof("Initializing with mapping file: %#v\n", mappingfile[0])
return &ed, ed.initializeIndex(mappingfile[0])
} else {
return &ed, ed.initializeIndex("")
}
}
return &ed, nil
}
func (e *EssWrapper) IndexExists() bool {
_, err := e.conn.DoCommand("GET", "/"+e.Index, nil, nil)
if err != nil {
return false
}
return true
}
/*
func (e *EssWrapper) SearchUsingFilters(docType string, filterOps ...interface{}) (elastigo.SearchResult, error) {
query := elastigo.Search(e.Index).Filter(filterOps...)
return e.conn.Search(e.Index, docType, nil, query)
}
*/
/* Raw search */
func (e *EssWrapper) Search(docType string, query interface{}) (elastigo.SearchResult, error) {
return e.conn.Search(e.Index, docType, nil, query)
}
func (e *EssWrapper) Get(docType, id string) (elastigo.BaseResponse, error) {
return e.conn.Get(e.Index, docType, id, nil)
}
func (e *EssWrapper) Delete(docType, id string) bool {
resp, err := e.conn.Delete(e.Index, docType, id, nil)
if err != nil {
log.Errorf("%s\n", err)
return false
}
return resp.Found
}
func (e *EssWrapper) GetTypes() (types []string, err error) {
var (
b []byte
)
if b, err = e.conn.DoCommand("GET", "/"+e.Index+"/_mapping", nil, nil); err != nil {
return
}
m := map[string]map[string]map[string]interface{}{}
if err = json.Unmarshal(b, &m); err != nil {
return
}
// Remove _default_ map
if _, ok := m[e.Index]["mappings"]["_default_"]; ok {
delete(m[e.Index]["mappings"], "_default_")
}
types = make([]string, len(m[e.Index]["mappings"]))
i := 0
for k, _ := range m[e.Index]["mappings"] {
types[i] = k
i++
}
return
}
/* Used to determine if the mapping file can be applied with the given version */
func (e *EssWrapper) IsVersionSupported() (supported bool) {
supported = false
info, err := e.Info()
if err != nil {
log.V(0).Infof("Could not get version: %s\n", err)
return
}
versionStr := strings.Join(strings.Split(info.Version.Number, ".")[:2], ".")
verNum, err := strconv.ParseFloat(versionStr, 64)
if err != nil {
log.V(0).Infof("Could not get version: %s\n", err)
return
}
if verNum >= 1.4 {
supported = true
}
return
}
/* Elasticsearch instance information. e.g. version */
func (e *EssWrapper) Info() (info EssInfo, err error) {
var b []byte
b, err = e.conn.DoCommand("GET", "", nil, nil)
err = json.Unmarshal(b, &info)
return
}
func (e *EssWrapper) AddWithId(docType, id string, data interface{}) (string, error) {
//log.V(10).Infof("%v\n", data)
resp, err := e.conn.Index(e.Index, docType, id, nil, data)
if err != nil {
log.Warningf("%s\n", err)
return "", err
}
if !resp.Created {
return "", fmt.Errorf("Failed: %s", resp)
}
return resp.Id, nil
}
func (e *EssWrapper) Close() {
e.conn.Close()
}
/*
Add document with auto-generated id.
*/
func (e *EssWrapper) Add(docType string, data interface{}) (string, error) {
return e.AddWithId(docType, "", data)
}
/*
Args:
docType : DTYPE_CONTAINER | DTYPE_REQUEST
id : document id
data : arbitrary data
*/
func (e *EssWrapper) Update(docType, id string, data interface{}) (string, error) {
resp, err := e.conn.Index(e.Index, docType, id, nil, data)
if err != nil {
log.Warningf("%s\n", err)
return "", err
}
log.V(10).Infof("Updated: %#v\n", data)
b, _ := json.MarshalIndent(data, "", " ")
log.V(10).Infof("Updated: %s\n", b)
log.V(10).Infof("Updated: %#v\n", resp)
return id, nil
}
func (e *EssWrapper) applyMappingFile(mapfile string) (err error) {
if !e.IsVersionSupported() {
log.Warningf("Not creating mapping. ESS version not supported. Must be > 1.4.")
return nil
}
if _, err := os.Stat(mapfile); err != nil {
log.Warningf("Not creating mapping. Mapping file not found (%s): %s", mapfile, err)
return nil
}
// Read mapping file to get map name
mdb, err := ioutil.ReadFile(mapfile)
if err != nil {
return
}
var mapData map[string]interface{}
if err = json.Unmarshal(mdb, &mapData); err != nil {
return
}
// Get map name from first key
var (
normMap = map[string]interface{}{}
mapname string
mapbytes []byte
)
for k, _ := range mapData {
normMap[k] = mapData[k]
mapname = k
break
}
if mapbytes, err = json.Marshal(normMap); err != nil {
return
}
log.V(10).Infof("Mapping (%s): %s\n", mapname, mapbytes)
if _, err = e.conn.DoCommand("PUT", fmt.Sprintf("/%s/_mapping/%s", e.Index, mapname), nil, mapbytes); err != nil {
return
}
log.Infof("Updated '%s' mapping for index '%s'\n", mapname, e.Index)
return nil
}
func (e *EssWrapper) initializeIndex(mappingFile string) error {
resp, err := e.conn.CreateIndex(e.Index)
if err != nil {
return err
}
log.V(3).Infof("Index created: %s %s\n", e.Index, resp)
if len(mappingFile) > 1 {
log.V(6).Infof("Applying mapping file: %s\n", mappingFile)
return e.applyMappingFile(mappingFile)
}
return nil
}