From fe767344df4a4b5c9459c36bb0e7582554e61680 Mon Sep 17 00:00:00 2001 From: Ernest Walzel Date: Fri, 18 Aug 2023 08:28:49 +0200 Subject: [PATCH] Exclude date_latest for date_earliest aggregations and vice versa --- .../Controllers/Api/V1/ItemController.php | 12 +++++++++++- .../Feature/Api/V1/ItemsAggregationsTest.php | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/Api/V1/ItemController.php b/app/Http/Controllers/Api/V1/ItemController.php index 4ad40a842..0f6d7d670 100644 --- a/app/Http/Controllers/Api/V1/ItemController.php +++ b/app/Http/Controllers/Api/V1/ItemController.php @@ -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(); } diff --git a/tests/Feature/Api/V1/ItemsAggregationsTest.php b/tests/Feature/Api/V1/ItemsAggregationsTest.php index c44e37cd1..c39b8e4d9 100644 --- a/tests/Feature/Api/V1/ItemsAggregationsTest.php +++ b/tests/Feature/Api/V1/ItemsAggregationsTest.php @@ -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, ], ]); @@ -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([