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

如何配置dbt项目标签,查询其创建的BigQuery作业并统计成本

解决dbt BigQuery作业成本统计问题

核心思路

dbt执行增量MERGE时会生成后台作业,这类作业不会直接记录到run_results.json中,但所有关联作业都会携带唯一的dbt_invocation_id标签。以此标识为核心,就能关联到某次dbt运行产生的所有作业,进而统计完整成本。

具体查询方案

1. 通过dbt_invocation_id定位单次dbt运行的所有作业

从run_results.json中提取本次运行的invocation_id,用它作为过滤条件查询所有相关作业,包括MERGE这类后台任务:

SELECT
  job_id,
  job_type,
  start_time,
  end_time,
  total_bytes_billed,
  total_bytes_processed,
  labels
FROM
  `my_project_id.region-eu.INFORMATION_SCHEMA.JOBS_BY_USER`
WHERE
  labels.dbt_invocation_id = '<你的dbt调用ID>'
  AND DATE(start_time) = '2024-XX-XX' -- 可选,限定日期缩小查询范围
ORDER BY
  start_time

2. 精准过滤目标项目/环境的作业

如果需要区分不同dbt环境(如dev/prod)或项目,可补充以下过滤条件:

  • 执行作业的服务账号邮箱user_email
  • 目标数据集destination_table.dataset_id
  • 作业类型或查询关键字(如包含MERGE)

示例扩展查询:

SELECT
  job_id,
  job_type,
  start_time,
  end_time,
  total_bytes_billed,
  total_bytes_processed,
  labels,
  destination_table.dataset_id,
  user_email
FROM
  `my_project_id.region-eu.INFORMATION_SCHEMA.JOBS_BY_USER`
WHERE
  labels.dbt_invocation_id = '<你的dbt调用ID>'
  AND user_email = 'dbt-service-account@my_project_id.iam.gserviceaccount.com'
  AND destination_table.dataset_id IN ('dbt_dev', 'dbt_prod')
ORDER BY
  total_bytes_billed DESC

3. 批量统计一段时间内的dbt作业成本

若需统计某段时间内所有dbt运行的总成本,直接筛选所有带dbt_invocation_id标签的作业即可:

SELECT
  labels.dbt_invocation_id,
  COUNT(DISTINCT job_id) AS total_jobs,
  SUM(total_bytes_billed) AS total_bytes_billed_all,
  SUM(total_bytes_processed) AS total_bytes_processed_all,
  DATE_TRUNC(DATE(start_time), DAY) AS run_date
FROM
  `my_project_id.region-eu.INFORMATION_SCHEMA.JOBS_BY_USER`
WHERE
  labels.dbt_invocation_id IS NOT NULL
  AND DATE(start_time) BETWEEN '2024-01-01' AND '2024-01-31'
GROUP BY
  labels.dbt_invocation_id, run_date
ORDER BY
  run_date DESC

关于自定义标签不显示的排查

你配置的自定义标签未出现在BigQuery作业中,可检查以下几点:

  • 确认模型标签是在config块内正确配置:
    models:
      my_project:
        +labels:
          project: "my_dbt_project"
          environment: "production"
    
  • 增量模型的incremental_strategy设置为merge(默认值),确保dbt会将标签传递给MERGE作业
  • 升级至dbt-bigquery 1.8.2及以上版本,部分早期小版本存在标签传递的bug

内容的提问来源于stack exchange,提问作者Vega

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:47:10