Community연구 & 데이터 분석github.com

Building dbt Models

잘 구조화된 dbt 모델(staging/intermediate/marts 레이어)을 구축하고, ref() 및 source() 참조, 구체화 방식, 적절한 전략의 증분 모델을 작성합니다. dbt 모델을 생성하거나 리팩터링할 때, 테이블/뷰/증분 선택, dbt 프로젝트 구조화, 증분 로직 작성 시 사용합니다.

Building dbt Models란 무엇인가요?

이 스킬은 dbt 프로젝트에서 모델을 효과적으로 구축하고 리팩터링하는 방법을 가이드합니다. staging, intermediate, marts의 계층 구조를 명확히 하고, 각 레이어에 적합한 구체화 방식(뷰, 테이블, 증분, 임시)을 선택하여 성능과 비용을 최적화합니다. 특히 증분 모델의 경우 unique_key와 is_incremental() 필터를 사용하여 중복 없이 효율적으로 데이터를 처리하며, 지연 데이터를 잡기 위한 lookback 기간도 포함합니다. 코드 예제를 통해 실제 SQL 작성법과 함께 hard-coded 테이블명 대신 ref()/source()를 사용하는 DAG 관리, 스키마.yml 테스트 추가 등 모범 사례를 제공합니다. Cursor, Claude Code 등 주요 AI 에이전트 도구에서 dbt 모델 작업 시 활용할 수 있습니다.

지원 대상~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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Building dbt Models은(는) 무엇을 하나요?

사용 시기

  • dbt 프로젝트에서 .sql 모델을 생성하거나 리팩터링할 때
  • 구체화 방식(뷰 / 테이블 / 증분 / 임시)을 결정할 때
  • 레이어를 구조화할 때(staging → intermediate → marts)
  • 대규모 증가 테이블을 위한 증분 모델을 작성할 때
  • 테스트 작성을 위해서는 testing-dbt-projects를, 실행 실패 처리는 debugging-dbt-runs를 사용하세요.

워크플로우

- [ ] 올바른 레이어(staging/intermediate/marts)에 모델 배치
- [ ] ref()/source()로만 업스트림 참조 — 하드코딩된 이름 사용 금지
- [ ] 크기와 갱신 필요성에 따라 구체화 방식 선택
- [ ] 증분 모델의 경우 unique_key + is_incremental() 필터 설정
- [ ] 테스트가 포함된 schema.yml 항목 추가
  1. 레이어링. staging/ = 소스 테이블당 하나의 모델, 가벼운 이름 변경/타입 변환, 뷰로 구체화. intermediate/ = 재사용 가능한 비즈니스 로직. marts/ = BI에서 소비하는 최종 차원 모델, 테이블로 구체화.
  2. 올바른 참조. {{ ref('stg_orders') }} 및 {{ source('shop', 'orders') }}를 사용하여 dbt가 DAG를 구축하고 환경을 관리하도록 합니다. 원시 schema.table은 절대 작성하지 마세요.
  3. 구체화 방식 선택: 뷰(저렴, 항상 최신, 소규모), 테이블(빠른 읽기, 실행마다 재구축), 증분(대규모 추가/업데이트 테이블), 임시(인라인 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() %}
  -- 이미 로드된 데이터보다 최신 행만, 지연 데이터를 위한 lookback 포함
  where ordered_at >= (select coalesce(max(ordered_at), '1900-01-01') from {{ this }})
                      - interval '3 days'
{% endif %}

unique_key + merge는 재실행을 멱등하게 만듭니다. lookback은 지연 도착 행을 포착합니다. BigQuery/Spark에서는 날짜 파티션에 insert_overwrite를 선호합니다.

일반적인 함정

  • ref()/source() 대신 하드코딩된 테이블 이름 — DAG, 계보 및 환경 전환을 깨뜨립니다.
  • unique_key 없는 증분 모델 — 재실행 시 중복이 추가됩니다.
  • lookback 없는 max(id) 증분 필터 — 지연 데이터를 조용히 누락시킵니다.
  • staging의 비즈니스 로직 — staging은 얇게 유지하세요. 조인/집계는 intermediate/marts에 속합니다.
  • 모든 것을 table로 구체화 — 웨어하우스 시간 낭비입니다. 소규모/저렴한 모델은 뷰를, 대규모 모델은 증분을 사용하세요.
  • 하나의 거대한 모델 — 테스트 가능성과 재사용을 위해 중간 단계로 분할하세요.

참조

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.

관련 스킬