如何使用 Cosmos DB SQL 显示数组中的位置

How to display the position within an array with Cosmos DB SQL

我在尝试从 Cosmos-db 中的文档数组 select 时遇到问题。 (SQL-api)

我能够 select 数组中的值,但是我希望也能够显示数组中的每个值位置。

示例 JSON 文档:

{
    "Type": "SampleJSONMessage",
"Version": "1",
"Reference": "Test",
"DateTime": "2019-03-29T15:16:11.503Z",
"Configuration": {
    "MessageType": "1",
    "MessageConfig": "100",
    "Source": [
        {
            "Source": "Stream1"
        },
        {
            "Source": "Stream2"
        },
        {
            "Source": "Stream3"
        },
        {
            "Source": "Stream4"
        }
    ]
}
}

我执行这个:

select c.Configuration.Source 来自 c

哪个returns这个:

[
{
    "Source": "Stream1" 
},
{
    "Source": "Stream2"
},
{
    "Source": "Stream3"
},
{
    "Source": "Stream4"
}
]

这是我想要显示的:

[
{
    "Source": "Stream1" ,
    "Position": "1"
},
{
    "Source": "Stream2",
    "Position": "2"
},
{
    "Source": "Stream3",
    "Position": "3"
},
{
    "Source": "Stream4",
    "Position": "4"
}
]

感谢任何帮助!

虽然每个数组元素的 specific index 存储在 CosmosDB 中,但 SQL API 目前没有直接访问它的方法。不过,用户定义的函数将起作用。

这是我添加到 collection:

的 UDF
function ADD_INDEX(array){
    array.forEach(function(item, index){item.Position = index.toString()});
    return array;
}

以及修改后的查询以使用它来获取您想要的输出:

select udf.ADD_INDEX(c.Configuration.Source) AS Source from c