如何在CosmosDB文档中别名数组元素?

时间:2020-01-06 08:00:22

标签: azure-cosmosdb azure-cosmosdb-sqlapi

我有以下文件

{
        "VehicleDetailId": 1,
        "VehicleDetail": [
            {
                "Id": 1,
                "Make": "BMW"
            },
            {
                "Id": 1,
                "Model": "ABDS"
            },
            {
                "Id": 1,
                "Trim": "5.6L/ASMD"
            },
            {
                "Id": 1,
                "Year": 2008
            }
        ]
}

我想给数组元素起别名,像这样

{
        "VehicleDetailId": 1,
        "Type": "VehicleDetail",
        "VehicleDetail": [
            {
                "MakeId": 1,
                "MakeValue": "BMW"
            },
            {
                "ModelId": 1,
                "ModelValue": "ABDS"
            },
            {
                "TrimId": 1,
                "TrimValue": "5.6L/ASMD"
            },
            {
                "YearId": 1,
                "YearValue": 2008
            }
        ]
}

以下查询似乎可以正常工作,但是由于Id对所有人都是通用的,因此每次都会重复。

SELECT c.vehicleDetailId, ARRAY(SELECT v.Id AS MakeId, v.Make AS MakeValue,
                                       v.Id AS ModelId, v.Model AS ModelValue,
                                       v.Id AS TrimId, v.Trim AS TrimValue,
                                       v.Id AS YearId, v.Year AS YearValue
                                FROM v IN c.VehicleDetail) AS VehicleDetail 
FROM c

我应该如何编写查询,以使ID不会每次都重复,并且可以从特定位置获取元素?

1 个答案:

答案 0 :(得分:1)

您可以使用UDF满足您的需求。

Udf代码:

function userDefinedFunction(array){
    var returnArray = [];
    for(var i=0;i<array.length;i++){
        var obj = array[i];
        var map = {};
        if(obj.Make){
            map["MakeId"]= obj.Id;
            map["MakeValue"]= obj.Make;
        }else if(obj.Model){
            map["ModelId"]= obj.Id;
            map["ModelValue"]= obj.Model;
        }else if(obj.Trim){
            map["TrimId"]= obj.Id;
            map["TrimValue"]= obj.Trim;
        }else if(obj.Year){
            map["YearId"]= obj.Id;
            map["YearValue"]= obj.Year;
        } 
        returnArray.push(map);
    }
    return returnArray;
}

Sql:

SELECT c.VehicleDetailId,udf.test(c.VehicleDetail) AS VehicleDetail 
FROM c

输出:

enter image description here