-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathelasticsearch.go
More file actions
79 lines (59 loc) · 2.21 KB
/
Copy pathelasticsearch.go
File metadata and controls
79 lines (59 loc) · 2.21 KB
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
package main
import (
"encoding/json"
"gopkg.in/olivere/elastic.v3"
"log"
"net/url"
"os"
"time"
)
// ElasticsearchTextClient is the ES client to the main index.
var ElasticsearchTextClient *elastic.Client
// ElasticsearchDocsClient is the ES client to the document store.
var ElasticsearchDocsClient *elastic.Client
// ElasticsearchConnect sets up persistent connections to both ES servers.
func ElasticsearchConnect() {
ElasticsearchTextClient = ElasticsearchConnectServer(Config.ElasticsearchText)
ElasticsearchDocsClient = ElasticsearchConnectServer(Config.ElasticsearchDocs)
}
// ElasticsearchConnectServer connects one single client to its ES server.
func ElasticsearchConnectServer(url string) *elastic.Client {
client, err := elastic.NewClient(
elastic.SetSniff(false),
elastic.SetURL(url),
elastic.SetHealthcheck(false),
elastic.SetSniff(false),
elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC: ", log.LstdFlags)))
// elastic.SetTraceLog(log.New(os.Stderr, "ELASTIC: ", log.LstdFlags)),
// elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags))
if err != nil {
// Don't panic, this might be a temporary failure.
log.Println("Connection to Elasticsearch failed:", err)
}
// We must do this to allow having an unconnected client instance,
// and throw proper errors instead of panicking at startup.
client.Stop()
_ = elastic.SetHealthcheck(true)(client)
_ = elastic.SetSniff(true)(client)
client.Start()
return client
}
// ElasticsearchRequest sends a POST request to an ES server and parses the returned JSON.
func ElasticsearchRequest(client *elastic.Client, path string, body string) (*elastic.SearchResult, time.Duration, error) {
if client == nil {
return nil, 0, elastic.ErrNoClient
}
// This is measured on our side in addition to the ElasticSearch-provided SearchResult.TookInMillis
// It is a good measure of the network & deserialization overhead.
start := time.Now()
params := make(url.Values)
res, err := client.PerformRequest("POST", path, params, body)
if err != nil {
return nil, time.Since(start), err
}
ret := new(elastic.SearchResult)
if err := json.Unmarshal(res.Body, ret); err != nil {
return nil, time.Since(start), err
}
return ret, time.Since(start), nil
}