c# - 如何使用查询从 cosmos db 中获取最大 id 值
问题描述
我想从 cosmos DB 中获取 id 的最大值。下面的代码运行良好,直到 cosmos DB 包含的文档少于 1000。如果超过,它总是给出 999 作为最大值。
尝试在 FeedOptions 中添加 MaxItemCount=-1。
public async Task<int> GetMaxId()
{
try
{
var option = new FeedOptions { EnableCrossPartitionQuery = true ,MaxItemCount=-1};
// SQL
var familiesSqlQuery = client.CreateDocumentQuery(cosmosConnector,
"SELECT value max(c.id) FROM c", option).AsDocumentQuery();
var val = await familiesSqlQuery.ExecuteNextAsync();
var s = val.FirstOrDefault();
return int.Parse(s.ToString());
}
catch
{
throw;
}
}
解决方案
实现您想要的可靠方法如下:
public async Task<int> GetMaxId()
{
try
{
var maxValue = 0;
var option = new FeedOptions { EnableCrossPartitionQuery = true };
// SQL
var familiesSqlQuery = client.CreateDocumentQuery(cosmosConnector,
"SELECT c.id FROM c", option).AsDocumentQuery();
while(familiesSqlQuery.HasMoreResults)
{
var ids = await familiesSqlQuery.ExecuteNextAsync();
var maxIdInBatch = ids.Select(int.Parse).Max();
if(maxIdInBatch > maxValue)
{
maxValue = maxIdInBatch;
}
}
return maxValue;
}
catch
{
throw;
}
}
出现这种情况的原因是您的 RU 不会因单个调用而耗尽,因为您将对所有结果进行分页。这将需要更长的时间,但它将是可靠和准确的。
推荐阅读
- svn - 如何在 Eggplant 上使用 TFS(Team Foundation Server)?
- database - 尝试生成一些活动来生成归档日志
- javascript - 如何从表的 CKEditor 上下文菜单中删除“删除表”选项
- python - Docker:不同python版本的相同pip缓存目录
- javascript - 在这种情况下如何按键对一组对象进行分组
- wordpress - 默认产品简短描述
- continuous-integration - 即兴创作使用代码管道和代码构建的 CI-CD 的最佳方式
- java - 调用方法后,其余代码在java中不起作用
- java - java.lang.RuntimeException:org.gradle.api.internal.provider.MissingValueException
- python - python为什么我的变量没有改变和使用我的字典