erichard / elasticsearch-query-builder

Build query for an ElasticSearch client using a fluent interface
MIT License
39 stars 20 forks source link

Feature request: Composite Aggregation #21

Open igoooor opened 1 year ago

igoooor commented 1 year ago

Hello there,

I believe that "composite aggregations" are currently missing in v3 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-composite-aggregation.html

This is currently the class I built to handle that, it is very basic at the moment so all cases might not be covered. And I'm not sure if it follows the logic you have in your other aggregations but at least it might give an idea

<?php

declare(strict_types=1);

namespace Core\Search\Model\Search\DQL;

use Erichard\ElasticQueryBuilder\Aggregation\AbstractAggregation;

class CompositeAggregation extends AbstractAggregation
{
    public function __construct(
        string $name,
        private array $aggregations,
        private int $size = 10,
    ) {
        parent::__construct($name, []);
    }

    protected function buildAggregation(): array
    {
        $build = [];
        foreach ($this->aggregations as $aggregation) {
            $build[] = [
                $aggregation => [
                    'terms' => [
                        'field' => $aggregation,
                    ],
                ],
            ];
        }

        return [
            'sources' => $build,
            'size' => $this->size,
        ];
    }

    protected function getType(): string
    {
        return 'composite';
    }
}
erichard commented 1 year ago

Hi !

The logic in v3 is:

For your Composite aggregation the only required property is source which seems similar but yet different from a real aggregation. Size should be handle with getter/setter.

Although similar, the terms value source doesn’t support the same set of parameters as the terms aggregation.

igoooor commented 1 year ago

Would you like me to adapt it based on your comments and open a PR?

erichard commented 1 year ago

Yes ! You are totally welcome to make a PR 👍