Skip to content

Commit

Permalink
Merge pull request #20 from designmynight/aggregation-collection
Browse files Browse the repository at this point in the history
feat: Added support for getting aggregation results as a custom collection
  • Loading branch information
robbytaylor authored Jan 22, 2018
2 parents a766350 + 3a98e2e commit 06dc204
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/DesignMyNight/Elasticsearch/EloquentBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class EloquentBuilder extends BaseBuilder
{
Expand Down Expand Up @@ -60,6 +61,14 @@ public function get($columns = ['*'])
return $builder->getModel()->newCollection($models);
}

public function getAggregations(string $collectionClass = ''): Collection
{
$collectionClass = $collectionClass ?: Collection::class;
$aggregations = $this->query->getAggregationResults();

return new $collectionClass($aggregations);
}

/**
* Get the hydrated models without eager loading.
*
Expand Down
15 changes: 14 additions & 1 deletion src/DesignMyNight/Elasticsearch/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ class QueryBuilder extends BaseBuilder

public $includeInnerHits;

protected $results;

protected $rawResponse;

protected $scrollSelect;
Expand Down Expand Up @@ -366,6 +368,8 @@ public function withInnerHits(): self
*/
public function getAggregationResults(): array
{
$this->getResultsOnce();

return $this->processor->getAggregationResults();
}

Expand All @@ -383,13 +387,22 @@ public function get($columns = ['*'])
$this->columns = $columns;
}

$results = $this->processor->processSelect($this, $this->runSelect());
$results = $this->getResultsOnce();

$this->columns = $original;

return $this->shouldUseScroll() ? $results : collect($results);
}

protected function getResultsOnce(): array
{
if ($this->results === null) {
$this->results = $this->processor->processSelect($this, $this->runSelect());
}

return $this->results;
}

/**
* Run the query as a "select" statement against the connection.
*
Expand Down

0 comments on commit 06dc204

Please sign in to comment.