Skip to content
This repository was archived by the owner on Nov 4, 2021. It is now read-only.

Commit a814033

Browse files
committed
Added count method
1 parent c8f6622 commit a814033

File tree

4 files changed

+83
-1
lines changed

4 files changed

+83
-1
lines changed

README.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,14 @@ App\MyModel::search('phone')
207207
->get();
208208
```
209209

210-
If you need to load relations you can use the `with` method:
210+
If you only need the number of matches for a query, use the `count` method:
211+
212+
```php
213+
App\MyModel::search('phone')
214+
->count();
215+
```
216+
217+
If you need to load relations, use the `with` method:
211218

212219
```php
213220
App\MyModel::search('phone')

src/Builders/FilterBuilder.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,4 +270,14 @@ public function select($fields)
270270

271271
return $this;
272272
}
273+
274+
/**
275+
* @return int
276+
*/
277+
public function count()
278+
{
279+
return $this
280+
->engine()
281+
->count($this);
282+
}
273283
}

src/ElasticEngine.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,29 @@ public function profile(Builder $builder)
180180
]);
181181
}
182182

183+
/**
184+
* @param Builder $builder
185+
* @return int
186+
*/
187+
public function count(Builder $builder)
188+
{
189+
$count = 0;
190+
191+
$this
192+
->buildSearchQueryPayloadCollection($builder)
193+
->each(function($payload) use (&$count) {
194+
$result = ElasticClient::count($payload);
195+
196+
$count = $result['count'];
197+
198+
if ($count > 0) {
199+
return false;
200+
}
201+
});
202+
203+
return $count;
204+
}
205+
183206
public function searchRaw(Model $model, $query)
184207
{
185208
$payload = (new TypePayload($model))

tests/ElasticEngineTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,48 @@ public function testBuildFilterQueryPayloadCollection()
201201
);
202202
}
203203

204+
public function testCount()
205+
{
206+
ElasticClient
207+
::shouldReceive('count')
208+
->once()
209+
->with([
210+
'index' => 'test',
211+
'type' => 'test',
212+
'body' => [
213+
'query' => [
214+
'bool' => [
215+
'must' => [
216+
'match_all' => new stdClass()
217+
],
218+
'filter' => [
219+
'bool' => [
220+
'must' => [
221+
[
222+
'term' => [
223+
'foo' => 'bar'
224+
]
225+
]
226+
]
227+
]
228+
]
229+
]
230+
]
231+
]
232+
]);
233+
234+
$model = $this->mockModel();
235+
236+
$filterBuilder = (new FilterBuilder($model))
237+
->where('foo', 'bar');
238+
239+
$this
240+
->engine
241+
->count($filterBuilder);
242+
243+
$this->addToAssertionCount(1);
244+
}
245+
204246
public function testSearchRaw()
205247
{
206248
ElasticClient

0 commit comments

Comments
 (0)