我正在尝试过滤使用cosmos db中的sql API查询父文档时返回的子文档。
例如给出此文档的示例:
{
"customerName": "Wallace",
"customerReference": 666777,
"orders": [
{
"date": "20181105T00:00:00",
"amount": 118.84,
"description": "Laptop Battery"
},
{
"date": "20181105T00:00:00",
"amount": 81.27,
"description": "Toner"
},
{
"date": "20181105T00:00:00",
"amount": 55.12,
"description": "Business Cards"
},
{
"date": "20181105T00:00:00",
"amount": 281.00,
"description": "Espresso Machine"
}]
}
我想查询客户以获取名称,参考和超过100.00的订单以产生这样的结果
[{
"customerName": "Wallace",
"customerReference": 666777,
"orders": [
{
"date": "20181105T00:00:00",
"amount": 118.84,
"description": "Laptop Battery"
},
{
"date": "20181105T00:00:00",
"amount": 281.00,
"description": "Espresso Machine"
}]
}]
我到目前为止的查询如下
SELECT c.customerName, c.customerReference, c.orders
from c
where c.customerReference = 666777
and c.orders.amount > 100
这将返回一个空集
[]
,如果您删除“和c.orders.amount> 100”,它将与文档匹配并返回所有订单。
要重现此问题,我只是建立了一个新数据库,添加了一个新集合,并将json示例复制为唯一文档。索引策略保留为我在下面复制的默认策略。
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*",
"indexes": [
{
"kind": "Range",
"dataType": "Number",
"precision": -1
},
{
"kind": "Range",
"dataType": "String",
"precision": -1
},
{
"kind": "Spatial",
"dataType": "Point"
}
]
}
],
"excludedPaths": []
}
答案 0 :(得分:0)
Cosmos DB不支持我在原始查询中尝试的深度过滤。
要获得所描述的结果,您需要使用结合使用ARRAY和VALUE的子查询,如下所示:
SELECT
c.customerName,
c.customerReference,
ARRAY(SELECT Value ord from ord in c.orders WHERE ord.amount > 100) orders
from c
where c.customerReference = 666777
请注意使用'ord'-'order'是保留字。
然后查询产生正确的结果-例如
[{
"customerName": "Wallace",
"customerReference": 666777,
"orders": [
{
"date": "20181105T00:00:00",
"amount": 118.84,
"description": "Laptop Battery"
},
{
"date": "20181105T00:00:00",
"amount": 281.00,
"description": "Espresso Machine"
}
]
}]