日志见解查询 - 通过数据透视进行分组
我有一个 CloudWatch 日志流,其中包含如下所示的结构化记录:
type | env |
---|---|
type1 | dev |
type1 | prod |
type2 | dev |
我想通过 env 查询每种类型的计数(以绘制它们的图表)
相当于以下 SQL 语句:
SELECT
SUM(CASE WHEN env = 'dev' THEN 1 ELSE 0 END) AS dev,
SUM(CASE WHEN env = 'prod' THEN 1 ELSE 0 END) AS prod
FROM TABLE
GROUP BY type
I已经编写了以下查询:
fields @timestamp, record.type as type, record.env as env
| stats count(env="dev") as dev, count(env="prod") as prod by type
期望得到以下结果:
type | dev | prod |
---|---|---|
type1 | 1 | 1 |
type2 | 1 | 0 |
但不幸的是,无论应用内部的过滤器如何,我都会得到相同的两列计数count()
如下:
如何实现我需要的输出
注意
我可以执行以下查询来获取按每个 env
:
fields @timestamp, record.type as type, record.env as env
| stats count(*) by type, env
我会得到:
类型 | env | count() |
---|---|---|
type1 | dev | 1 |
type1 | prod | 1 |
type2 | dev | 1 |
但我需要旋转版本
I have a CloudWatch log stream that contains structured records like the following:
type | env |
---|---|
type1 | dev |
type1 | prod |
type2 | dev |
I'd like to query the counts of each type by the env (to graph them)
Something equivalent to the following SQL statement:
SELECT
SUM(CASE WHEN env = 'dev' THEN 1 ELSE 0 END) AS dev,
SUM(CASE WHEN env = 'prod' THEN 1 ELSE 0 END) AS prod
FROM TABLE
GROUP BY type
I've written the following query:
fields @timestamp, record.type as type, record.env as env
| stats count(env="dev") as dev, count(env="prod") as prod by type
expecting to get the following result:
type | dev | prod |
---|---|---|
type1 | 1 | 1 |
type2 | 1 | 0 |
But unfortunately, I'm getting the same count for both columns regardless of the applied filter inside the count()
as follows:
How can I achieve the output I need
Note
I can do the following query to get the results grouped by each env
:
fields @timestamp, record.type as type, record.env as env
| stats count(*) by type, env
I'll get :
type | env | count() |
---|---|---|
type1 | dev | 1 |
type1 | prod | 1 |
type2 | dev | 1 |
But I need the pivoted version
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这样一个简单的情况,即
count
或sum(field)
你可以执行以下
操作 注意,上面的方法不适用于需要诸如
avg
、stddev
等统计数据的情况。avg(isDev * docsCount )
将为prod
行,这些零将影响输出。For such a simple case, i.e. when
count
orsum(field)
is requiredyou can do following
Note, approach above does not work for the cases when you need statistics like
avg
,stddev
etc.avg(isDev * docsCount)
will produce zeroes for theprod
rows, and those zeroes will impact output.