From a7332880131568b00b80b09904d32477ded73163 Mon Sep 17 00:00:00 2001 From: Manuele Menozzi Date: Sat, 27 Jun 2020 21:10:02 +0200 Subject: [PATCH] Add count method to client --- src/Client.php | 16 ++++++++++++++++ tests/Integration/ClientTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/Client.php b/src/Client.php index 7c72fe0..f8c0994 100644 --- a/src/Client.php +++ b/src/Client.php @@ -180,6 +180,22 @@ public function search(array $query, string $indexOrIndices = null, array $optio return $this->doRequest($this->createJsonRequest($method, $uri, ['query' => $query])); } + public function count(string $index, array $options = [], array $query = null): Promise + { + $method = 'GET'; + $uri = [$this->baseUri, $index]; + $uri[] = '_count'; + $uri = implode('/', $uri); + if ($options) { + $uri .= '?' . http_build_query($options); + } + $body = null; + if (null !== $query) { + $body = ['query' => $query]; + } + return $this->doRequest($this->createJsonRequest($method, $uri, $body)); + } + private function createJsonRequest(string $method, string $uri, array $body = null): Request { $request = (new Request($uri, $method)) diff --git a/tests/Integration/ClientTest.php b/tests/Integration/ClientTest.php index 32b2f7c..7b31fa8 100644 --- a/tests/Integration/ClientTest.php +++ b/tests/Integration/ClientTest.php @@ -240,4 +240,36 @@ public function testSearch(): void $this->assertIsArray($response); $this->assertCount(1, $response['hits']['hits']); } + + public function testCount(): void + { + Promise\wait($this->client->createIndex(self::TEST_INDEX)); + Promise\wait( + $this->client->indexDocument(self::TEST_INDEX, '', ['payload' => []], ['refresh' => 'true']) + ); + Promise\wait( + $this->client->indexDocument(self::TEST_INDEX, '', ['payload' => []], ['refresh' => 'true']) + ); + + $response = Promise\wait($this->client->count(self::TEST_INDEX)); + + $this->assertIsArray($response); + $this->assertEquals(2, $response['count']); + } + + public function testCountWithQuery(): void + { + Promise\wait($this->client->createIndex(self::TEST_INDEX)); + Promise\wait( + $this->client->indexDocument(self::TEST_INDEX, '', ['user' => 'kimchy'], ['refresh' => 'true']) + ); + Promise\wait( + $this->client->indexDocument(self::TEST_INDEX, '', ['user' => 'foo'], ['refresh' => 'true']) + ); + + $response = Promise\wait($this->client->count(self::TEST_INDEX, [], ['term' => ['user' => 'kimchy']])); + + $this->assertIsArray($response); + $this->assertEquals(1, $response['count']); + } }