Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CosmosDB sort results by a value into an array

I've some CosmosDB documents like the following

{
  "ProductId": 1,
  "Status": true,
  "Code": "123456",
  "IsRecall": false,
  "ScanLog": [
    {
      "Location": {
        "type": "Point",
        "coordinates": [
          13.5957758,
          42.7111538
        ]
      },
      "TimeStamp": 201602160957190600,
      "ScanType": 0,
      "UserId": "1004"
    },
    {
      "Location": {
        "type": "Point",
        "coordinates": [
          13.5957907,
          42.7111359
        ]
      },
      "TimeStamp": 201602161246336640,
      "ScanType": 0,
      "UserId": "1004"
    }
  ]
}

How can I order the query results by the TimeStamp property? I've tried using this query

SELECT c.Code, b.TimeStamp FROM c JOIN b IN c.ScanLog ORDER BY b.TimeStamp

but I receive this error

Order-by over correlated collections is not supported.

What is the correct way to do this?

like image 551
Matteo Avatar asked Feb 23 '16 17:02

Matteo


1 Answers

JOINs with ORDER BY are currently not supported.

However, here is a user defined function (UDF) that will do the trick:

function sortScanLog (scanLog) { 
  function compareTimeStamps(a, b) {
    return a.TimeStamp - b.TimeStamp;
  }
  return scanLog.sort(compareTimeStamps);
}

You use with a query like this:

SELECT c.ProductId, udf.sortScanLog(c.ScanLog) as ScanLog FROM c

If you want the opposite sort order, simply swap the a and b. So, the signature of the compareTimeStamps inner function would be:

function compareTimeStamps(b, a)

Alternatively, you can sort client-side after the results are returned.

like image 145
Larry Maccherone Avatar answered Sep 28 '22 08:09

Larry Maccherone