在 Azure DocumentDB / Azure CosmosDB 中选择字典的键和值



考虑存储在 DocumentDB 中的这两个示例文档。

文档 1

"JobId": "04e63d1d-2af1-42af-a349-810f55817602",
"JobType": 3,
"
"Properties": {
"Key1": "Value1",
"Key2": "Value2"
}
"KeyNames": ["Key1", "Key2"]

文档 2

"JobId": "04e63d1d-2af1-42af-a349-810f55817603",
"JobType": 4,
"
"Properties": {
"Key3": "Value3",
"Key4": "Value4"
}
"KeyNames": ["Key3", "Key4"]

我想为每个文档选择属性对象中的所有键和所有值。 像这样:

SELECT 
c.JobId,
c.JobType,
c.Properties.<Keys> AS Keys,
c.Properties.<Values> AS Values
FROM c

但如您所见,密钥不是固定的。那么我该如何列出它们呢?所以最后我得到了这样的结果。我不能使用 .NET 或 LINQ。我需要在 DocumentDB 查询资源管理器中执行查询。

[
{
"JobId": "04e63d1d-2af1-42af-a349-810f55817602",
"JobType": 3,
"Key1": "Value1"
}
{
"JobId": "04e63d1d-2af1-42af-a349-810f55817602",
"JobType": 3,
"Key2": "Value2"
}
{
"JobId": "04e63d1d-2af1-42af-a349-810f55817603",
"JobType": 4,
"Key3": "Value3"
}
{
"JobId": "04e63d1d-2af1-42af-a349-810f55817603",
"JobType": 4,
"Key4": "Value4"
}
]

我能够在DocumentDB中使用UDF解决我的问题。因为键名是一个数组。自加入正在返回密钥。

所以这个查询。

SELECT 
c.JobId,
c.JobType,
Key,
udf.GetValueUsingKey(c.Properties, Key) AS Value
FROM collection AS c
JOIN Key in c.KeyNames

返回了我想要的结果。

可以使用 DocumentDB 中提供的脚本资源管理器来定义 UDF。 出于我的目的,我使用了:

function GetValueUsingKey(Properties, Key) { 
var result = Properties[Key];
return JSON.stringify(result);
}

希望这对:)有所帮助

最新更新