-
Notifications
You must be signed in to change notification settings - Fork 7
/
aggreg.go
59 lines (50 loc) · 1.31 KB
/
aggreg.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
package logic
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os4gophers/domain"
"github.com/opensearch-project/opensearch-go"
)
func MovieCountPerGenreAgg(ctx context.Context) {
client := ctx.Value(domain.ClientKey).(*opensearch.Client)
var searchBuffer bytes.Buffer
aggregRequest := domain.AggregationRequest{
Size: 0,
Aggs: &domain.Aggs{
MovieCountPerGenre: &domain.MovieCountPerGenreRequest{
Terms: &domain.Terms{
Field: "genres.keyword",
Size: 5,
},
},
},
}
err := json.NewEncoder(&searchBuffer).Encode(aggregRequest)
if err != nil {
panic(err)
}
response, err := client.Search(
client.Search.WithContext(ctx),
client.Search.WithIndex("movies"),
client.Search.WithBody(&searchBuffer),
client.Search.WithTrackTotalHits(true),
client.Search.WithPretty(),
)
if err != nil {
panic(err)
}
defer response.Body.Close()
var aggregResponse = domain.AggregationResponse{}
err = json.NewDecoder(response.Body).Decode(&aggregResponse)
if err != nil {
panic(err)
}
if len(aggregResponse.Aggregations.MovieCountPerGenreResponse.Buckets) > 0 {
fmt.Printf("✅ Top 5 Genres and their Movie Count: \n")
for _, bucket := range aggregResponse.Aggregations.MovieCountPerGenreResponse.Buckets {
fmt.Printf(" 🚀 %s = %d\n", bucket.Key, bucket.DocumentCount)
}
}
}