33namespace Ensi \LaravelElasticQuery \Search ;
44
55use Closure ;
6+ use Ensi \LaravelElasticQuery \Aggregating \AggregationCollection ;
67use Ensi \LaravelElasticQuery \Concerns \DecoratesBoolQuery ;
78use Ensi \LaravelElasticQuery \Concerns \ExtendsSort ;
9+ use Ensi \LaravelElasticQuery \Contracts \Aggregation ;
810use Ensi \LaravelElasticQuery \Contracts \CollapsibleQuery ;
911use Ensi \LaravelElasticQuery \Contracts \SearchIndex ;
1012use Ensi \LaravelElasticQuery \Contracts \SortableQuery ;
@@ -25,6 +27,7 @@ class SearchQuery implements SortableQuery, CollapsibleQuery
2527 protected BoolQueryBuilder $ boolQuery ;
2628 protected SortCollection $ sorts ;
2729 protected ?Collapse $ collapse = null ;
30+ protected ?AggregationCollection $ aggregations = null ;
2831 protected ?int $ size = null ;
2932 protected ?int $ from = null ;
3033 protected array $ fields = [];
@@ -60,6 +63,7 @@ public function paginate(int $size, int $offset = 0): Page
6063 return new Page (
6164 $ size ,
6265 $ hits ,
66+ aggs: $ this ->aggregations ?->parseResults($ response ['aggregations ' ] ?? []),
6367 offset: $ offset ,
6468 total: data_get ($ response , 'hits.total.value ' , 0 )
6569 );
@@ -82,6 +86,7 @@ public function cursorPaginate(int $size, ?string $cursor = null): CursorPage
8286 return new CursorPage (
8387 $ size ,
8488 $ hits ,
89+ aggs: $ this ->aggregations ?->parseResults($ response ['aggregations ' ] ?? []),
8590 current: $ current ->encode (),
8691 next: $ this ->findNextCursor ($ sorts , $ size , $ hits ),
8792 previous: $ this ->findPreviousCursor ($ sorts , $ size , $ current )
@@ -131,6 +136,10 @@ protected function execute(
131136 $ dsl ['sort ' ] = $ sorts ->toDSL ();
132137 }
133138
139+ if (!is_null ($ this ->aggregations )) {
140+ $ dsl ['aggs ' ] = $ this ->aggregations ->toDSL ();
141+ }
142+
134143 if (!is_null ($ this ->collapse )) {
135144 $ dsl ['collapse ' ] = $ this ->collapse ->toDSL ();
136145 }
@@ -175,9 +184,17 @@ public function sortByNested(string $field, Closure $callback): static
175184 return $ this ;
176185 }
177186
178- public function collapse (string $ field ): static
187+ public function collapse (string $ field , array $ innerHits = []): static
188+ {
189+ $ this ->collapse = new Collapse ($ field , $ innerHits );
190+
191+ return $ this ;
192+ }
193+
194+ public function addAggregations (Aggregation $ aggregation ): static
179195 {
180- $ this ->collapse = new Collapse ($ field );
196+ $ this ->aggregations ??= new AggregationCollection ();
197+ $ this ->aggregations ->add ($ aggregation );
181198
182199 return $ this ;
183200 }
0 commit comments