我正在尝试压缩和过滤CosmosDB中的json数据。 数据如下所示,我想在数组Variables中展平所有内容,然后按照数组中的特定_id和Timestamp进行过滤:
{
"_id": 21032,
"FirstConnected": {
"$date": 1522835868346
},
"LastUpdated": {
"$date": 1523360279908
},
"Variables": [
{
"_id": 99999,
"Values": [
{
"Timestamp": {
"$date": 1522835868347
},
"Value": 1
}
]
},
{
"_id": 99998,
"Values": [
{
"Timestamp": {
"$date": 1523270312001
},
"Value": 8888
}
]
}
]
}
答案 0 :(得分:3)
如果您只是通过嵌套的' _id'来寻找过滤。属性然后你可以使用ARRAY_CONTAINS w / partial_match参数设置为true。查询看起来像这样:
SELECT VALUE c
FROM c
WHERE ARRAY_CONTAINS(c.Variables, {_id: 99998}, true)
如果您还想展平数组,那么可以使用JOIN
SELECT VALUE v
FROM v IN c.Variables
WHERE v._id = 99998
答案 1 :(得分:1)
如果要使用根对象中的属性展平Variables数组中的数据,可以像这样查询集合:
SELECT root._id, root.FirstConnected, root.LastUpdated, var.Values
FROM root
JOIN var IN root.Variables
WHERE var._id = 99998
这将导致:
[
{
"_id": 21032,
"FirstConnected": {
"$date": 1522835868346
},
"LastUpdated": {
"$date": 1523360279908
},
"Values": [
{
"Timestamp": {
"$date": 1523270312001
},
"Value": 8888
}
]
}
]
如果你想甚至展平Values数组,你需要写这样的东西:
SELECT root._id, root.FirstConnected, root.LastUpdated,
var.Values[0].Timestamp, var.Values[0]["Value"]
FROM root
JOIN var IN root.Variables
WHERE var._id = 99998
请注意,CosmosDB会考虑" Value"作为保留关键字,您需要使用escpape语法。此查询的结果是:
[
{
"_id": 21032,
"FirstConnected": {
"$date": 1522835868346
},
"LastUpdated": {
"$date": 1523360279908
},
"Timestamp": "1970-01-01T00:00:00Z",
"Value": 8888
}
]
检查更多详情https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sql-query#Advanced