Skip to content

Commit

Permalink
Ensure the search::count() is counting all results
Browse files Browse the repository at this point in the history
  • Loading branch information
thePanz committed Jan 15, 2020
1 parent 9392fb0 commit 59dc7e6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
6 changes: 5 additions & 1 deletion lib/Elastica/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -391,12 +391,16 @@ public function setCollapse(Collapse $collapse): self
/**
* Adds a track_total_hits argument.
*
* @param bool|int $trackTotalHits Track total hits parameter (default = true)
* @param bool|int $trackTotalHits Track total hits parameter
*
* @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-track-total-hits
*/
public function setTrackTotalHits($trackTotalHits = true): self
{
if (!is_bool($trackTotalHits) && !is_int($trackTotalHits)) {
throw new InvalidException('TrackTotalHits must be either a boolean, or an integer value');
}

return $this->setParam('track_total_hits', $trackTotalHits);
}
}
2 changes: 2 additions & 0 deletions lib/Elastica/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,8 @@ public function count($query = '', bool $fullResult = false, string $method = Re
// Clone the object as we do not want to modify the original query.
$query = clone $this->getQuery();
$query->setSize(0);
$query->setTrackTotalHits(true);

$path = $this->getPath();

$response = $this->getClient()->request(
Expand Down
29 changes: 23 additions & 6 deletions test/Elastica/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -535,21 +535,38 @@ public function testCollapseSecondLevelArrayStructure()
}

/**
* @group unit
* @group functional
*/
public function testSetTrackTotalHitsIsInParams()
public function testSetTrackTotalHitsIsInParams(): void
{
$query = new Query();
$param = false;
$query->setTrackTotalHits($param);
$query->setTrackTotalHits(false);

$this->assertFalse($query->getParam('track_total_hits'));
}

public function provideSetTrackTotalHitsInvalidValue(): iterable
{
yield 'string' => ['string string'];
yield 'null' => [null];
yield 'object' => [new \stdClass()];
yield 'array' => [[]];
}

/**
* @group functional
*/
public function testSetTrackTotalHitsInvalidValueNull($value): void
{
$this->expectException(InvalidException::class);

$this->assertEquals($param, $query->getParam('track_total_hits'));
(new Query())->setTrackTotalHits($value);
}

/**
* @group functional
*/
public function testSetTrackTotalHits()
public function testSetTrackTotalHits(): void
{
$index = $this->_createIndex();
$index->setMapping(new Mapping([
Expand Down

0 comments on commit 59dc7e6

Please sign in to comment.