2

This is my JSON data, which is stored into cosmos db

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

Now I want to write a query to eliminate the keyData and get only the Keys (like below)

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

So far I tried the query like

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

Which is not working.

Update 1:

After trying with the Sajeetharan now I can able to get the result, but the issue it producing another JSON inside the Array.

Like

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

Is there is any way that extracts only the Array without having key value pari again?

{
    "userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
    "Name": "Name",
    "Keys"  :[
        "Government",
        "Training",
        "support"
    ]
} 
Jayendran
  • 9,638
  • 8
  • 60
  • 103

2 Answers2

2

You could try this one,

SELECT C.id, ARRAY(SELECT VALUE serving FROM serving IN C.keyData.Keys) AS Keys FROM C 
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Please use cosmos db stored procedure to implement your desired format based on the @Sajeetharan's 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.');
}

Output:

enter image description here

Jay Gong
  • 23,163
  • 2
  • 27
  • 32
  • Thanks @jaygong upvoted since sajeetharan updated query worked now. But with your solution I learned how to achieve this using storproc. Thanks again ! – Jayendran Mar 12 '19 at 04:38
  • @Jayendran Thank you.@sajeetharan's solution is very nice for you. – Jay Gong Mar 12 '19 at 06:17