我需要支持Azure Cosmos DB的分页。我知道Cosmos DB可以在下一组结果上进行连续令牌。但是我不明白如何导航到以前的结果。
据我所知,从官方方式中,您只能基于连续令牌实施分页。您需要封装方法来实现这一点。
您可以参考@Nick撰写的文档。另外,您可以参考以下示例代码:
private static async Task<KeyValuePair<string, IEnumerable<CeleryTask>>> QueryDocumentsByPage(int pageNumber, int pageSize, string continuationToken)
{
DocumentClient documentClient = new DocumentClient(new Uri("https://{CosmosDB/SQL Account Name}.documents.azure.com:443/"), "{CosmosDB/SQL Account Key}");
var feedOptions = new FeedOptions {
MaxItemCount = pageSize,
EnableCrossPartitionQuery = true,
// IMPORTANT: Set the continuation token (NULL for the first ever request/page)
RequestContinuation = continuationToken
};
IQueryable<CeleryTask> filter = documentClient.CreateDocumentQuery<CeleryTask>("dbs/{Database Name}/colls/{Collection Name}", feedOptions);
IDocumentQuery<CeleryTask> query = filter.AsDocumentQuery();
FeedResponse<CeleryTask> feedRespose = await query.ExecuteNextAsync<CeleryTask>();
List<CeleryTask> documents = new List<CeleryTask>();
foreach (CeleryTask t in feedRespose)
{
documents.Add(t);
}
// IMPORTANT: Ensure the continuation token is kept for the next requests
return new KeyValuePair<string, IEnumerable<CeleryTask>>(feedRespose.ResponseContinuation, documents);
}
然后,以下示例说明了如何通过调用上一个方法来检索给定页面的文档:
private static async Task QueryPageByPage()
{
// Number of documents per page
const int PAGE_SIZE = 3;
int currentPageNumber = 1;
int documentNumber = 1;
// Continuation token for subsequent queries (NULL for the very first request/page)
string continuationToken = null;
do
{
Console.WriteLine($"----- PAGE {currentPageNumber} -----");
// Loads ALL documents for the current page
KeyValuePair<string, IEnumerable<CeleryTask>> currentPage = await QueryDocumentsByPage(currentPageNumber, PAGE_SIZE, continuationToken);
foreach (CeleryTask celeryTask in currentPage.Value)
{
Console.WriteLine($"[{documentNumber}] {celeryTask.Id}");
documentNumber++;
}
// Ensure the continuation token is kept for the next page query execution
continuationToken = currentPage.Key;
currentPageNumber++;
} while (continuationToken != null);
Console.WriteLine("n--- END: Finished Querying ALL Dcuments ---");
}
顺便说一句,您可以在Cosmos DB反馈中遵循以下有关此功能的痕迹:
- https://github.com/azure/azure-documentdb-dotnet/issues/377
- https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6350987--documentdb-ablow-palla-palla-pagel-paging-skip-skip-take