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

如何在Cosmos DB中根据嵌套值查询目标对象

Azure Cosmos DB 嵌套属性查询解决方案

文档格式修正

你的示例JSON存在格式问题,Cosmos DB中每个条目是独立的文档,正确的单文档结构如下:

{
  "id": "fruit-doc-1",
  "Fruit": {
      "Apples": 200,
      "Oranges": 130,        
      "Strawberries": {
          "Small": 30,
          "Large": "Finished"
      }
  }
}
{
  "id": "fruit-doc-2",
  "Fruit": {
      "Apples": 78,
      "Oranges": 90,        
      "Strawberries": {
          "Small": 10,
          "Large": 30
      }
  }
}

核心查询语句

使用Cosmos DB SQL语法,直接筛选嵌套属性并返回目标Fruit对象:

SELECT c.Fruit
FROM c
WHERE c.Fruit.Strawberries.Large = "Finished"

执行后会仅返回Strawberries.Large值为"Finished"的Fruit对象(即示例中的第一个对象)。

如果需要返回完整文档而非仅Fruit节点,修改查询为:

SELECT c
FROM c
WHERE c.Fruit.Strawberries.Large = "Finished"

性能优化(可选)

若集合数据量较大,为避免全表扫描,可给嵌套属性/Fruit/Strawberries/Large创建范围索引:
在集合的索引策略中添加如下配置:

{
  "indexingMode": "consistent",
  "automatic": true,
  "includedPaths": [
    {
      "path": "/Fruit/Strawberries/Large/?",
      "indexes": [
        {
          "kind": "Range",
          "dataType": "String",
          "precision": -1
        }
      ]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:26:03