You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grafana Loki查询求助:实现两查询结果运算并在单柱状图展示

Loki查询实现A-B差值与原B值同图展示

你之前用unless的思路不对,unless是用来过滤掉左右标签完全匹配的时间序列,不是做数值减法,所以达不到需求。要实现A结果减B结果,同时保留B的原始值,可以按以下方式编写查询:

最终组合查询

通过给两个查询添加自定义标签区分系列,再用数学运算计算差值,最后合并两个结果:

# 计算A-B的差值,标记为success系列
label_replace(
  count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `INFO` [$__auto])))
  - 
  count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `ERROR` [$__auto]))),
  "metric_type", "success", "", ""
)
# 合并原B查询,标记为error系列
|
label_replace(
  count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `ERROR` [$__auto]))),
  "metric_type", "error", "", ""
)

图表展示设置

在Grafana柱状图面板中,选择metric_type作为图例字段,就能分别显示success(A-B的结果)和error(原B的结果)两个柱子。

可选优化

如果担心减法出现负数,可用clamp_min强制数值不小于0:

label_replace(
  clamp_min(
    count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `INFO` [$__auto])))
    - 
    count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `ERROR` [$__auto]))),
    0
  ),
  "metric_type", "success", "", ""
)
|
label_replace(
  count by(count) (sum by(label_ELM_jobId) (count_over_time({label_ELM="offboard"} |~ `ERROR` [$__auto]))),
  "metric_type", "error", "", ""
)

内容的提问来源于stack exchange,提问作者Smooth-Home2767

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 09:10:00