This repository has been archived by the owner on Jul 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elasticsearch.go
70 lines (55 loc) · 1.67 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
package elasticclient
import (
log "github.com/Sirupsen/logrus"
"gopkg.in/olivere/elastic.v3"
"regexp"
"strings"
)
const illegalCharactersRegexp = "[:,?<>/\\*?| ]"
type ESClient struct {
client *elastic.Client
}
func NewESClient(url string) *ESClient {
client, _ := elastic.NewSimpleClient(elastic.SetURL(url))
return &ESClient{client}
}
func (esc *ESClient) CreateIndexIfNotExist(name string) (string, error) {
validIndexName := esc.removeIllegalCharacters(name)
exist, err := esc.client.IndexExists(validIndexName).Do()
if err != nil {
log.Errorf("Failed checking if index exist %s. %+v", validIndexName, err)
}
if !exist {
_, err = esc.client.CreateIndex(validIndexName).Do()
// ignore index_already_exists_exception error, probably race condition
if err != nil && !strings.Contains(err.Error(), "index_already_exists_exception") {
log.Errorf("Failed creating index %s. %+v", validIndexName, err)
} else {
err = nil
log.Infof("Index <%s> created", validIndexName)
}
}
return validIndexName, err
}
func (esc *ESClient) Index(indexName, docType, doc string) error {
response, err := esc.client.Index().
Index(indexName).
Type(docType).
BodyString(doc).
Refresh(true).
Do()
if err != nil {
log.Errorf("Failed indexing document %s for index %s. %+v", doc, indexName, err)
} else {
log.Infof("Indexed document %s to index %s", response.Id, response.Index)
}
return err
}
func (esc *ESClient) removeIllegalCharacters(indexName string) string {
match, _ := regexp.MatchString(illegalCharactersRegexp, indexName)
if !match {
return indexName
}
r, _ := regexp.Compile(illegalCharactersRegexp)
return r.ReplaceAllString(indexName, "_")
}