azure-cosmosdb – 文档计数查询忽略PartitionKey

我希望得到所选分区中所有文档的计数.但是,以下代码将返回集合中所有文档的计数,并且成本为0 RU.

    var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);

    string command = "SELECT VALUE COUNT(1) FROM Collection c";

    FeedOptions feedOptions = new FeedOptions()
    {
        PartitionKey = new PartitionKey(BuildPartitionKey(contextName, domainName)),
        EnableCrossPartitionQuery = false
    };

    var count = client.CreateDocumentQuery<int>(collectionLink, command, feedOptions)
        .ToList()
        .First();

向查询添加WHERE c.partition =’blah’子句将起作用,但在集合中花费3.71 RU且包含11个文档.

为什么上面的代码片段会返回整个Collection的Count,是否有更好的解决方案来获取所选分区中所有文档的数量?

最佳答案

If the query includes a filter against the partition key, like SELECT
* FROM c WHERE c.city = “Seattle”, it is routed to a single partition. If the query does not have a filter on partition key, then it is
executed in all partitions, and results are merged client side.

当我们向Azure Cosmos DB发出查询时,您可以检查SDK在此官方doc中执行的逻辑步骤.

If the query is an aggregation like COUNT, the counts from individual
partitions are summed to produce the overall count.

因此,当您只使用SELECT VALUE COUNT(1)FROM Collection c时,它将在所有分区中执行,结果将合并到客户端.

如果要获取所选分区中所有文档的计数,只需添加where c.partition =’XX’过滤器.

希望它能帮到你.

点赞