Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the count function, that got lost during the 6.0 upgrade #933

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions Service/IndexService.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,14 +308,35 @@ private function executeSearch(Search $search): array

public function getIndexDocumentCount(): int
{
$body = [
'index' => $this->getIndexName(),
'body' => [],
];
return $this->count();
}

/**
* Counts documents by given search.
*
* @param Search|null $search
* @param array $params
* @param bool $returnRaw If set true returns raw response gotten from client.
*
* @return int|array
*/
public function count(Search $search = null, array $params = [], $returnRaw = false)
{
$body = array_merge(
[
'index' => $this->getIndexName(),
'body' => $search !== null ? $search->toArray() : [],
],
$params
);

$results = $this->getClient()->count($body);

return $results['count'];
if ($returnRaw) {
return $results;
} else {
return $results['count'];
}
}

public function remove($id, $routing = null)
Expand Down
34 changes: 34 additions & 0 deletions Tests/Functional/Service/IndexServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use ONGR\App\Entity\DummyDocumentInTheEntityDirectory;
use ONGR\ElasticsearchBundle\Result\DocumentIterator;
use ONGR\ElasticsearchBundle\Test\AbstractElasticsearchTestCase;
use ONGR\ElasticsearchDSL\Query\FullText\SimpleQueryStringQuery;

/**
* Functional tests for orm manager.
Expand Down Expand Up @@ -120,4 +121,37 @@ public function testIndexConfigOverride()

$this->assertEquals(['localhost:9200'], $hosts);
}

public function testCount()
{
$index = $this->getIndex(DummyDocument::class);

$search = $index->createSearch();
$search->addQuery(new SimpleQueryStringQuery('foo'));

$count = $index->count($search);

$this->assertEquals(2, $count);
}

public function testRawCount()
{
$index = $this->getIndex(DummyDocument::class);

$search = $index->createSearch();
$search->addQuery(new SimpleQueryStringQuery('bar'));

$result = $index->count($search, [], true);

$this->assertEquals(1, $result['count']);
}

public function testIndexDocumentCount()
{
$index = $this->getIndex(DummyDocument::class);

$count = $index->getIndexDocumentCount();

$this->assertEquals(3, $count);
}
}