如何在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
相关产品推荐
相关产品推荐

