55use Ensi \LaravelElasticQuery \Aggregating \BucketCollection ;
66use Ensi \LaravelElasticQuery \Aggregating \Result ;
77use Ensi \LaravelElasticQuery \Contracts \Aggregation ;
8+ use Ensi \LaravelElasticQuery \Search \Sorting \Sort ;
89use Webmozart \Assert \Assert ;
910
1011class TermsAggregation implements Aggregation
1112{
12- public function __construct (private string $ name , private string $ field , private ?int $ size = null )
13- {
13+ public function __construct (
14+ private string $ name ,
15+ private string $ field ,
16+ private ?int $ size = null ,
17+ private ?Sort $ sort = null ,
18+ private ?Aggregation $ composite = null ,
19+ ) {
1420 Assert::stringNotEmpty (trim ($ name ));
1521 Assert::stringNotEmpty (trim ($ field ));
1622 Assert::nullOrGreaterThan ($ this ->size , 0 );
@@ -29,20 +35,39 @@ public function toDSL(): array
2935 $ body ['size ' ] = $ this ->size ;
3036 }
3137
32- return [
38+ if ($ this ->sort ) {
39+ $ body ['order ' ] = $ this ->sort ->toDSL ();
40+ }
41+
42+ $ dsl = [
3343 $ this ->name => [
3444 'terms ' => $ body ,
3545 ],
3646 ];
47+
48+ if ($ this ->isComposite ()) {
49+ $ dsl [$ this ->name ]['aggs ' ] = $ this ->composite ->toDSL ();
50+ }
51+
52+ return $ dsl ;
3753 }
3854
3955 public function parseResults (array $ response ): array
4056 {
4157 $ buckets = array_map (
42- fn (array $ bucket ) => Result::parseBucket ($ bucket ),
58+ function (array $ bucket ) {
59+ $ values = $ this ->isComposite () ? $ this ->composite ->parseResults ($ bucket ) : [];
60+
61+ return Result::parseBucket ($ bucket , $ values );
62+ },
4363 $ response [$ this ->name ]['buckets ' ] ?? []
4464 );
4565
4666 return [$ this ->name => new BucketCollection ($ buckets )];
4767 }
68+
69+ public function isComposite (): bool
70+ {
71+ return isset ($ this ->composite );
72+ }
4873}
0 commit comments