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

如何在Cosmos DB中结合聚合子查询过滤主查询结果?

Cosmos DB 实现重复记录详细数据查询的方法

实现思路

先通过聚合子查询筛选出符合条件的重复sourceSystemId,再将这些ID作为过滤条件传入主查询,获取对应的详细记录。

具体查询语句

-- 主查询:获取重复记录的详细数据
SELECT *
FROM c
WHERE c.sourceSystem = "Netsuite"
AND c.sourceSystemId IN (
    -- 子查询:筛选出对应多个id的重复sourceSystemId
    SELECT VALUE agg.sourceSystemId
    FROM c
    WHERE c.sourceSystem = "Netsuite"
    GROUP BY c.sourceSystemId
    HAVING COUNT(c.id) > 1
)

关键细节说明

  • 子查询中使用SELECT VALUE,只返回sourceSystemId的纯数组,避免返回包含对象的结果集,让IN子句的匹配更高效。
  • 主查询和子查询都加上c.sourceSystem = "Netsuite"的过滤,能提前缩小数据扫描范围,提升查询性能。

性能优化建议

  • 为sourceSystem和sourceSystemId创建复合索引,索引定义示例:
    {
        "indexingMode": "consistent",
        "automatic": true,
        "includedPaths": [
            {
                "path": "/sourceSystem/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String",
                        "precision": -1
                    }
                ]
            },
            {
                "path": "/sourceSystemId/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String",
                        "precision": -1
                    }
                ]
            }
        ]
    }
    
  • 避免在查询中使用不必要的字段投影,只选择需要的字段能减少数据传输量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:17:34