Skip to content

Commit 7e56817

Browse files
Fixed unexpected behavior for ElasticsearchEngine::getTotalCount() in hyperf/scout. (#3095)
* Fixed unexpected behavior for `ElasticsearchEngine::getTotalCount()` in `hyperf/scout`. * Format code Co-authored-by: 李铭昕 <[email protected]>
1 parent 1361913 commit 7e56817

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/Engine/ElasticsearchEngine.php

+8-3
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ public function paginate(Builder $builder, $perPage, $page)
136136
'from' => (($page * $perPage) - $perPage),
137137
'size' => $perPage,
138138
]);
139-
$result['nbPages'] = $result['hits']['total'] / $perPage;
139+
$result['nbPages'] = $this->getTotalCount($result) / $perPage;
140140
return $result;
141141
}
142142

@@ -158,7 +158,7 @@ public function mapIds($results): BaseCollection
158158
*/
159159
public function map(Builder $builder, $results, $model): Collection
160160
{
161-
if ($results['hits']['total'] === 0) {
161+
if ($this->getTotalCount($results) === 0) {
162162
return $model->newCollection();
163163
}
164164
$keys = collect($results['hits']['hits'])->pluck('_id')->values()->all();
@@ -177,7 +177,12 @@ public function map(Builder $builder, $results, $model): Collection
177177
*/
178178
public function getTotalCount($results): int
179179
{
180-
return $results['hits']['total'];
180+
$total = $results['hits']['total'];
181+
if (is_array($total)) {
182+
return $results['hits']['total']['value'];
183+
}
184+
185+
return $total;
181186
}
182187

183188
/**

tests/Cases/ElasticsearchEngineTest.php

+20-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ public function testMapCorrectlyMapsResultsToModels()
130130
$model->shouldReceive('newCollection')->andReturn($models);
131131
$results = $engine->map($builder, [
132132
'hits' => [
133-
'total' => '1',
133+
'total' => 1,
134134
'hits' => [
135135
[
136136
'_id' => '1',
@@ -140,4 +140,23 @@ public function testMapCorrectlyMapsResultsToModels()
140140
], $model);
141141
$this->assertEquals(1, count($results));
142142
}
143+
144+
public function testGetTotalCount()
145+
{
146+
$client = Mockery::mock('Elasticsearch\Client');
147+
$engine = new ElasticsearchEngine($client, 'scout');
148+
$this->assertSame(1, $engine->getTotalCount([
149+
'hits' => [
150+
'total' => 1,
151+
],
152+
]));
153+
$this->assertSame(2, $engine->getTotalCount([
154+
'hits' => [
155+
'total' => [
156+
'value' => 2,
157+
'relation' => 'eq',
158+
],
159+
],
160+
]));
161+
}
143162
}

0 commit comments

Comments
 (0)