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
62 changes: 62 additions & 0 deletions src/Aggregating/Bucket/FiltersAggregation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace Ensi\LaravelElasticQuery\Aggregating\Bucket;

use Ensi\LaravelElasticQuery\Aggregating\BucketCollection;
use Ensi\LaravelElasticQuery\Aggregating\FiltersCollection;
use Ensi\LaravelElasticQuery\Aggregating\Result;
use Ensi\LaravelElasticQuery\Contracts\Aggregation;
use Webmozart\Assert\Assert;

class FiltersAggregation implements Aggregation
{
public function __construct(
private string $name,
private FiltersCollection $filters,
private ?Aggregation $composite = null,
private ?string $otherBucketKey = null,
) {
Assert::stringNotEmpty(trim($name));
Assert::greaterThan($filters->count(), 0);
}

public function name(): string
{
return $this->name;
}

public function toDSL(): array
{
$body['filters']['filters'] = $this->filters->toDSL();

if ($this->otherBucketKey != null) {
$body['filters']['other_bucket_key'] = $this->otherBucketKey;
}

if ($this->isComposite()) {
$body['aggs'] = $this->composite->toDSL();
}

return [$this->name => $body];
}

public function parseResults(array $response): array
{
$buckets = array_map(
function (mixed $key, array $bucket) {
$values = $this->isComposite() ? $this->composite->parseResults($bucket) : [];

return Result::parseBucketWithKey($key, $bucket, $values);
},
array_keys($response[$this->name]['buckets'] ?? []),
$response[$this->name]['buckets'] ?? []
);

return [$this->name => new BucketCollection($buckets)];
}

public function isComposite(): bool
{
return isset($this->composite);
}
}
34 changes: 34 additions & 0 deletions src/Aggregating/FiltersCollection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Ensi\LaravelElasticQuery\Aggregating;

use Ensi\LaravelElasticQuery\Contracts\Criteria;
use Ensi\LaravelElasticQuery\Contracts\DSLAware;
use Illuminate\Support\Collection;

class FiltersCollection implements DSLAware
{
private Collection $items;

public function __construct()
{
$this->items = new Collection();
}

public function count(): int
{
return $this->items->count();
}

public function toDSL(): array
{
return $this->items
->mapWithKeys(fn (Criteria $criteria, string $key) => [$key => $criteria->toDSL()])
->all();
}

public function add(string $name, Criteria $criteria): void
{
$this->items->put($name, $criteria);
}
}
5 changes: 5 additions & 0 deletions src/Aggregating/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public static function parseBucket(array $source, array $compositeValues = []):
return new Bucket(self::parse($source, 'key'), (int)($source['doc_count'] ?? 0), $compositeValues);
}

public static function parseBucketWithKey(mixed $key, array $source, array $compositeValues = []): Bucket
{
return new Bucket($key, (int)($source['doc_count'] ?? 0), $compositeValues);
}

public static function parse(array $source, string $key): mixed
{
$stringValue = $source["{$key}_as_string"] ?? null;
Expand Down
13 changes: 13 additions & 0 deletions src/Concerns/ConstructsAggregations.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
use Closure;
use Ensi\LaravelElasticQuery\Aggregating\AggregationCollection;
use Ensi\LaravelElasticQuery\Aggregating\Bucket\FilterAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Bucket\FiltersAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Bucket\NestedAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Bucket\TermsAggregation;
use Ensi\LaravelElasticQuery\Aggregating\CompositeAggregationBuilder;
use Ensi\LaravelElasticQuery\Aggregating\FiltersCollection;
use Ensi\LaravelElasticQuery\Aggregating\Metrics\CardinalityAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Metrics\MinMaxAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Metrics\ValueCountAggregation;
Expand Down Expand Up @@ -43,6 +45,17 @@ public function filter(string $name, Criteria $criteria, AggregationCollection $
return $this;
}

public function filters(
string $name,
FiltersCollection $filters,
?Aggregation $composite = null,
?string $otherBucketKey = null,
): static {
$this->aggregations->add(new FiltersAggregation($name, $filters, $composite, $otherBucketKey));

return $this;
}

public function minmax(string $name, string $field): static
{
$this->aggregations->add(new MinMaxAggregation($name, $this->absolutePath($field)));
Expand Down
39 changes: 39 additions & 0 deletions tests/IntegrationTests/AggregationQueryIntegrationTest.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
<?php

use Ensi\LaravelElasticQuery\Aggregating\Bucket;
use Ensi\LaravelElasticQuery\Aggregating\FiltersCollection;
use Ensi\LaravelElasticQuery\Aggregating\Metrics\MinMaxScoreAggregation;
use Ensi\LaravelElasticQuery\Aggregating\Metrics\TopHitsAggregation;
use Ensi\LaravelElasticQuery\Aggregating\MinMax;
use Ensi\LaravelElasticQuery\Contracts\AggregationsBuilder;
use Ensi\LaravelElasticQuery\Filtering\Criterias\RangeBound;
use Ensi\LaravelElasticQuery\Filtering\Criterias\Term;
use Ensi\LaravelElasticQuery\Search\Sorting\Sort;
use Ensi\LaravelElasticQuery\Tests\Data\Models\ProductsIndex;
use Ensi\LaravelElasticQuery\Tests\IntegrationTestCase;
Expand Down Expand Up @@ -139,3 +142,39 @@
assertCount(2, $results->get('codes'));
assertGreaterThanOrEqual($scores->first(), $scores->last());
});

test('aggregation query filters', function (?string $defaultBucket) {
/** @var IntegrationTestCase $this */

$filters = new FiltersCollection();
$filters->add('filter_tags', new Term('tags', 'video'));
$filters->add('filter_rating', new RangeBound('rating', '>=', 7));

$topHits = new TopHitsAggregation('top_hits');

$results = ProductsIndex::aggregate()
->filters('group_by_filters', $filters, $topHits, otherBucketKey: $defaultBucket)
->get()
->get('group_by_filters')
->keyBy(fn (Bucket $bucket) => $bucket->key);

$additionResult = $defaultBucket !== null ? 1 : 0;
assertCount($filters->count() + $additionResult, $results);

assertEqualsCanonicalizing(
[1, 328],
extractBucketValues($results, 'filter_tags', $topHits->name(), 'product_id')
);

assertEqualsCanonicalizing(
[1, 150, 405],
extractBucketValues($results, 'filter_rating', $topHits->name(), 'product_id')
);

if ($defaultBucket != null) {
assertEqualsCanonicalizing(
[319, 471],
extractBucketValues($results, $defaultBucket, $topHits->name(), 'product_id')
);
}
})->with([null, 'default_bucket']);
12 changes: 12 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Ensi\LaravelElasticQuery\Aggregating\Bucket;
use Illuminate\Support\Collection;
use Illuminate\Testing\AssertableJsonString;

/*
Expand Down Expand Up @@ -58,3 +60,13 @@ function makeAssertableArray(array $source): AssertableJsonString
{
return new AssertableJsonString($source);
}

function extractBucketValues(Collection $result, string $bucketName, string $aggregationName, string $key): array
{
/** @var Bucket $bucket */
$bucket = $result->get($bucketName);

$hits = $bucket->getCompositeValue($aggregationName);

return array_map(fn (array $hit) => $hit['_source'][$key], $hits);
};
Loading