【问题标题】:CosmosDB MongoDB 3.6 fails sort() query with compounded indexCosmosDB MongoDB 3.6 使用复合索引的 sort() 查询失败
【发布时间】:2020-04-09 10:49:36
【问题描述】:

Newby MongoDB 和 CosmosDB 用户在这里,我已经阅读了这个问题的答案 How does MongoDB treat find().sort() queries with respect to single and compound indexes? 和官方 MongoDB 文档,我相信我的索引创建反映了这个答案,所以我倾向于这是一个 CosmosDB 问题,但阅读他们的文档CosmosDB 3.6 也支持复合索引,所以我现在很茫然。

我可以从 mongo 命令行对一个索引创建为db.Videos.createIndex({"PublishedOn": 1})db.Videos.createIndex({"PublishedOn": -1}) 的集合运行类似db.Videos.find().sort({"PublishedOn": 1}) 的sort() 查询。

当我像 db.Videos.find({"IsPinned": false}).sort({"PublishedOn": 1}) 这样在 find 中添加 'where' 子句时,上述索引仍然有效。

但是我现在有想要避免的文档查找,所以我删除了上面的单字段索引并创建了一个复合索引,如 db.Videos.createIndex({"IsPinned": 1, "PublishedOn": 1})db.Videos.createIndex({"PublishedOn": 1, "IsPinned": 1}) 但现在查询总是失败并出现错误 The index path corresponding to the specified order-by item is excluded. .

这是 CosmosDB 的限制还是我在索引中的“排序”不好?

【问题讨论】:

  • Cosmos 是一个独立的实现,不与 MongoDB 共享任何底层服务器代码,因此您无法根据 MongoDB 部署支持的内容推断预期行为。例如,错误 The index path corresponding to the specified order-by item is excluded 特定于 Cosmos 的 API。我希望{"PublishedOn": 1, "IsPinned": 1} 上的索引应该可用(或者更确切地说,MongoDB 根据您的查询使用)。似乎 Cosmos 可能需要不同的索引定义来支持排序。也许索引中的PublishedOn 排序顺序必须与查询匹配?
  • 你说 CosmosDB 不是 MongoDB 是绝对正确的,我希望我没有用我的问题来推断。

标签: azure-cosmosdb-mongoapi


【解决方案1】:

CosmosDB 的问题在于它希望所有 WHERE 字段都以完全相同的顺序在 GROUP BY 子句中使用,否则它不会使用索引。

将索引创建为db.Videos.createIndex({"IsPinned": 1, "PublishedOn": 1}),然后将查询更新为db.Videos.find({"IsPinned": false}).sort({"IsPinned": 1, "PublishedOn": 1}) 就像一个魅力。

我通过阅读 CosmosDB 文档中关于索引策略 (https://docs.microsoft.com/en-us/azure/cosmos-db/index-policy) 推断出这一点,因为 MongoDB 文档在索引创建 (https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-indexing) 部分之后突然停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多