/
termquery.go
81 lines (57 loc) · 1.51 KB
/
termquery.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
package aggregations
import (
"context"
"errors"
"fmt"
es "github.com/elastic/go-elasticsearch/v7"
"github.com/sfomuseum/go-sfomuseum-elasticsearch/queries"
"github.com/tidwall/gjson"
"io/ioutil"
)
func TermQueryAggregation(es_client *es.Client, es_index string, label string, term string) ([]*Bucket, error) {
q, err := queries.TermQueryAggregationQuery(label, term)
if err != nil {
return nil, err
}
rsp, err := es_client.Search(
es_client.Search.WithContext(context.Background()),
es_client.Search.WithIndex(es_index),
es_client.Search.WithBody(q),
es_client.Search.WithPretty(),
)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
body, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
path := fmt.Sprintf("aggregations.%s.buckets", label)
buckets_rsp := gjson.GetBytes(body, path)
if !buckets_rsp.Exists() {
return nil, errors.New("Unable to find buckets")
}
buckets := make([]*Bucket, 0)
for _, b := range buckets_rsp.Array() {
k_rsp := b.Get("key")
c_rsp := b.Get("doc_count")
b := &Bucket{
Key: k_rsp.String(),
DocCount: c_rsp.Int(),
}
buckets = append(buckets, b)
}
return buckets, nil
}
func TermQueryAggregationKeys(es_client *es.Client, es_index string, label string, term string) ([]string, error) {
buckets, err := TermQueryAggregation(es_client, es_index, label, term)
if err != nil {
return nil, err
}
keys := make([]string, 0)
for _, b := range buckets {
keys = append(keys, b.Key)
}
return keys, nil
}