doctrine / couchdb-client

CouchDB Client library
MIT License
122 stars 68 forks source link

Pagination #65

Open xub opened 8 years ago

xub commented 8 years ago

how to pagination ?

swysor commented 7 years ago

Per the couch documentation there are a couple ways to do this: http://docs.couchdb.org/en/2.0.0/couchapp/views/pagination.html

skipping method:

For a view query to be paginated, you just use the limit=10 then subsequent call would be limit=10 & skip=10 (these are settings you can apply to the Query class returned by the clients createViewQuery()). With this method your paging logic would have to guard against less than 10 rows being returned as this would indicate the "end of pages". If done via an API you would need to return the current_skip_value and next_skip_value to the API client so they could know how many records to skip next time.

So first query would be like

    $client = CouchDBClient::create($options);  
    $query = $client->createViewQuery();
    $query->setLimit(10);
    $first_page = $query->execute();

second queries would be:

    $query->setSkip(10);
    $second_page = $query->execute();

third query would then be:

    $query->setSkip(20);
    $third_page = $query->execute();

paging method

The alternitive way is via the what the couchdb documenation refers to as the "paging" method.

EG: For a 10 record page, you would ask for 11 rows back, you only display up to the 10th row and you return the 11th id as your "next_start_key". Subsequent requests would specify start_key as the previous next_start_key. NOTE: becasue the view keys do not have to be unique, I normally use start_key_docid for this instead as this will break if the keys are not unique (and in a lot of cases mine are not).

There are functions in the Query class https://github.com/doctrine/couchdb-client/blob/master/lib/Doctrine/CouchDB/View/Query.php (which is what the client gives you an instance of when you call createViewQuery) that expose these as:

$query->setStartKey(<some key>);
//or better
$query->setLimit(11);
$first_page  = $query->execute();

$second_page = $query->setStartKeyDocId(<doc_id of first_page 11th result>);
$third_page = $query->setStartKeyDocId(<doc_id of second_page 11th result>);

Hope that helps!