Community研究與資料分析github.com

構建 dbt 模型

建立結構良好的 dbt 模型 — 包括分層(staging/intermediate/marts)、正確使用 ref() 與 source()、選擇物化策略,以及使用正確策略撰寫增量模型。適用於建立或重構 dbt 模型、選擇 table vs view vs incremental、組織 dbt 專案結構,或撰寫增量邏輯。

構建 dbt 模型 是什麼?

此技能指導開發者與 AI 助手如何建立結構化、可維護的 dbt 模型。它涵蓋了核心的 dbt 模型設計原則,包括將模型正確放置在 staging、intermediate 與 marts 層級,強制使用 ref() 與 source() 而非硬編碼資料表名稱,並根據資料大小與更新頻率選擇最適合的物化策略(view、table、incremental 或 ephemeral)。該技能提供了具體的程式碼範例,展示如何撰寫輕量的 staging 模型以及包含 unique_key、merge 策略與 `is_incremental()` 過濾器的增量模型,並附帶 lookback 視窗以處理延遲到達的資料。它也指出了常見的陷阱,例如在增量模型上遺漏 unique_key、在 staging 層中混入商業邏輯,或過度使用 table 物化導致不必要的倉儲成本。此技能支援所有常見的 dbt 平台(如 Snowflake、BigQuery、Databricks、Postgres 等),並且與 Claude Code、Cursor、Codex 等 AI 代理工具相容,因為其建議與平台無關。使用此技能能確保 dbt 專案的 DAG 完整性、環境可移植性與整體可維護性。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Unknown-333/awesome-data-engineering-skills/tree/main/skills/building-dbt-models

Installed? Explore more 研究與資料分析 skills: affaan-m/uspto-database, affaan-m/scholar-evaluation, affaan-m/literature-review · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

構建 dbt 模型 是做什麼的?

何時使用

  • 在 dbt 專案中建立或重構 .sql 模型。
  • 決定物化策略(view / table / incremental / ephemeral)。
  • 組織分層結構(staging → intermediate → marts)。
  • 為大型、持續增長的資料表撰寫增量模型。
  • 請勿用於測試撰寫(請使用 testing-dbt-projects)或執行失敗處理(請使用 debugging-dbt-runs)。

工作流程

- [ ] 將模型放置於正確的層級(staging/intermediate/marts)
- [ ] 僅透過 ref()/source() 引用上游資料 — 絕不硬編碼名稱
- [ ] 根據大小與刷新需求選擇物化策略
- [ ] 對於增量模型,設定 unique_key + is_incremental() 過濾器
- [ ] 在 schema.yml 中新增測試條目
  1. 分層。 staging/ = 每個來源資料表一個模型,進行輕量的重新命名與型別轉換,物化為 view。intermediate/ = 可重複使用的商業邏輯。marts/ = 供 BI 使用的最終維度模型,物化為 table。
  2. 正確引用。 使用 {{ ref('stg_orders') }} 與 {{ source('shop', 'orders') }},讓 dbt 建立 DAG 並管理環境。絕不直接撰寫原始 schema.table。
  3. 選擇物化策略: view(便宜、永遠最新、適合小資料)、table(讀取快速、每次執行重建)、incremental(大型附加/更新資料表)、ephemeral(內嵌 CTE,不建立物件)。
  4. 增量模型 只處理新增或變更的資料列。

模式

Staging 模型 — 每個來源一個,輕量且一致:

-- models/staging/shop/stg_orders.sql
with source as (select * from {{ source('shop', 'orders') }})
select
    order_id,
    customer_id,
    cast(order_ts as timestamp) as ordered_at,
    round(amount_cents / 100.0, 2) as amount
from source

增量模型 — 過濾新增資料列並設定冪等合併鍵:

{{ config(materialized='incremental', unique_key='order_id',
          incremental_strategy='merge') }}

select * from {{ ref('stg_orders') }}
{% if is_incremental() %}
  -- 只載入比現有資料更新的資料列,並加入回溯以處理延遲到達的資料
  where ordered_at >= (select coalesce(max(ordered_at), '1900-01-01') from {{ this }})
                      - interval '3 days'
{% endif %}

unique_key 加上 merge 使重新執行具有冪等性;回溯則能捕捉延遲到達的資料列。在 BigQuery/Spark 上,建議對日期分割區使用 insert_overwrite。

常見陷阱

  • 使用硬編碼的資料表名稱 而非 ref()/source() — 會破壞 DAG、血緣與環境切換。
  • 增量模型缺少 unique_key — 重新執行時會附加重複資料。
  • 使用 max(id) 增量過濾器但無回溯 — 會默默丟失延遲到達的資料。
  • 在 staging 層中加入商業邏輯 — 保持 staging 輕量;連線與聚合應歸屬於 intermediate/marts。
  • 所有模型都物化為 table — 浪費倉儲時間;小/便宜模型應使用 view,大型模型則用 incremental。
  • 單一巨型模型 — 應拆分為 intermediate 步驟以提高可測試性與可重用性。

參考資料

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

Unknown-333/authoring-airflow-dags

Write production-grade Apache Airflow DAGs using the TaskFlow API — idempotent tasks, correct scheduling and catchup, retries/SLAs, connections/variables, and avoiding top-level code. Use when creating or reviewing Airflow DAGs, scheduling pipelines, wiring task dependencies, configuring retries/backfills, or fixing non-idempotent tasks.

Unknown-333/building-dagster-assets

Build Dagster pipelines using software-defined assets — asset dependencies, partitions, resources and IO managers, asset checks, and schedules/sensors. Use when creating Dagster assets or jobs, modeling data as assets, adding partitions or backfills, wiring resources/IO managers, or migrating from task-based orchestration to assets.

Unknown-333/building-feature-pipelines

Build ML feature pipelines and feature stores — point-in-time-correct joins to avoid label leakage, offline/online parity, feature freshness and backfills, and materialization with tools like Feast. Use when engineering features for ML, preventing train/serve skew or data leakage, building a feature store, or backfilling historical features for training.

Unknown-333/building-iceberg-tables

Design and operate Apache Iceberg tables — partitioning and hidden partitioning, partition/schema evolution, snapshots and time travel, compaction and small-file cleanup, and MERGE/upsert for lakehouse tables on Spark, Flink, Trino, or Snowflake. Use when creating or maintaining Iceberg tables, choosing partitioning, evolving schema/partitions, or fixing small-file and metadata bloat.

Unknown-333/building-ingestion-pipelines

Build batch and incremental data ingestion (extract-load) pipelines — full vs incremental extraction, change data capture (CDC), watermarks and high-water marks, API pagination and rate limits, and choosing managed EL tools (Fivetran, Airbyte) vs custom code. Use when ingesting data from databases, APIs, files, or SaaS into a warehouse/lake, or designing incremental extraction and CDC.

Unknown-333/building-kafka-consumers

Build reliable Apache Kafka consumers and producers — consumer groups and partition assignment, offset commit strategy, at-least-once vs exactly-once, idempotent/transactional producers, rebalancing, and dead-letter handling. Use when writing Kafka consumers/producers, configuring offset commits or consumer groups, tuning throughput, or handling rebalances and poison messages.

Unknown-333/debugging-data-pipelines

Systematically root-cause data pipeline failures and data incidents — job errors, wrong or missing data, duplicates, and freshness misses — by tracing lineage upstream, isolating the failing stage, reconciling against source, and planning a safe fix and backfill. Use when a pipeline fails, numbers look wrong, data is missing or duplicated, a dashboard is stale, or a stakeholder reports a data discrepancy.

Unknown-333/designing-backfills-and-replays

Plan and run safe data backfills and replays — idempotent reprocessing of historical windows, partition-by-partition execution, isolating backfill compute from production, verifying results, and avoiding double-counting or changed history. Use when backfilling a new or fixed model, reprocessing after a bug, replaying events, or loading history for a new pipeline without corrupting existing data.

Unknown-333/designing-data-contracts

Define and enforce data contracts between producers and consumers — explicit schema, semantics, ownership, SLAs, and versioning — to prevent silent upstream changes from breaking downstream pipelines. Use when a producer schema change could break consumers, defining an interface between teams/services and the warehouse, or adding schema enforcement at ingestion.

相關技能