首页 文章

Azure Cosmos数据库聚合和索引

提问于
浏览
0

我正在尝试使用Cosmos DB而且我在集合中进行简单计数时遇到了一些麻烦 .

我的集合架构如下,我在这个集合中有80.000个文档 .

{
    "_id" : ObjectId("5aca8ea670ed86102488d39d"),
    "UserID" : "5ac161d742092040783a4ee1",
    "ReferenceID" : 87396,
    "ReferenceDate" : ISODate("2018-04-08T21:50:30.167Z"),
    "ElapsedTime" : 1694,
    "CreatedDate" : ISODate("2018-04-08T21:50:30.168Z")
}

如果我在下面运行此命令来计算集合中的所有文档,我会很快得到结果:

db.Tests.count()

但是当我向同一个用户运行同样的命令时,我收到一条消息“请求率很大” .

db.Tests.find({UserID:"5ac161d742092040783a4ee1"}).count()

在Cosmos DB文档中,我发现了这个cenario,建议增加RU . 目前我有400 RU / s,当我增加到10.000 RU / s时,我能够在没有错误的情况下运行命令,但是在5秒内 .

我已经尝试创建索引明确,但似乎Cosmos DB不使用索引进行计数 .

我不认为在大约100,000个文档的集合中为一个简单的计数支付10,000 RU / s是不合理的,尽管大约需要5秒 .

1 回答

  • 1

    过滤查询计数使用索引(如果可用) .

    如果您尝试按非索引列上的过滤器计数,则查询不会超时,但会失败 . 试试吧 . 您应该得到以下错误:

    {“错误”:[“指定了无效的查询,其中包含针对从索引中排除的路径的过滤器 . 请考虑在请求中添加允许扫描标头 . ”]}

    So definitely add a suitable index on UserID.

    如果你没有得到上述错误,那么你可能已经设置了 enableScanInQuery 标志 . 这几乎总是一个坏主意,全扫描不会扩展 . 含义 - 随着数据集的增长,它将消耗越来越多的RU . 所以 make sure it is off and index instead.

    如果您在所选列上有索引,则应运行查询 . 您可以通过发送x-ms-documentdb-populatequerymetrics标头 verify that index is actually being used . 哪个应该返回 indexLookupTimeInMsindexUtilizationRatio 字段的确认 . 示例输出:

    “totalExecutionTimeInMs = 8.44; queryCompileTimeInMs = 8.01; queryLogicalPlanBuildTimeInMs = 0.04; queryPhysicalPlanBuildTimeInMs = 0.06; queryOptimizationTimeInMs = 0.00; VMExecutionTimeInMs = 0.14; indexLookupTimeInMs = 0.11; documentLoadTimeInMs = 0.00; systemFunctionExecuteTimeInMs = 0.00; userFunctionExecuteTimeInMs = 0.00; retrievalDocumentCount = 0; detectedDocumentSize = 0; outputDocumentCount = 1; outputDocumentSize = 0; writeOutputTimeInMs = 0.01; indexUtilizationRatio = 0.00"

    如果您觉得RU费用太大,它还会为您提供一些洞察力 .

    如果索引查找时间本身太高,请考虑索引是否足够有选择性以及索引设置是否合适 . 查看您的 UserId 值和分布并相应地调整索引 .


    另一个值得考虑的猜测是 check if the API you are using would defer executing find(..) ,直到它知道 count() 真的是你所追求的 . 目前还不清楚您正在使用哪种API . 如果事实证明它在进行计数之前将所有匹配的文档提取到客户端那么这将解释意外的高RU成本,特别是如果涉及大量匹配文档或大文档 . Check the API documentation .

    我还建议 executing the same query directly in Azure Portal to compare the RU cost 并验证问题是否与客户有关 .

相关问题