@@ -28,6 +28,8 @@ class SearchQuery implements SortableQuery, CollapsibleQuery
2828 protected ?int $ size = null ;
2929 protected ?int $ from = null ;
3030 protected array $ fields = [];
31+ protected array $ include = [];
32+ protected array $ exclude = [];
3133
3234 public function __construct (protected SearchIndex $ index )
3335 {
@@ -120,7 +122,7 @@ protected function execute(
120122 'from ' => $ from ,
121123 'query ' => $ this ->boolQuery ->toDSL (),
122124 'track_total_hits ' => $ totals ,
123- '_source ' => $ source && ! $ this ->fields ,
125+ '_source ' => $ this ->sourceToDSL ( $ source ) ,
124126 'fields ' => $ source && $ this ->fields ? $ this ->fields : null ,
125127 ];
126128
@@ -140,6 +142,16 @@ protected function execute(
140142 return $ this ->index ->search (array_filter ($ dsl ));
141143 }
142144
145+ protected function sourceToDSL (bool $ source ): array | bool
146+ {
147+ return $ source && !$ this ->fields ?
148+ [
149+ 'include ' => $ this ->include ,
150+ 'exclude ' => $ this ->exclude ,
151+ ] :
152+ false ;
153+ }
154+
143155 protected function parseHits (array $ response ): Collection
144156 {
145157 return collect (data_get ($ response , 'hits.hits ' ) ?? []);
@@ -179,6 +191,24 @@ public function take(int $count): static
179191 return $ this ;
180192 }
181193
194+ public function select (array $ include ): static
195+ {
196+ array_map (Assert::stringNotEmpty (...), $ include );
197+
198+ $ this ->include = $ include ;
199+
200+ return $ this ;
201+ }
202+
203+ public function exclude (array $ exclude ): static
204+ {
205+ array_map (Assert::stringNotEmpty (...), $ exclude );
206+
207+ $ this ->exclude = $ exclude ;
208+
209+ return $ this ;
210+ }
211+
182212 public function skip (int $ count ): static
183213 {
184214 Assert::greaterThanEq ($ count , 0 );
0 commit comments