简体   繁体   中英

How to group data by date in Azure Cosmos DB?

I am building an analytic tool and I am using Azure function and Azure Cosmos to do the backend.

The tool is working, but some widgets are too heavy and need to retrieve too much data from Cosmos. So instead of getting a lot of data from Cosmos, and then parse this data on the frontend (javascript), I reached the conclusion that I need to do the opposite. But these are quite complex queries to manage in SQL.

The basic topo is while a visitor starts to watch a video, I have a log of type "Play" that is created (an entry in Cosmos DB). Later I can fetch all the "Play" logs for a period of time, and manipulating data in Javascript to get the number of plays per minute, like below:

const results = [
  "2021-04-15T15:47:34": 3,
  "2021-04-15T15:47:35": 7,
  "2021-04-15T15:47:36": 2,
  "2021-04-15T15:47:37": 13,
  //and so on
]

Then I use those data to have a graph that is displaying the number of play per minutes

The query I am using right now in Azure is:

SELECT c.id,c.date,c.type FROM c WHERE c.liveId = "{ID}" AND c.type = "Play" AND (c.date BETWEEN "2021-06-04T12:31:30.233Z" AND "2021-07-31T21:59:59.999Z")

And it returns me:

      {
        "id": "0eef48c0-a797-4461-8d59-0a8a5d546c1c",
        "date": "2021-04-15T12:35:29.118Z",
        "type": "Load"
      },
      {
        "id": "b52b0a35-99ab-4e17-a2d3-9f638501c97f",
        "date": "2021-04-15T12:35:29.164Z",
        "type": "Load"
      },
      {
        "id": "ce2d5326-06a9-4d0b-9eb2-8cede6ada7eb",
        "date": "2021-04-15T12:35:29.164Z",
        "type": "Load"
      },
      {
        "id": "dd0a225c-1806-4c08-a5a4-c65f092e3928",
        "date": "2021-04-15T12:35:29.187Z",
        "type": "Load"
      },

Is there any way to do build such a query in Cosmos to get:

const results = [
  "2021-04-15T15:47:34": 3,
  "2021-04-15T15:47:35": 3,
  "2021-04-15T15:47:36": 3,
  "2021-04-15T15:47:37": 3,
  //and so on
]

directly from the query?

I searched but didn't find anything really clear about grouping by date on Cosmos.

You can try below query once, it could differ a little based on properties but can be used to do group by with count. Just to add date should match including timestamp for below query to work, otherwise count could differ.

Updated:

select d.newdate,d.cnt  from
(SELECT left(c.date,16) as newdate,count(c.date) as cnt FROM c
WHERE c.type = 'Load' and (c.date between '2021-03-04T12:31:30.233Z' AND '2021-07-31T21:59:59.999Z')
group by left(c.date,16)) d

Result( Updated ):

[
    {
        "newdate": "2021-04-15T12:35",
        "cnt": 7
    },
    {
        "newdate": "2021-04-15T12:36",
        "cnt": 3
    }
]

Then you can use this data in JavaScript accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM