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;
    }