Created
March 27, 2021 13:23
-
-
Save frantisekjandos/69a52d442ece13225cfca2eb843c6173 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.Azure.Cosmos; | |
using Microsoft.Azure.Cosmos.Fluent; | |
using Microsoft.Azure.Cosmos.Linq; | |
namespace Devteam.CosmosPagingTest | |
{ | |
class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
var cosmosClient = new CosmosClientBuilder("connstr") | |
.WithConnectionModeDirect() | |
.WithThrottlingRetryOptions(TimeSpan.FromSeconds(3), 1) | |
.WithApplicationName("NotificationService") | |
.WithRequestTimeout(TimeSpan.FromMinutes(10)) | |
.Build(); | |
var container = cosmosClient.GetContainer("db", "container"); | |
const string recipientId = "xxx"; | |
const int take = 10; | |
await TestOffsetLimit(recipientId, container, take); | |
Console.WriteLine(); | |
await TestIterator(recipientId, container, take); | |
} | |
private static async Task TestIterator(string recipientId, Container container, int take) | |
{ | |
var feedIterator = container.GetItemLinqQueryable<Notification>(true, null, | |
new QueryRequestOptions {PartitionKey = new PartitionKey(recipientId), MaxItemCount = take}) | |
.Where(n => n.RecipientId == recipientId) | |
.OrderByDescending(x => x.ValidFrom) | |
.ToFeedIterator(); | |
while (feedIterator.HasMoreResults) | |
{ | |
var response = await feedIterator.ReadNextAsync(); | |
Console.WriteLine($"{response.RequestCharge}"); | |
} | |
} | |
private static async Task TestOffsetLimit(string recipientId, Container container, int take) | |
{ | |
var skip = 0; | |
while (true) | |
{ | |
var notifications = await GetBatch(recipientId, container, skip, take); | |
if (notifications.Count < take) | |
{ | |
return; | |
} | |
skip += take; | |
} | |
} | |
private static async Task<IList<Notification>> GetBatch(string recipientId, Container container, int skip, int take) | |
{ | |
var feedIterator = container.GetItemLinqQueryable<Notification>(true, null, | |
new QueryRequestOptions {PartitionKey = new PartitionKey(recipientId)}) | |
.Where(n => n.RecipientId == recipientId) | |
.OrderByDescending(x => x.ValidFrom) | |
.Skip(skip) | |
.Take(take) | |
.ToFeedIterator(); | |
var batch = new List<Notification>(); | |
while (feedIterator.HasMoreResults) | |
{ | |
var response = await feedIterator.ReadNextAsync(); | |
Console.WriteLine($"{response.RequestCharge}"); | |
batch.AddRange(response); | |
} | |
return batch; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment