You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Cosmos DB复合索引未降低RU消耗,求正确配置方案

Cosmos DB 查询复合索引优化方案

问题分析

你的查询核心逻辑分为三部分:

  1. 等值过滤:BusinessId = 'id'
  2. 范围过滤+排序:PurchaseDate 范围查询 + ORDER BY PurchaseDate DESC
  3. 负向模糊过滤:NOT Contains(LOWER(p.TransactionIdentifier), 'history')

之前的索引配置问题:

  • (BusinessId, TransactionIdentifier):无法支持PurchaseDate的排序需求,因此系统提示无匹配索引——Cosmos DB需要复合索引包含排序字段才能避免全集合排序。
  • (BusinessId, PurchaseDate DESC, TransactionIdentifier):第三列TransactionIdentifier因查询中使用了LOWER()函数,无法命中索引(索引存储原始值,而非小写转换后的值),额外的索引列只会增大索引体积,导致RU消耗上升。

正确索引配置

只需要创建以下复合索引即可:

{
  "indexingMode": "consistent",
  "automatic": true,
  "includedPaths": [
    {
      "path": "/*"
    }
  ],
  "excludedPaths": [],
  "compositeIndexes": [
    [
      { "path": "/BusinessId", "order": "ascending" },
      { "path": "/PurchaseDate", "order": "descending" }
    ]
  ]
}

额外优化建议

  1. 去掉LOWER()函数:如果业务允许,在写入数据时将TransactionIdentifier存储为小写形式,这样查询可改为NOT Contains(p.TransactionIdentifier, 'history')。若后续该过滤条件仍有性能问题,可单独给TransactionIdentifier添加范围索引(但在BusinessId和PurchaseDate过滤后数据量不大的情况下,此步骤非必需)。
  2. 验证执行计划:在Cosmos DB数据资源管理器中查看查询执行计划,确认复合索引已被命中,且TransactionIdentifier的过滤是在索引筛选后的结果集中进行的。

内容的提问来源于stack exchange,提问作者Brandon Parker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:12:24