Repository navigation
Expand file tree
/
Copy pathsearch.go
More file actions
118 lines (100 loc) · 2.28 KB
/
Copy pathsearch.go
File metadata and controls
118 lines (100 loc) · 2.28 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
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
package es
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Search struct {
Query interface{} `json:"query"`
Fields []string `json:"stored_fields,omitempty"`
}
type BoolQuery struct {
And []interface{}
Or []interface{}
MinimumOr int
}
func (q BoolQuery) MarshalJSON() ([]byte, error) {
qq := struct {
And []interface{} `json:"must,omitempty"`
Or []interface{} `json:"should,omitempty"`
MinimumOr int `json:"minimum_should_match"`
}(q)
v := struct {
Bool interface{} `json:"bool"`
}{qq}
return json.Marshal(v)
}
type Term struct {
Key string
Value interface{}
Boost float64
}
func (t Term) MarshalJSON() ([]byte, error) {
type value struct {
Value interface{} `json:"value"`
Boost float64 `json:"boost,omitempty"`
}
v := struct {
Term map[string]value `json:"term"`
}{
map[string]value{t.Key: value{t.Value, t.Boost}},
}
return json.Marshal(v)
}
type Match struct {
Key string
Value interface{}
}
func (m Match) MarshalJSON() ([]byte, error) {
type value struct {
Query interface{} `json:"query"`
}
v := struct {
Match map[string]value `json:"match"`
}{
map[string]value{m.Key: value{m.Value}},
}
return json.Marshal(v)
}
type SearchHit struct {
Index string `json:"_index"`
Type string `json:"_type"`
ID string `json:"_id"`
Score float64 `json:"_score"`
Source json.RawMessage `json:"_source"`
Fields json.RawMessage `json:"fields"`
}
type searchHits struct {
Hits []SearchHit `json:"hits"`
}
type searchResult struct {
Hits searchHits `json:"hits"`
}
func (client *Client) Search(s Search, count int) ([]SearchHit, error) {
b, err := json.Marshal(s)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s/_search?size=%d", client.Base, client.Index, count), bytes.NewReader(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
if err, ok := err.(APIError); ok {
if err.Err.Type == "index_not_found_exception" {
return nil, nil
}
}
return nil, err
}
defer resp.Body.Close()
res := searchResult{}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return nil, err
}
return res.Hits.Hits, nil
}