Skip to content

Commit

Permalink
Exclude date_latest for date_earliest aggregations
Browse files Browse the repository at this point in the history
and vice versa
  • Loading branch information
eronisko committed Aug 18, 2023
1 parent 178a8d5 commit fe76734
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion app/Http/Controllers/Api/V1/ItemController.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,19 @@ public function aggregations(Request $request)
// Add filter terms to each aggregation
// Based on https://madewithlove.com/blog/faceted-search-using-elasticsearch/
foreach (array_keys($aggregationsQuery) as $term) {
$termFilter = Arr::except($filter, $term);

// Additionally exclude date_latest for date_earliest and vice versa
if ($term === 'date_earliest') {
$termFilter = Arr::except($termFilter, 'date_latest');
}
if ($term === 'date_latest') {
$termFilter = Arr::except($termFilter, 'date_earliest');
}

$aggregationsQuery[$term]['filter'] = $this->createQueryBuilder(
$q,
Arr::except($filter, $term)
$termFilter
)->buildQuery();
}

Expand Down
19 changes: 19 additions & 0 deletions tests/Feature/Api/V1/ItemsAggregationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@ public function setUp(): void
'author' => 'Galanda, Mikuláš',
'topic' => 'spring',
'date_earliest' => 1000,
'date_latest' => 1000,
],
[
'author' => 'Wouwerman, Philips',
'topic' => 'summer',
'date_earliest' => 2000,
'date_latest' => 2000,
],
]);

Expand Down Expand Up @@ -81,6 +83,23 @@ public function test_filtered_faced_does_not_affect_itself()
]);
}

public function test_filtered_date_field_does_not_affect_other_date_fields()
{
$this->getAggregations([
'filter' => ['date_earliest' => ['gte' => 2000]],
'terms' => ['date_latest' => 'date_latest'],
])->assertExactJson([
'date_latest' => [['value' => 1000, 'count' => 1], ['value' => 2000, 'count' => 1]],
]);

$this->getAggregations([
'filter' => ['date_latest' => ['gte' => 2000]],
'terms' => ['date_earliest' => 'date_earliest'],
])->assertExactJson([
'date_earliest' => [['value' => 1000, 'count' => 1], ['value' => 2000, 'count' => 1]],
]);
}

public function test_gets_min_and_max()
{
$this->getAggregations([
Expand Down

0 comments on commit fe76734

Please sign in to comment.