31

I have CWL Entries as below. Showing entries in SQL Type for clarity

Name City
1     Chicago
2     Wuhan
3     Chicago
4     Wuhan
5     Los Angeles

Now I want to get below output

City         Count
Chicago        2
Wuhan          2
Los Angeles    1

Is there a way I can run GROUP BY in CWL Insights.

Pseudo Query

Select Count(*), City From {TableName} GROUP BY City

1 Answer 1

82

You can use the aggregation function count with the by statement: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html

Here is a full example for your case, assuming the logs contain the entries exactly as you have in the example (regex for city name is very simple, you may want to refine that).

fields @timestamp, @message
| parse @message /^(?<number>\d+)\s+(?<city>[a-zA-Z\s]+)$/
| filter ispresent(city)
| stats count(*) by city

Result:

---------------------------
|     city     | count(*) |
|--------------|----------|
| Chicago      | 2        |
| Wuhan        | 2        |
| Los Angeles  | 1        |
---------------------------
5
  • Good query! Is there a way to give an alias to count(*), similar to sql where aliasing can be used?
    – Nida
    Commented Sep 9, 2020 at 1:13
  • 4
    You can use as in a similar way you would in sql: docs.aws.amazon.com/AmazonCloudWatch/latest/logs/… Commented Sep 9, 2020 at 7:08
  • 1
    @Nida you just do | stats count(*) as counts by city Commented Apr 8, 2022 at 7:33
  • is there any way of simple group by query. I mean I do not want the aggregation like count, sum, avg etc. Like taking above example it will only return data grouped by cities. So that I can get all the names of from each city.
    – Arshad Ali
    Commented Jun 14, 2022 at 9:53
  • 1
    You can do the aggregation and the just drop the numbers. Like this: stackoverflow.com/questions/72309353/… Commented Jun 15, 2022 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.