// Aggregation adds an aggreation to perform as part of the search.
969043
func (s *SearchService) Aggregation(name string, aggregation Aggregation) *SearchService {
	s.searchSource = s.searchSource.Aggregation(name, aggregation)
	return s
}
658540
func (a *AggregateResult) Avg(field string) float64 {
	sum := a.Sum(field)
	return sum / float64(len(a.reduction))
}
74245
func (s *Sensu) GetAggregatesSlice(limit int, offset int) ([]interface{}, error) {
	return s.getList("aggregates", limit, offset)
}
903974
func Aggregate(t *testing.T, repo grimoire.Repo) {
	// preparte tests data
	user := User{Name: "name1", Gender: "male", Age: 10}
	repo.From(users).MustSave(&user)

	tests := []grimoire.Query{
		repo.From(users).Where(c.Eq(id, user.ID)),
		repo.From(users).Where(c.Eq(name, "name1")),
		repo.From(users).Where(c.Eq(age, 10)),
		repo.From(users).Where(c.Eq(id, user.ID), c.Eq(name, "name1")),
		repo.From(users).Where(c.Eq(id, user.ID), c.Eq(name, "name1"), c.Eq(age, 10)),
		repo.From(users).Where(c.Eq(id, user.ID)).OrWhere(c.Eq(name, "name1")),
		repo.From(users).Where(c.Eq(id, user.ID)).OrWhere(c.Eq(name, "name1"), c.Eq(age, 10)),
		repo.From(users).Where(c.Eq(id, user.ID)).OrWhere(c.Eq(name, "name1")).OrWhere(c.Eq(age, 10)),
		repo.From(users).Where(c.Ne(gender, "male")),
		repo.From(users).Where(c.Gt(age, 59)),
		repo.From(users).Where(c.Gte(age, 60)),
		repo.From(users).Where(c.Lt(age, 11)),
		repo.From(users).Where(c.Lte(age, 10)),
		repo.From(users).Where(c.Nil(note)),
		repo.From(users).Where(c.NotNil(name)),
		repo.From(users).Where(c.In(id, 1, 2, 3)),
		repo.From(users).Where(c.Nin(id, 1, 2, 3)),
		repo.From(users).Where(c.Like(name, "name%")),
		repo.From(users).Where(c.NotLike(name, "noname%")),
		repo.From(users).Where(c.Fragment("id > 0")),
		repo.From(users).Where(c.Not(c.Eq(id, 1), c.Eq(name, "name1"), c.Eq(age, 10))),
		repo.From(users).Group("gender"),
		repo.From(users).Group("age").Having(c.Gt(age, 10)),
	}

	for _, query := range tests {
		field := "id"

		statement, _ := builder.Find(query.Select("count(" + field + ") AS count"))
		t.Run("Aggregate|"+statement, func(t *testing.T) {
			var counts []struct {
				Count int
			}

			err := query.Aggregate("count", field, &counts)
			assert.True(t, len(counts) > 0)
			assert.Nil(t, err)

			var sums []struct {
				Sum int
			}

			err = query.Aggregate("sum", field, &sums)
			assert.True(t, len(sums) > 0)
			assert.Nil(t, err)

		})
	}
}
418213
func AggBoundary(ts uint32, span uint32) uint32 {
	return ts + span - ((ts-1)%span + 1)
}
1025585
func (b Bucket) Aggregation(name string) Aggregation {
	if agg, ok := b[name]; ok {
		return agg.(map[string]interface{})
	} else {
		return Aggregation{}
	}
}
983641
func NewAggregator() *Aggregator {
	a := &Aggregator{
		buffers: make(map[string]*buffer.Buffer),
		msgc:    make(chan *rfc5424.Message, 1000),
		pausec:  make(chan struct{}),
	}
	go a.run()
	return a
}
1249246
func (sink *influxdbSink) aggregationFunc(aggregationName core.AggregationType, fieldName string) string {
	switch aggregationName {
	case core.AggregationTypeAverage:
		return fmt.Sprintf("MEAN(%q)", fieldName)
	case core.AggregationTypeMaximum:
		return fmt.Sprintf("MAX(%q)", fieldName)
	case core.AggregationTypeMinimum:
		return fmt.Sprintf("MIN(%q)", fieldName)
	case core.AggregationTypeMedian:
		return fmt.Sprintf("MEDIAN(%q)", fieldName)
	case core.AggregationTypeCount:
		return fmt.Sprintf("COUNT(%q)", fieldName)
	case core.AggregationTypePercentile50:
		return fmt.Sprintf("PERCENTILE(%q, 50)", fieldName)
	case core.AggregationTypePercentile95:
		return fmt.Sprintf("PERCENTILE(%q, 95)", fieldName)
	case core.AggregationTypePercentile99:
		return fmt.Sprintf("PERCENTILE(%q, 99)", fieldName)
	}

	// This should have been checked by the API level, so something's seriously wrong here
	panic(fmt.Sprintf("Unknown aggregation type %q", aggregationName))
}
306013
func (a *AggregationBucketRangeItem) UnmarshalJSON(data []byte) error {
	var aggs map[string]json.RawMessage
	if err := json.Unmarshal(data, &aggs); err != nil {
		return err
	}
	if v, ok := aggs["key"]; ok && v != nil {
		json.Unmarshal(v, &a.Key)
	}
	if v, ok := aggs["doc_count"]; ok && v != nil {
		json.Unmarshal(v, &a.DocCount)
	}
	if v, ok := aggs["from"]; ok && v != nil {
		json.Unmarshal(v, &a.From)
	}
	if v, ok := aggs["from_as_string"]; ok && v != nil {
		json.Unmarshal(v, &a.FromAsString)
	}
	if v, ok := aggs["to"]; ok && v != nil {
		json.Unmarshal(v, &a.To)
	}
	if v, ok := aggs["to_as_string"]; ok && v != nil {
		json.Unmarshal(v, &a.ToAsString)
	}
	a.Aggregations = aggs
	return nil
}
33973
func addAggregationRoutes(a metricsAggregationFetcher, ws *restful.WebService) {
	// The /metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for the Cluster entity of the historical API.
	ws.Route(ws.GET("/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("clusterMetrics", a.clusterAggregations)).
		Doc("Export some cluster-level metric aggregations").
		Operation("clusterAggregations").
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	// The /nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations for a Node entity of the historical API.
	// The {node-name} parameter is the hostname of a specific node.
	ws.Route(ws.GET("/nodes/{node-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("nodeMetrics", a.nodeAggregations)).
		Doc("Export a node-level metric").
		Operation("nodeAggregations").
		Param(ws.PathParameter("node-name", "The name of the node to lookup").DataType("string")).
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metric").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	if a.isRunningInKubernetes() {
		// The /namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes some aggregations
		// for a Namespace entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("namespaceMetrics", a.namespaceAggregations)).
			Doc("Export some namespace-level metric aggregations").
			Operation("namespaceAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Pod entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)).
			Doc("Export some pod-level metric aggregations").
			Operation("podAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Container entity of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pods/{pod-name}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)).
			Doc("Export some aggregations for a Pod Container").
			Operation("podContainerAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("pod-name", "The name of the pod to use").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Pod entity of the historical API.
		ws.Route(ws.GET("/pod-id/{pod-id}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podMetrics", a.podAggregations)).
			Doc("Export some pod-level metric aggregations").
			Operation("podAggregations").
			Param(ws.PathParameter("pod-id", "The UID of the pod to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))

		// The /pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// some aggregations for a Container entity of the historical API.
		ws.Route(ws.GET("/pod-id/{pod-id}/containers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podContainerMetrics", a.podContainerAggregations)).
			Doc("Export some aggregations for a Pod Container").
			Operation("podContainerAggregations").
			Param(ws.PathParameter("pod-id", "The name of the pod to use").DataType("string")).
			Param(ws.PathParameter("container-name", "The name of the namespace to use").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResult{}))
	}

	// The /nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
	// some aggregations for a free Container entity of the historical API.
	ws.Route(ws.GET("/nodes/{node-name}/freecontainers/{container-name}/metrics-aggregated/{aggregations}/{metric-name:*}").
		To(metrics.InstrumentRouteFunc("freeContainerMetrics", a.freeContainerAggregations)).
		Doc("Export a contsome iner-level metric aggregations for a free container").
		Operation("freeContainerAggregations").
		Param(ws.PathParameter("node-name", "The name of the node to use").DataType("string")).
		Param(ws.PathParameter("container-name", "The name of the container to use").DataType("string")).
		Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
		Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
		Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
		Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
		Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
		Writes(types.MetricAggregationResult{}))

	if a.isRunningInKubernetes() {
		// The /namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// metrics for a list of pods of the historical API.
		ws.Route(ws.GET("/namespaces/{namespace-name}/pod-list/{pod-list}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)).
			Doc("Export some aggregations for all pods from the given list").
			Operation("podListAggregations").
			Param(ws.PathParameter("namespace-name", "The name of the namespace to lookup").DataType("string")).
			Param(ws.PathParameter("pod-list", "Comma separated list of pod names to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResultList{}))

		// The /pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name} endpoint exposes
		// metrics for a list of pod ids of the historical API.
		ws.Route(ws.GET("/pod-id-list/{pod-id-list}/metrics-aggregated/{aggregations}/{metric-name:*}").
			To(metrics.InstrumentRouteFunc("podListAggregations", a.podListAggregations)).
			Doc("Export an aggregation for all pods from the given list").
			Operation("podListAggregations").
			Param(ws.PathParameter("pod-id-list", "Comma separated list of pod UIDs to lookup").DataType("string")).
			Param(ws.PathParameter("aggregations", "A comma-separated list of requested aggregations").DataType("string")).
			Param(ws.PathParameter("metric-name", "The name of the requested metric").DataType("string")).
			Param(ws.QueryParameter("start", "Start time for requested metrics").DataType("string")).
			Param(ws.QueryParameter("end", "End time for requested metric").DataType("string")).
			Param(ws.QueryParameter("labels", "A comma-separated list of key:values pairs to use to search for a labeled metric").DataType("string")).
			Writes(types.MetricAggregationResultList{}))
	}
}
795769
func (a *AggregateResult) Group(result ...interface{}) {
	for i := range result {
		resultVal := reflect.ValueOf(result[i])
		if resultVal.Kind() != reflect.Ptr {
			panic("result argument must be an address")
		}

		if i >= len(a.group) {
			panic(fmt.Sprintf("There is not %d elements in the grouping", i))
		}

		resultVal.Elem().Set(a.group[i])
	}
}
1262315
func (dg *discoveryGateway) GetAggregateStats(target *querypb.Target) (*querypb.AggregateStats, queryservice.QueryService, error) {
	stats, err := dg.tsc.GetAggregateStats(target)
	return stats, dg, err
}
37982
func (b *SearchRequestBuilder) Agg() AggBuilder {
	aggBuilder := newAggBuilder(b.version)
	b.aggBuilders = append(b.aggBuilders, aggBuilder)
	return aggBuilder
}
895936
func (builder *Builder) Aggregate(q grimoire.Query) (string, []interface{}) {
	qs, args := builder.query(q)
	field := q.AggregateMode + "(" + q.AggregateField + ") AS " + q.AggregateMode

	return builder.fields(false, append(q.GroupFields, field)...) + qs, args
}
954129
func (a *aggregationPushDownSolver) aggPushDown(p LogicalPlan) LogicalPlan {
	if agg, ok := p.(*LogicalAggregation); ok {
		proj := a.tryToEliminateAggregation(agg)
		if proj != nil {
			p = proj
		} else {
			child := agg.children[0]
			if join, ok1 := child.(*LogicalJoin); ok1 && a.checkValidJoin(join) {
				if valid, leftAggFuncs, rightAggFuncs, leftGbyCols, rightGbyCols := a.splitAggFuncsAndGbyCols(agg, join); valid {
					var lChild, rChild LogicalPlan
					// If there exist count or sum functions in left join path, we can't push any
					// aggregate function into right join path.
					rightInvalid := a.checkAnyCountAndSum(leftAggFuncs)
					leftInvalid := a.checkAnyCountAndSum(rightAggFuncs)
					if rightInvalid {
						rChild = join.children[1]
					} else {
						rChild = a.tryToPushDownAgg(rightAggFuncs, rightGbyCols, join, 1)
					}
					if leftInvalid {
						lChild = join.children[0]
					} else {
						lChild = a.tryToPushDownAgg(leftAggFuncs, leftGbyCols, join, 0)
					}
					join.SetChildren(lChild, rChild)
					join.SetSchema(expression.MergeSchema(lChild.Schema(), rChild.Schema()))
					join.buildKeyInfo()
					proj := a.tryToEliminateAggregation(agg)
					if proj != nil {
						p = proj
					}
				}
			} else if proj, ok1 := child.(*LogicalProjection); ok1 {
				// TODO: This optimization is not always reasonable. We have not supported pushing projection to kv layer yet,
				// so we must do this optimization.
				for i, gbyItem := range agg.GroupByItems {
					agg.GroupByItems[i] = expression.ColumnSubstitute(gbyItem, proj.schema, proj.Exprs)
				}
				agg.collectGroupByColumns()
				for _, aggFunc := range agg.AggFuncs {
					newArgs := make([]expression.Expression, 0, len(aggFunc.Args))
					for _, arg := range aggFunc.Args {
						newArgs = append(newArgs, expression.ColumnSubstitute(arg, proj.schema, proj.Exprs))
					}
					aggFunc.Args = newArgs
				}
				projChild := proj.children[0]
				agg.SetChildren(projChild)
			} else if union, ok1 := child.(*LogicalUnionAll); ok1 {
				var gbyCols []*expression.Column
				gbyCols = expression.ExtractColumnsFromExpressions(gbyCols, agg.GroupByItems, nil)
				pushedAgg := a.makeNewAgg(agg.ctx, agg.AggFuncs, gbyCols)
				newChildren := make([]LogicalPlan, 0, len(union.children))
				for _, child := range union.children {
					newChild := a.pushAggCrossUnion(pushedAgg, union.Schema(), child)
					newChildren = append(newChildren, newChild)
				}
				union.SetSchema(expression.NewSchema(newChildren[0].Schema().Columns...))
				union.SetChildren(newChildren...)
			}
		}
	}
	newChildren := make([]LogicalPlan, 0, len(p.Children()))
	for _, child := range p.Children() {
		newChild := a.aggPushDown(child)
		newChildren = append(newChildren, newChild)
	}
	p.SetChildren(newChildren...)
	return p
}
348909
func getAggregations(request *restful.Request) ([]core.AggregationType, error) {
	aggregationsRaw := strings.Split(request.PathParameter("aggregations"), ",")
	if len(aggregationsRaw) == 0 {
		return nil, fmt.Errorf("No aggregations specified")
	}

	aggregations := make([]core.AggregationType, len(aggregationsRaw))

	for ind, aggNameRaw := range aggregationsRaw {
		aggName := core.AggregationType(aggNameRaw)
		if _, ok := core.AllAggregations[aggName]; !ok {
			return nil, fmt.Errorf("Unknown aggregation %q", aggName)
		}
		aggregations[ind] = aggName
	}

	return aggregations, nil
}
988579
func Flatten(agg Aggregate) Aggregate {
	result := []error{}
	if agg == nil {
		return nil
	}
	for _, err := range agg.Errors() {
		if a, ok := err.(Aggregate); ok {
			r := Flatten(a)
			if r != nil {
				result = append(result, r.Errors()...)
			}
		} else {
			if err != nil {
				result = append(result, err)
			}
		}
	}
	return NewAggregate(result)
}