File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -46,6 +46,15 @@ class FilterBuilder extends Builder
4646 */
4747 public $ select = [];
4848
49+ /**
50+ * @var array
51+ */
52+ public $ aggregates = [];
53+ /**
54+ * @var array
55+ */
56+ public $ aggregateRules = [];
57+
4958 /**
5059 * FilterBuilder constructor.
5160 *
@@ -560,4 +569,41 @@ public function onlyTrashed()
560569 $ this ->wheres ['must ' ][] = ['term ' => ['__soft_deleted ' => 1 ]];
561570 });
562571 }
572+
573+ /**
574+ * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/returning-only-agg-results.html
575+ *
576+ * @param int $size
577+ * @return $this
578+ */
579+ public function aggregate ($ size = 0 )
580+ {
581+ $ this ->take ($ size );
582+ $ payloadCollection = [];
583+ $ aggregateRules = $ this ->aggregateRules ?: $ this ->model ->getAggregateRules ();
584+ foreach ($ aggregateRules as $ rule ) {
585+ if (is_callable ($ rule )) {
586+ $ payloadCollection [] = call_user_func ($ rule );
587+ } else {
588+ $ ruleEntity = new $ rule ;
589+ if ($ aggregatePayload = $ ruleEntity ->buildAggregatePayload ()) {
590+ $ payloadCollection [] = $ aggregatePayload ;
591+ }
592+ }
593+ }
594+ $ this ->aggregates = array_reduce ($ payloadCollection , 'array_merge ' , []);
595+ return $ this ->engine ()->search ($ this );
596+ }
597+
598+ /**
599+ * Adds rule to the aggregate rules of the builder.
600+ *
601+ * @param $rule
602+ * @return $this
603+ */
604+ public function aggregateRule ($ rule )
605+ {
606+ $ this ->aggregateRules [] = $ rule ;
607+ return $ this ;
608+ }
563609}
You can’t perform that action at this time.
0 commit comments