Skip to content

Improve paginated response #36

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

Merged
merged 1 commit into from
Jun 6, 2022
Merged
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
5 changes: 1 addition & 4 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,5 @@
### PHPUnit
/.phpunit.result.cache

### Documentation
/docs

### Local test
/test*.php
/test*.php
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased v2.x]

### Added

- Documentation on paginated responses
- Throw custom exception is client is missing

### Changed

- Rework paginated responses

### Deprecated

- `\MacFJA\RediSearch\Redis\Response\AggregateResponseItem::getValue` (use `\MacFJA\RediSearch\Redis\Response\AggregateResponseItem::getFieldValue` instead)

## [2.1.2]

### Fixed
Expand Down
27 changes: 27 additions & 0 deletions docs/BuildQuery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Building a Query

To help create RediSearch, the library offer a builder.

It all start with the class `\MacFJA\RediSearch\Query\Builder`. From there you can add groups and query elements.

---

For example, for search all people named `John`, and preferably with the last name `Doe` that work as an accountant in the 10 km around Washington DC, and the resume contain text `cake` the request will be:
```php
use MacFJA\RediSearch\Query\Builder;
use MacFJA\RediSearch\Query\Builder\GeoFacet;
use MacFJA\RediSearch\Query\Builder\TextFacet;
use MacFJA\RediSearch\Query\Builder\Optional;
use MacFJA\RediSearch\Redis\Command\SearchCommand\GeoFilterOption;

$queryBuilder = new Builder();
$query = $queryBuilder
->addTextFacet('firstname', 'John') // people named `John`
->addElement(new Optional(new TextFacet(['lastname'], 'Doe'))) // preferably with the last name `Doe`
->addTextFacet('job', 'accountant') // work as an accountant
->addGeoFacet('address', -77.0365427, 38.8950368, 10, GeoFilterOption::UNIT_KILOMETERS) // in the 10 km around Washington DC
->addString('cake') // the resume contain text `cake`
->render();

// @firstname:John ~@lastname:Doe @job:accountant @address:[-77.0365427 38.8950368 10 km] cake
```
70 changes: 70 additions & 0 deletions docs/UsingResult.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Using result

As you can set an offset and limit on `FT.SEARCH` and `FT.AGGREGATE`, they are paginated commands.
The result of those commands is a page, that can contain one or more document.

---

So in this library, the result of `\MacFJA\RediSearch\Redis\Command\Search` and `\MacFJA\RediSearch\Redis\Command\Aggregate` is also a paginated object:
either a `\MacFJA\RediSearch\Redis\Response\PaginatedResponse` (for Search and Aggregate) or a `\MacFJA\RediSearch\Redis\Response\CursorResponse` (for Aggregate)

The 2 classes are representing a page.

Both `\MacFJA\RediSearch\Redis\Response\PaginatedResponse` and `\MacFJA\RediSearch\Redis\Response\CursorResponse` can be read inside a `foreach` loop or with any iterator function.
(As they implement the [`\Iterator` interface](https://www.php.net/manual/en/class.iterator.php))
What you are iterating over, are the pages (not the documents inside the page).

```php
// If your RediSearch search have 15 results in total, but you set the pagination to 10 per page:
/** @var PaginatedResponse $results */

/** @var array<SearchResponseItem> $items */
$items = $results->current();
// $items is a list of 10 SearchResponseItem

$results->next(); // To be able to class `->next()`, you need to call `->setClient()` first !

/** @var array<SearchResponseItem> $items */
$items = $results->current();
// $items is a list of 5 SearchResponseItem
```

## Get all items on all pages

```php
/** @var \MacFJA\RediSearch\Redis\Client $client */
/** @var \MacFJA\RediSearch\Redis\Command\Search $search */

/** @var \MacFJA\RediSearch\Redis\Response\PaginatedResponse $results */
$results = $client->execute($search);
$results->setClient($client);

$items = [];
foreach ($results as $pageIndex => $pageContent) {
$items = array_merge($items, $pageContent);
}
/** @var \MacFJA\RediSearch\Redis\Response\SearchResponseItem $item */
foreach ($items as $item) {
doSomething($item);
}
```
Be careful, this will load all items in the memory.
This will also call Redis multiple time if there are several pages.

---

If you need to avoid loading all items in the memory, you can use [`ResponseItemIterator`](https://github.com/MacFJA/php-redisearch-integration/blob/main/src/Iterator/ResponseItemIterator.php) from the sister project [macfja/redisearch-integration](https://github.com/MacFJA/php-redisearch-integration).
This class it a custom iterator that will load in memory only one page at the time.

```php
/** @var \MacFJA\RediSearch\Redis\Client $client */
/** @var \MacFJA\RediSearch\Redis\Command\Search $search */

$results = $client->execute($search);
$allItems = new \MacFJA\RediSearch\Integration\Iterator\ResponseItemIterator($results, $client);
/** @var \MacFJA\RediSearch\Redis\Response\SearchResponseItem $item */
foreach ($allItems as $item) {
// Only one page exist in the memory
doSomething($item);
}
```
33 changes: 33 additions & 0 deletions src/Exception/MissingClientException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

/*
* Copyright MacFJA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace MacFJA\RediSearch\Exception;

use RuntimeException;
use Throwable;

class MissingClientException extends RuntimeException
{
public function __construct(Throwable $previous = null)
{
parent::__construct('The Redis client is missing. You need to manually set it.', 0, $previous);
}
}
6 changes: 6 additions & 0 deletions src/Redis/Client/AmpRedisClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ class AmpRedisClient extends AbstractClient
/** @var Redis */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(Redis $redis)
{
if (!static::supports($redis)) {
Expand Down Expand Up @@ -83,6 +86,9 @@ public function pipeline(Command ...$commands): array
}, $commands);
}

/**
* @codeCoverageIgnore
*/
protected function doPipeline(Command ...$commands): array
{
return [];
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/CheprasovRedisClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ class CheprasovRedisClient extends AbstractClient
/** @var AbstractRedisClient */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(AbstractRedisClient $redis)
{
if (!static::supports($redis)) {
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/CredisClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class CredisClient extends AbstractClient
/** @var Credis_Client */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(Credis_Client $redis)
{
if (!self::supports($redis)) {
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/PredisClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ class PredisClient extends AbstractClient
/** @var ClientInterface */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(ClientInterface $redis)
{
if (!static::supports($redis)) {
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/RedisentClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ class RedisentClient extends AbstractClient
/** @var Redis */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(Redis $redis)
{
if (!static::supports($redis)) {
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/Rediska/RediskaRediSearchCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
use Rediska_Command_Abstract;
use Rediska_Connection_Exec;

/**
* @codeCoverageIgnore
*/
class RediskaRediSearchCommand extends Rediska_Command_Abstract
{
public function create(): Rediska_Connection_Exec
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/RediskaClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class RediskaClient extends AbstractClient
/** @var Rediska */
private $redis;

/**
* @codeCoverageIgnore
*/
private function __construct(Rediska $redis)
{
if (!static::supports($redis)) {
Expand Down
3 changes: 3 additions & 0 deletions src/Redis/Client/TinyRedisClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ class TinyRedisClient extends AbstractClient
/** @var \TinyRedisClient */
private $redis;

/**
* @codeCoverageIgnore
*/
public function __construct(\TinyRedisClient $redis)
{
if (!self::supports($redis)) {
Expand Down
18 changes: 17 additions & 1 deletion src/Redis/Response/AggregateResponseItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
/**
* @codeCoverageIgnore Simple value object
*/
class AggregateResponseItem
class AggregateResponseItem implements ResponseItem
{
/** @var array<string,null|array<mixed>|float|int|string> */
private $fields = [];
Expand All @@ -49,8 +49,24 @@ public function getFields(): array
* @param null|array<mixed>|float|int|string $default
*
* @return null|array<mixed>|float|int|string
*
* @deprecated Use ::getFieldValue instead
* @codeCoverageIgnore
* @psalm-suppress
* @SuppressWarnings
*/
public function getValue(string $fieldName, $default = null)
{
trigger_error(sprintf(
'Method %s is deprecated from version 2.2.0, use %s::getFieldValue instead',
__METHOD__,
__CLASS__
), E_USER_DEPRECATED);
// @phpstan-ignore-next-line
return $this->getFieldValue($fieldName, $default);
}

public function getFieldValue(string $fieldName, $default = null)
{
return $this->fields[$fieldName] ?? $default;
}
Expand Down
7 changes: 5 additions & 2 deletions src/Redis/Response/ArrayResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,12 @@ private static function getNextValue(array $notKeyedArray, string $key)
*/
private static function getKeys(array $notKeyedArray): array
{
$keys = array_filter(array_values($notKeyedArray), static function (int $key): bool {
if (count($notKeyedArray) % 2 > 0) {
array_pop($notKeyedArray);
}
$keys = array_values(array_filter(array_values($notKeyedArray), static function (int $key): bool {
return 0 === $key % 2;
}, ARRAY_FILTER_USE_KEY);
}, ARRAY_FILTER_USE_KEY));

return array_map(static function ($key): string {
return (string) $key;
Expand Down
31 changes: 31 additions & 0 deletions src/Redis/Response/ClientAware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

/*
* Copyright MacFJA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace MacFJA\RediSearch\Redis\Response;

use MacFJA\RediSearch\Redis\Client;

interface ClientAware
{
public function setClient(Client $client): ClientAware;

public function getClient(): ?Client;
}
42 changes: 42 additions & 0 deletions src/Redis/Response/ClientAwareTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

/*
* Copyright MacFJA
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace MacFJA\RediSearch\Redis\Response;

use MacFJA\RediSearch\Redis\Client;

trait ClientAwareTrait
{
/** @var null|Client */
private $client;

public function getClient(): ?Client
{
return $this->client;
}

public function setClient(Client $client): ClientAware
{
$this->client = $client;

return $this;
}
}
Loading