Search code examples
amazon-cloudwatchaws-cloudwatch-log-insights

AWS CloudWatch Insights - Simple Ternary IF or some similar function


Considering that I have many attributes with time measurements in my logs. I want to count how many times each of them is bigger than my timeout limit, 10 seconds for example.

I currently am able to do this running many times very similar queries like this:

fields context
| filter context.time_to_prepare > 10
| count(*) as count_slow_time_to_prepare by bin(10m)
fields context
| filter context.time_to_shine > 10
| count(*) as count_slow_time_to_shine by bin(10m)

.. one query for each attribute

It would be better and easier to plot if we could extract all these metrics in the same query. To do that, all that is missing is some ternary operator, or something similar.

My hope was that something like this would work:

fields context
| filter context.total_time > 0
| stats sum(if(context.time_to_prepare > 10,1,0)) as slow_time_to_prepare,
|       sum(if(context.time_to_shine   > 10,1,0)) as slow_time_to_shine  ,
# .. one row for each attribute
|       sum(if(context.time_to_move    > 10,1,0)) as slow_time_to_move   by bin(10m)

But that didn't work. The "if" function does not exist.

So, there is any way to make a ternary if?


Solution

  • I was pretty close,

    This code should do the job:

    fields context
    | filter context.total_time > 0
    | stats sum(context.time_to_prepare > 10) as slow_time_to_prepare,
    |       sum(context.time_to_shine   > 10) as slow_time_to_shine  ,
    # .. one row for each attribute
    |       sum(context.time_to_move    > 10) as slow_time_to_move   by bin(10m)
    

    The True and False of the a > b becomes 1 and 0 that can be used in the grouping functions like sum, avg, etc.