-
Notifications
You must be signed in to change notification settings - Fork 1
/
elastic_search.go
131 lines (115 loc) · 2.55 KB
/
elastic_search.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
package main
// Elastic search client
import (
"context"
"fmt"
"log"
"reflect"
"time"
"github.com/olivere/elastic"
)
const (
indexName = "pages"
indexMapping = `{
"settings":{
"number_of_shards":1,
"number_of_replicas":0
},
"mappings":{
"page":{
"properties":{
"title": {
"type":"text"
},
"description": {
"type":"text"
},
"body": {
"type":"text"
},
"url": {
"type":"text"
}
}
}
}
}`
)
var client *elastic.Client
// NewElasticSearchClient returns an elastic seach client
func NewElasticSearchClient() *elastic.Client {
var err error
connected := false
retries := 0
// Custom retry strategy for docker-compose initialization
for connected == false {
// Create a new elastic client
client, err = elastic.NewClient(
elastic.SetURL("http://elasticsearch:9200"), elastic.SetSniff(false))
if err != nil {
// log.Fatal(err)
if retries == 5 {
log.Fatal(err)
}
fmt.Println("Elasticsearch isn't ready for connection", 5-retries, "less")
retries++
time.Sleep(3 * time.Second)
} else {
connected = true
}
}
// Getting the ES version number is quite common, so there's a shortcut
esversion, err := client.ElasticsearchVersion("http://elasticsearch:9200")
if err != nil {
// Handle error
panic(err)
}
fmt.Printf("Elasticsearch version %s\n", esversion)
return client
}
// ExistsIndex checks if the given index exists or not
func ExistsIndex(i string) bool {
// Check if index exists
exists, err := client.IndexExists(i).Do(context.TODO())
if err != nil {
log.Fatal(err)
}
return exists
}
// CreateIndex creates a new index
func CreateIndex(i string) {
createIndex, err := client.CreateIndex(indexName).
Body(indexMapping).
Do(context.Background())
if err != nil {
fmt.Println(err)
return
}
if !createIndex.Acknowledged {
log.Println("CreateIndex was not acknowledged. Check that timeout value is correct.")
}
}
// SearchContent returns the results for a given query
func SearchContent(input string) []Page {
pages := []Page{}
ctx := context.Background()
// Search for a page in the database using multi match query
q := elastic.NewMultiMatchQuery(input, "title", "description", "body", "url").
Type("most_fields").
Fuzziness("2")
result, err := client.Search().
Index(indexName).
Query(q).
From(0).Size(20).
Sort("_score", false).
Do(ctx)
if err != nil {
log.Fatal(err)
}
var ttyp Page
for _, page := range result.Each(reflect.TypeOf(ttyp)) {
p := page.(Page)
pages = append(pages, p)
}
return pages
}