-
Notifications
You must be signed in to change notification settings - Fork 49
/
elastic.go
102 lines (92 loc) · 2.13 KB
/
elastic.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
package search
import (
"bytes"
"context"
"encoding/json"
"errors"
elastic "github.com/elastic/go-elasticsearch/v7"
"github.com/tinrab/meower/schema"
)
type ElasticRepository struct {
client *elastic.Client
}
func NewElastic(url string) (*ElasticRepository, error) {
client, err := elastic.NewClient(elastic.Config{
Addresses: []string{url},
})
if err != nil {
return nil, err
}
_, err = client.Info()
if err != nil {
return nil, err
}
return &ElasticRepository{client}, nil
}
func (r *ElasticRepository) Close() {
}
func (r *ElasticRepository) InsertMeow(ctx context.Context, meow schema.Meow) error {
body, _ := json.Marshal(meow)
_, err := r.client.Index(
"meows",
bytes.NewReader(body),
r.client.Index.WithDocumentID(meow.ID),
r.client.Index.WithRefresh("wait_for"),
)
return err
}
func (r *ElasticRepository) SearchMeows(ctx context.Context, query string, skip uint64, take uint64) (result []schema.Meow, err error) {
var buf bytes.Buffer
reqBody := map[string]interface{}{
"query": map[string]interface{}{
"multi_match": map[string]interface{}{
"query": query,
"fields": []string{"body"},
"fuzziness": 3,
"cutoff_frequency": 0.0001,
},
},
}
if err = json.NewEncoder(&buf).Encode(reqBody); err != nil {
return nil, err
}
res, err := r.client.Search(
r.client.Search.WithContext(ctx),
r.client.Search.WithIndex("meows"),
r.client.Search.WithFrom(int(skip)),
r.client.Search.WithSize(int(take)),
r.client.Search.WithBody(&buf),
r.client.Search.WithTrackTotalHits(true),
)
if err != nil {
return nil, err
}
defer func() {
if err = res.Body.Close(); err != nil {
result = nil
}
}()
if res.IsError() {
return nil, errors.New("search failed")
}
type Response struct {
Took int64
Hits struct {
Total struct {
Value int64
}
Hits []*struct {
Source schema.Meow `json:"_source"`
}
}
}
resBody := Response{}
if err := json.NewDecoder(res.Body).Decode(&resBody); err != nil {
return nil, err
}
var meows []schema.Meow
for _, hit := range resBody.Hits.Hits {
meows = append(meows, hit.Source)
}
return meows, nil
}