1package elastic
2
3type GeoHashGridAggregation struct {
4	field           string
5	precision       int
6	size            int
7	shardSize       int
8	subAggregations map[string]Aggregation
9	meta            map[string]interface{}
10}
11
12func NewGeoHashGridAggregation() *GeoHashGridAggregation {
13	return &GeoHashGridAggregation{
14		subAggregations: make(map[string]Aggregation),
15		precision:       -1,
16		size:            -1,
17		shardSize:       -1,
18	}
19}
20
21func (a *GeoHashGridAggregation) Field(field string) *GeoHashGridAggregation {
22	a.field = field
23	return a
24}
25
26func (a *GeoHashGridAggregation) Precision(precision int) *GeoHashGridAggregation {
27	a.precision = precision
28	return a
29}
30
31func (a *GeoHashGridAggregation) Size(size int) *GeoHashGridAggregation {
32	a.size = size
33	return a
34}
35
36func (a *GeoHashGridAggregation) ShardSize(shardSize int) *GeoHashGridAggregation {
37	a.shardSize = shardSize
38	return a
39}
40
41func (a *GeoHashGridAggregation) SubAggregation(name string, subAggregation Aggregation) *GeoHashGridAggregation {
42	a.subAggregations[name] = subAggregation
43	return a
44}
45
46func (a *GeoHashGridAggregation) Meta(metaData map[string]interface{}) *GeoHashGridAggregation {
47	a.meta = metaData
48	return a
49}
50
51func (a *GeoHashGridAggregation) Source() (interface{}, error) {
52	// Example:
53	// {
54	//     "aggs": {
55	//         "new_york": {
56	//             "geohash_grid": {
57	//                 "field": "location",
58	//                 "precision": 5
59	//             }
60	//         }
61	//     }
62	// }
63
64	source := make(map[string]interface{})
65	opts := make(map[string]interface{})
66	source["geohash_grid"] = opts
67
68	if a.field != "" {
69		opts["field"] = a.field
70	}
71
72	if a.precision != -1 {
73		opts["precision"] = a.precision
74	}
75
76	if a.size != -1 {
77		opts["size"] = a.size
78	}
79
80	if a.shardSize != -1 {
81		opts["shard_size"] = a.shardSize
82	}
83
84	// AggregationBuilder (SubAggregations)
85	if len(a.subAggregations) > 0 {
86		aggsMap := make(map[string]interface{})
87		source["aggregations"] = aggsMap
88		for name, aggregate := range a.subAggregations {
89			src, err := aggregate.Source()
90			if err != nil {
91				return nil, err
92			}
93			aggsMap[name] = src
94		}
95	}
96
97	if len(a.meta) > 0 {
98		source["meta"] = a.meta
99	}
100
101	return source, nil
102}
103