在noSQL类型文档上通过SQL从父级属性名称创建新属性

时间:2019-04-19 00:43:15

标签: sql nosql azure-cosmosdb

问题

我试图编写一个SQL查询,以使该属性的子属性成为该子属性中“新”属性的一部分。例如,示例文档如下所示:

[
    {
        "StudentId": "12",
        "Classes" : {
            "Math":{
               "Location": "RoomA",
               "Grade": "A"
            },
            "Science": {
                "Location": "RoomB",
                "Grade": "B"
            }
        }
    }
]

目标

目标是查询该文档以获得如下结果:

[
    {
        "StudentId": "12",
        "Classes" : {
                "Name": "Math",
                "Location": "RoomA",
                "Grade": "A"
                },
                {
                "Name": "Science",
                "Location": "RoomB",
                "Grade": "B"
                }
        }
    }
]

我的第一步是弄清楚如何在没有实际属性的情况下实际获取相应的类名。我的以下SQL查询:

SELECT t.StudentId, {"Name": t.Classes.Math} FROM t WHERE t.StudentId= "12"

例如,在“ Math”中抓住了整个结构:

[
    {
        "TenantId": "12",
        "Classes": {
            "Name": {
                "Location": "RoomA",
                "Grade": "A"
            }
        }
    }
]

编辑:我正在用它来查询CosmosDB文档

1 个答案:

答案 0 :(得分:0)

您的需求需要更改sql查询中未涉及的文档原始结构。

我建议您使用cosmos db存储过程作为解决方法,请参阅我的示例代码:

function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT r.StudentId,r.Classes FROM r',
    function (err, feed, options) {
        if (err) throw err;
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            returnArray = [];
            for(var i =0;i<feed.length;i++){
                classArray = [];   
                for(var key in feed[i].Classes)
                {
                   var map = {};
                   map["Name"] = key;          
                   map["Location"] = feed[i].Classes[key].Location;
                   map["Grade"] = feed[i].Classes[key].Grade;
                   classArray.push(map);
                }
                feed[i].Classes = classArray;
            }         
            response.setBody(feed);
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.'); }

输出:

enter image description here