Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,15 @@ AggregationInterface ─┬─ TermsAggregation (uses FilterableAggregation, Glo
├─ HistogramAggregation (uses FilterableAggregation, GlobalizableAggregation)
├─ SumAggregation (uses FilterableAggregation, GlobalizableAggregation)
├─ CardinalityAggregation (uses FilterableAggregation, GlobalizableAggregation)
├─ DateHistogramAggregation (uses FilterableAggregation, GlobalizableAggregation)
└─ CompositeAggregation [abstract] ─ user-defined composites

SortInterface ─┬─ FieldSort
└─ ScoreSort

Exception hierarchy:
QueryException [abstract] ─ EmptyBoolQueryException, EmptyNestedQueryException, EmptyRangeQueryException, EmptyTermsQueryException, InvalidOperatorQueryException, InvalidRelationQueryException
AggregationException [abstract] ─ DuplicatedContainerAggregationException, DuplicatedNestedAggregationException, InvalidAggregationSizeException, InvalidContainerAggregationException, InvalidIntervalException, InvalidPrecisionThresholdException, NotEnoughFieldsAggregationException
AggregationException [abstract] ─ DuplicatedContainerAggregationException, DuplicatedNestedAggregationException, InvalidAggregationSizeException, InvalidContainerAggregationException, InvalidDateHistogramIntervalException, InvalidIntervalException, InvalidPrecisionThresholdException, NotEnoughFieldsAggregationException
BuilderException [abstract] ─ DuplicatedBuilderAggregationException, InvalidFromException, InvalidSizeException
```

Expand Down
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ new HistogramAggregation('price_histogram', 'price', 10);
new HistogramAggregation('price_histogram', 'price', 50, 1);
```

<<<<<<< HEAD
### SumAggregation

https://www.elastic.co/docs/reference/aggregations/search-aggregations-metrics-sum-aggregation
Expand Down Expand Up @@ -361,6 +362,31 @@ new CardinalityAggregation('active_unique_brands', 'brand.keyword')
->query(new TermQuery('status', 'active'));
```

### DateHistogramAggregation

https://www.elastic.co/docs/reference/aggregations/search-aggregations-bucket-datehistogram-aggregation

```php
use Bonu\ElasticsearchBuilder\Aggregation\DateHistogramAggregation;

// Monthly buckets using calendar interval
new DateHistogramAggregation('sales_over_time', 'date', calendarInterval: 'month');

// Fixed 30-day intervals with date format
new DateHistogramAggregation('monthly_sales', 'date', fixedInterval: '30d', format: 'yyyy-MM-dd');

// With all options: calendar interval, min_doc_count, format, time zone, offset
new DateHistogramAggregation(
'hourly_activity',
'timestamp',
calendarInterval: 'hour',
minDocCount: 1,
format: 'yyyy-MM-dd HH:mm',
timeZone: 'Europe/Prague',
offset: '+6h',
);
```

## Sorts

### FieldSort
Expand Down
1 change: 1 addition & 0 deletions src/Aggregation/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Aggregation classes implementing `AggregationInterface`. All immutable; mutation
| `HistogramAggregation.php` | Fixed-interval numeric buckets | `FilterableAggregation`, `GlobalizableAggregation` |
| `SumAggregation.php` | Sum of numeric field values | `FilterableAggregation`, `GlobalizableAggregation` |
| `CardinalityAggregation.php` | Distinct value count (cardinality) | `FilterableAggregation`, `GlobalizableAggregation` |
| `DateHistogramAggregation.php` | Date-based histogram buckets (calendar/fixed interval) | `FilterableAggregation`, `GlobalizableAggregation` |

## ADDING A NEW AGGREGATION

Expand Down
81 changes: 81 additions & 0 deletions src/Aggregation/DateHistogramAggregation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

declare(strict_types=1);

namespace Bonu\ElasticsearchBuilder\Aggregation;

use Bonu\ElasticsearchBuilder\Exception\Aggregation\InvalidDateHistogramIntervalException;

use function array_filter;

/**
* @see https://www.elastic.co/docs/reference/aggregations/search-aggregations-bucket-datehistogram-aggregation
*/
class DateHistogramAggregation implements AggregationInterface
{
use FilterableAggregation;
use GlobalizableAggregation;

/**
* @param string|\Stringable $name
* @param string|\Stringable $field
* @param null|string $calendarInterval
* @param null|string $fixedInterval
* @param null|int $minDocCount
* @param null|string $format
* @param null|string $timeZone
* @param null|string $offset
*
* @throws \Bonu\ElasticsearchBuilder\Exception\Aggregation\InvalidDateHistogramIntervalException
*/
public function __construct(
protected string | \Stringable $name,
protected string | \Stringable $field,
protected ?string $calendarInterval = null,
protected ?string $fixedInterval = null,
protected ?int $minDocCount = null,
protected ?string $format = null,
protected ?string $timeZone = null,
protected ?string $offset = null,
) {
if ($calendarInterval === null && $fixedInterval === null) {
throw new InvalidDateHistogramIntervalException('Either calendarInterval or fixedInterval must be provided.');
}

if ($calendarInterval !== null && $fixedInterval !== null) {
throw new InvalidDateHistogramIntervalException('Only one of calendarInterval or fixedInterval can be provided, not both.');
}
}

/**
* @inheritDoc
*/
#[\Override]
public function getName(): string
{
return (string) $this->name;
}

/**
* @inheritDoc
*/
#[\Override]
public function toArray(): array
{
$value = ['date_histogram' => array_filter([
'field' => (string) $this->field,
'calendar_interval' => $this->calendarInterval,
'fixed_interval' => $this->fixedInterval,
'min_doc_count' => $this->minDocCount,
'format' => $this->format,
'time_zone' => $this->timeZone,
'offset' => $this->offset,
], static fn (mixed $value): bool => $value !== null)];
$value = $this->addFilterToAggregation($value, $this->getName());
$value = $this->addGlobalToAggregation($value, $this->getName());

return [
$this->getName() => $value,
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Bonu\ElasticsearchBuilder\Exception\Aggregation;

class InvalidDateHistogramIntervalException extends AggregationException
{
}
79 changes: 79 additions & 0 deletions tests/Integration/Aggregation/DateHistogramAggregationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace Bonu\ElasticsearchBuilder\Tests\Integration\Aggregation;

use PHPUnit\Framework\Attributes\Test;
use Bonu\ElasticsearchBuilder\QueryBuilder;
use Bonu\ElasticsearchBuilder\Tests\IntegrationTestCase;
use Bonu\ElasticsearchBuilder\Aggregation\DateHistogramAggregation;

/**
* @internal
*/
final class DateHistogramAggregationTest extends IntegrationTestCase
{
#[Test]
public function itCreatesDateHistogramWithCalendarInterval(): void
{
$response = $this->client?->search(
new QueryBuilder(self::INDEX)
->aggregation(new DateHistogramAggregation('releases_by_year', 'album_release_date', calendarInterval: 'year'))
->size(1)
->build()
)->asArray();

$this->assertArrayHasKey('aggregations', $response);
$this->assertNotEmpty($response['aggregations']['releases_by_year']['buckets']);

foreach ($response['aggregations']['releases_by_year']['buckets'] as $bucket) {
$this->assertArrayHasKey('key', $bucket);
$this->assertArrayHasKey('key_as_string', $bucket);
$this->assertArrayHasKey('doc_count', $bucket);
}
}

#[Test]
public function itCreatesDateHistogramWithFixedInterval(): void
{
$response = $this->client?->search(
new QueryBuilder(self::INDEX)
->aggregation(new DateHistogramAggregation('releases_by_quarter', 'album_release_date', fixedInterval: '90d'))
->size(1)
->build()
)->asArray();

$this->assertArrayHasKey('aggregations', $response);
$this->assertNotEmpty($response['aggregations']['releases_by_quarter']['buckets']);

foreach ($response['aggregations']['releases_by_quarter']['buckets'] as $bucket) {
$this->assertArrayHasKey('key', $bucket);
$this->assertArrayHasKey('doc_count', $bucket);
}
}

#[Test]
public function itCreatesDateHistogramWithFormatAndMinDocCount(): void
{
$response = $this->client?->search(
new QueryBuilder(self::INDEX)
->aggregation(new DateHistogramAggregation(
'releases_by_month',
'album_release_date',
calendarInterval: 'month',
minDocCount: 1,
format: 'yyyy-MM',
))
->size(1)
->build()
)->asArray();

$this->assertArrayHasKey('aggregations', $response);

foreach ($response['aggregations']['releases_by_month']['buckets'] as $bucket) {
$this->assertGreaterThanOrEqual(1, $bucket['doc_count']);
$this->assertMatchesRegularExpression('/^\d{4}-\d{2}$/', $bucket['key_as_string']);
}
}
}
Loading