From d7b63f8c81475269dbe4bdac8b23e0e37dfe2f92 Mon Sep 17 00:00:00 2001 From: Bart van Asselt Date: Thu, 25 Apr 2024 09:56:18 +0200 Subject: [PATCH] Add support for nested aggregations --- src/Application/Results.php | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/Application/Results.php b/src/Application/Results.php index 2a93531..8c18bc0 100644 --- a/src/Application/Results.php +++ b/src/Application/Results.php @@ -5,6 +5,9 @@ namespace JeroenG\Explorer\Application; use Countable; +use function array_key_exists; +use function array_merge; +use function is_array; class Results implements Countable { @@ -31,11 +34,7 @@ public function aggregations(): array foreach ($this->rawResults['aggregations'] as $name => $rawAggregation) { if (array_key_exists('doc_count', $rawAggregation)) { - foreach ($rawAggregation as $nestedAggregationName => $rawNestedAggregation) { - if (isset($rawNestedAggregation['buckets'])) { - $aggregations[] = new AggregationResult($nestedAggregationName, $rawNestedAggregation['buckets']); - } - } + $aggregations = array_merge($aggregations, $this->parseNestedAggregation($rawAggregation)); continue; } @@ -49,4 +48,22 @@ public function count(): int { return $this->rawResults['hits']['total']['value']; } + + /** @return AggregationResult[] */ + private function parseNestedAggregation(array $rawAggregation): array { + $aggregations = []; + if (array_key_exists('doc_count', $rawAggregation)) { + foreach ($rawAggregation as $nestedAggregationName => $rawNestedAggregation) { + if (isset($rawNestedAggregation['buckets'])) { + $aggregations[] = new AggregationResult($nestedAggregationName, $rawNestedAggregation['buckets']); + } + + if(is_array($rawNestedAggregation)) { + $aggregations = array_merge($aggregations, $this->parseNestedAggregation($rawNestedAggregation)); + } + } + } + + return $aggregations; + } }