Build the aggregation.

@param BucketInterface $bucket Term bucket.

@return array
544043
public function buildBucket(BucketInterface $bucket)
    {
        if ($bucket->getType() !== BucketInterface::TYPE_TERM) {
            throw new \InvalidArgumentException("Query builder : invalid aggregation type {$bucket->getType()}.");
        }

        $aggregation = ['terms' => ['field' => $bucket->getField(), 'size' => $bucket->getSize()]];

        if (is_array($bucket->getSortOrder())) {
            $aggregation['terms']['order'] = $bucket->getSortOrder();
        } elseif (in_array($bucket->getSortOrder(), [$bucket::SORT_ORDER_COUNT, $bucket::SORT_ORDER_MANUAL])) {
            $aggregation['terms']['order'] = [$bucket::SORT_ORDER_COUNT => SortOrderInterface::SORT_DESC];
        } elseif ($bucket->getSortOrder() == $bucket::SORT_ORDER_TERM) {
            $aggregation['terms']['order'] = [$bucket::SORT_ORDER_TERM => SortOrderInterface::SORT_ASC];
        } elseif ($bucket->getSortOrder() == $bucket::SORT_ORDER_RELEVANCE && !$bucket->isNested()) {
            $aggregation['aggregations']['termRelevance'] = ['avg' => ['script' => $bucket::SORT_ORDER_RELEVANCE]];
            $aggregation['terms']['order'] = ['termRelevance' => SortOrderInterface::SORT_DESC];
        }

        return $aggregation;
    }
714314
public function buildAggregations(array $buckets = [])
    {
        $aggregations = [];

        foreach ($buckets as $bucket) {
            $bucketType = $bucket->getType();
            $builder    = $this->getBuilder($bucketType);
            $aggregation     = $builder->buildBucket($bucket);
            $subAggregations = $aggregation['aggregations'] ?? [];

            if (!empty($bucket->getChildBuckets())) {
                $subAggregations = array_merge($subAggregations, $this->buildAggregations($bucket->getChildBuckets()));
            }

            foreach ($bucket->getMetrics() as $metric) {
                $subAggregations[$metric->getName()] = [$metric->getType() => ['field' => $metric->getField()]];
            }

            foreach ($bucket->getPipelines() as $pipeline) {
                $pipelineType    = $pipeline->getType();
                $pipelineBuilder = $this->getPipelineBuilder($pipelineType);
                $pipelineAgg     = $pipelineBuilder->buildPipeline($pipeline);
                $subAggregations[$pipeline->getName()] = $pipelineAgg;
            }

            if (!empty($subAggregations)) {
                $aggregation['aggregations'] = $subAggregations;
            }

            if ($bucket->isNested()) {
                if ($bucket->getNestedFilter()) {
                    $aggregation = [
                        'filter'       => $this->queryBuilder->buildQuery($bucket->getNestedFilter()),
                        'aggregations' => [$bucket->getName() => $aggregation],
                    ];
                }

                $aggregation = [
                    'nested'       => ['path' => $bucket->getNestedPath()],
                    'aggregations' => [$bucket->getName() => $aggregation],
                ];
            }

            if ($bucket->getFilter()) {
                $aggregation = [
                    'filter'       => $this->queryBuilder->buildQuery($bucket->getFilter()),
                    'aggregations' => [$bucket->getName() => $aggregation],
                ];
            }

            $aggregations[$bucket->getName()] = $aggregation;
        }

        return $aggregations;
    }
581714
private function getBuilder($bucketType)
    {
        if (!isset($this->builders[$bucketType])) {
            throw new \InvalidArgumentException("No builder found for aggregation type {$bucketType}.");
        }

        return $this->builders[$bucketType];
    }
979023
public function dropBucket($bucket){
        $err = $this->subBucketManager->dropBucket($bucket);
        if($err){
            return $this->error($err->message(), ['errorCode'=>$err->code()]);
        }
        return $this->success('操作成功');
    }
1179286
public function toArray(): array
    {
        $result = [
            $this->type => $this->script ? ['script' => $this->script] : array_merge(['field' => $this->field], $this->additionalParams),
        ];

        if ($this->subAggregations) {
            $result['aggs'] = $this->subAggregations;
        }

        return $result;
    }
1342197
private function getBucketValues($rawBucket)
    {
        $values = [];

        if (isset($rawBucket['sum_other_doc_count']) && $rawBucket['sum_other_doc_count'] > 0) {
            $rawBucket['buckets']['__other_docs']['doc_count'] = $rawBucket['sum_other_doc_count'];
        }

        foreach ($rawBucket['buckets'] as $key => $value) {
            if (isset($value['key'])) {
                $key = $value['key'];
                unset($value['key']);
            }

            $valueParams = [
                'value'        => $key,
                'metrics'      => $this->getMetrics($value),
                'aggregations' => $this->getSubAggregations($value),
            ];

            $subAggregationsNames = $valueParams['aggregations']->getBucketNames();

            foreach (array_keys($valueParams['metrics']) as $metricName) {
                if (in_array($metricName, $subAggregationsNames)) {
                    unset($valueParams['metrics'][$metricName]);
                }
            }

            $values[] = $this->valueFactory->create($valueParams);
        }

        return $values;
    }
390110
private function getAggregations()
    {
        $aggs = [];

        foreach ($this->aggregationProviders as $aggregationProvider) {
            $aggs[] = $aggregationProvider->getAggregation();
        }

        return $aggs;
    }
1325344
public function work_running($bucket = self::DEFAULT_BUCKET)
	{
		$results = array();
		foreach ($this->forked_children as $pid => $child)
		{
			if ($child['status'] != self::STOPPED && $child['bucket'] === $bucket)
			{
				$results[$pid] = $child;
			}
		}

		return $results;
	}
539431
public function aggregate(Criteria $criteria, Context $context): AggregatorResult
    {
        return $this->innerRepo->aggregate($criteria, $context);
    }
1266839
public function dropBucket($bucket)
    {
        $path = "/drop/".$bucket;
        list(, $error) = $this->rsPost($path);
        return $error;
    }
361321
public function add_bucket($bucket)
	{
		// create the bucket by copying values from the default bucket
		$this->max_children[$bucket] = $this->max_children[self::DEFAULT_BUCKET];
		$this->child_single_work_item[$bucket] = $this->child_single_work_item[self::DEFAULT_BUCKET];
		$this->max_work_per_child[$bucket] = $this->max_work_per_child[self::DEFAULT_BUCKET];
		$this->child_max_run_time[$bucket] = $this->child_max_run_time[self::DEFAULT_BUCKET];
		$this->child_single_work_item[$bucket] = $this->child_single_work_item[self::DEFAULT_BUCKET];
		$this->child_function_run[$bucket] = $this->child_function_run[self::DEFAULT_BUCKET];
		$this->parent_function_fork[$bucket] = $this->parent_function_fork[self::DEFAULT_BUCKET];
		$this->child_function_sighup[$bucket] = $this->child_function_sighup[self::DEFAULT_BUCKET];
		$this->child_function_exit[$bucket] = $this->child_function_exit[self::DEFAULT_BUCKET];
		$this->child_function_timeout[$bucket] = $this->child_function_timeout[self::DEFAULT_BUCKET];
		$this->parent_function_child_exited[$bucket] = $this->parent_function_child_exited[self::DEFAULT_BUCKET];
		$this->child_persistent_mode[$bucket] = $this->child_persistent_mode[self::DEFAULT_BUCKET];
		$this->child_persistent_mode_data[$bucket] = $this->child_persistent_mode_data[self::DEFAULT_BUCKET];
		$this->work_units[$bucket] = array();
		$this->buckets[$bucket] = $bucket;
		$this->results[$bucket] = array();
	}
76389
public function buckets() {
        if (!$this->id) {
            throw new Exception("The server has no ID, can\'t get buckets");
        }

        $bucket = new Bucket($this->patrol);

        $bucket->defaults([
            'server_id' => $this->id
        ]);

        return $bucket->all();
    }
1115336
protected function fetchBucketValue(Bucket $bucket)
    {
        if ($this->behavior & self::WEAK_VALUE) {
            assert($bucket->value instanceof WeakReference);

            return $bucket->value->get();
        }

        return $bucket->value;
    }
731101
public function aggregate($aggregation = [])
    {
        if ($aggregation instanceof Closure) {
            // Store the callback
            $callback = $aggregation;

            // Create a new pipeline
            $aggregation = new Query\Aggregation();

            // Fire the callback
            $callback($aggregation);
        }

        if ($aggregation instanceof Query\Aggregation) {
            // Retrieve the pipeline
            $aggregation = $aggregation->getPipeline();
        }

        // Execute the aggregation.
        return $this->collection->aggregate($aggregation);
    }
510787
private function buildAggregateAsObject($document)
    {
        $returnObject = [];

        foreach ($document as $event) {
            $returnObject[] = new Event(
                new AggregateUuid($event->uuid),
                $event->type,
                unserialize($event->body),
                $event->version,
                $event->occurred_on
            );
        }

        return $returnObject;
    }
608894
public function buildIndex($bucketName, $indexNames)
    {
        $sql = $this->db->getQueryBuilder()->buildIndex($bucketName, $indexNames);

        return $this->setSql($sql)->setBucketName($bucketName);
    }
411592
protected function buildSelectFromAggregation(Aggregation $aggregation)
    {
        $tableAlias = $this->getAlias();
        $rawColumns = $aggregation->getFields();
        $newSelect = $this->getLookupBuilder()->buildJoin($this, $rawColumns);
        if (false === $newSelect) {
            if (empty($tableAlias) || '*' === $rawColumns) {
                $columns = $rawColumns;
            } else {
                $columns = $tableAlias.'.'.$rawColumns;
            }
        } else {
            list($alias, $joinColumn) = $newSelect;
            $columns = $alias.'.'.$joinColumn;
        }
        $fieldsSql = $this->buildColumns($columns);
        $aggregation->setFieldsSql($fieldsSql);

        return $this->getAdapter()->quoteSql($aggregation->toSQL());
    }