Files
opencloud/services/search/pkg/aggregation/metric.go
T
Dominik Schmidt 48867e07f1 feat(search): add metric aggregations
sum/min/max/avg over a numeric field: bleve folds the accumulators from doc values, OpenSearch reads them from a stats aggregation, the service layer reduces them to the value of the kind after the cross-space merge. The proto gains MetricDefinition, MetricKind and Metric, which travels as accumulators (sum, count, min, max) so the merge works whatever the kind; value is set after the merge and absent for a metric without a single value. A metric is only valid on a numeric field, and only one of bucketDefinition and metricDefinition at a time. AGG-06, 18 and 21 in the parity suite.
2026-11-27 15:51:25 +01:00

43 lines
1.2 KiB
Go

package aggregation
import (
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
)
// Observe adds a field value to the accumulators of m.
func Observe(m *searchsvc.Metric, v float64) {
add(m, &searchsvc.Metric{Sum: v, Count: 1, Min: v, Max: v})
}
func add(into, from *searchsvc.Metric) {
if from.GetCount() == 0 {
return
}
if into.GetCount() == 0 {
into.Min, into.Max = from.GetMin(), from.GetMax()
} else {
into.Min, into.Max = min(into.GetMin(), from.GetMin()), max(into.GetMax(), from.GetMax())
}
into.Sum += from.GetSum()
into.Count += from.GetCount()
}
// MetricValue reduces the accumulators to the value of the metric's kind;
// there is none without a single observed value.
func MetricValue(m *searchsvc.Metric) (float64, bool) {
if m.GetCount() == 0 {
return 0, false
}
switch m.GetKind() {
case searchsvc.MetricKind_METRIC_KIND_SUM:
return m.GetSum(), true
case searchsvc.MetricKind_METRIC_KIND_MIN:
return m.GetMin(), true
case searchsvc.MetricKind_METRIC_KIND_MAX:
return m.GetMax(), true
case searchsvc.MetricKind_METRIC_KIND_AVG:
return m.GetSum() / float64(m.GetCount()), true
}
return 0, false
}