代码之家  ›  专栏  ›  技术社区  ›  Jayendran

Azure Cosmos查询要转换为列表

  •  0
  • Jayendran  · 技术社区  · 5 年前

    这是我的JSON数据,存储在cosmos数据库中

    {
        "id": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
        "Name": "Name",
        "keyData": {
            "Keys": [
                "Government",
                "Training",
                "support"
            ]
        }
    }
    

    现在我想写一个查询来消除 keyData Keys (如下图所示)

    {
        "userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
        "Name": "Name",
        "Keys"  :[
            "Government",
            "Training",
            "support"
        ]
    }
    

    到目前为止,我尝试了如下查询

    SELECT c.id,k.Keys  FROM c
    JOIN k in c.keyPhraseBatchResult 
    

    在尝试使用 萨吉塔兰 现在我可以得到结果了,但问题是它会在数组中生成另一个JSON。

    喜欢

    {
        "id": "ee885fdc-9951-40e2-b1e7-8564003cd554",
        "keys": [
            {
                "serving": "Government"
            },
            {
                "serving": "Training"
            },
            {
                "serving": "support"
            }
        ]
    }
    

    是否有任何方法可以只提取数组而不提取 key value 又是巴黎?

    {
        "userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
        "Name": "Name",
        "Keys"  :[
            "Government",
            "Training",
            "support"
        ]
    } 
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   Sajeetharan    5 年前

    你可以试试这个,

    SELECT C.id, ARRAY(SELECT VALUE serving FROM serving IN C.keyData.Keys) AS Keys FROM C 
    
        2
  •  1
  •   Jay Gong    5 年前

    请使用cosmos db存储过程根据@Sajeetharan的sql实现所需的格式。

    function sample() {
        var collection = getContext().getCollection();
    
        var isAccepted = collection.queryDocuments(
            collection.getSelfLink(),
            'SELECT C.id,ARRAY(SELECT serving FROM serving IN C.keyData.Keys) AS keys FROM C',
        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();
                var map = {};
                 for(var i=0;i<feed.length;i++){
                     var keyArray = feed[i].keys;
                     var array = [];
                     for(var j=0;j<keyArray.length;j++){
                        array.push(keyArray[j].serving)
                     }
                     feed[i].keys = array;
                 }
                response.setBody(feed);
            }
        });
    
        if (!isAccepted) throw new Error('The query was not accepted by the server.');
    }
    

    enter image description here