MacFJA / php-redisearch

PHP Client for RediSearch
MIT License
66 stars 9 forks source link

Search results very complex to browse #31

Closed pierrexp9 closed 2 years ago

pierrexp9 commented 2 years ago

Hello MacJFA, (using version 2.1.0)

I wanted to share with you that I find it very hard for a newcomer to simply browse the results of a search, this is the current method I use.

I do not really get why I have to get $results[0] to get to the actual results. (I could also do a $results->current() I suppose, but the problem stays the same).

 /** @var PaginatedResponse $results */
$results = iterator_to_array($results);
$results = $results[0];
/** @var SearchResponseItem $result */
foreach ($results as $result) {
    var_dump($result->getFields());
}

Also, thanks a million for your hard work on this library !

MacFJA commented 2 years ago

The way the PaginatedResponse is built/thought of is to hold the list of individual response.

PaginatedResponse is a page, and a page contains a list of items. And those item are SearchResponseItem or AggregateResponseItem

As your search (or aggregate) can have multiple page, you can request the next page:

// 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();
/** @var array<SearchResponseItem> $items */
$items = $results->current();
// $items is a list of 5 SearchResponseItem

The sister project macfja/redisearch-integration have a special PHP Iterator (ResponseItemIterator) that allow to loop over every results (across all needed pages) like this:

/** @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) {
    // $item is a "document" result for RediSearch
    echo $item->getField('name');
}

I will write a documentation on how the PaginatedResponse object work