使用 dbt 快照的 SCD2

dbt 中級

Mike Metzger

Data Engineer

什麼是快照?

  • 檢視資料集隨時間的變化
  • 呈現物件的不同狀態,例如
    • 訂單狀態
    • 生產狀態
    • 出貨狀態

訂單

1 Photo by micheile henderson on Unsplash
dbt 中級

SCD2

資料變更

1 Photo by Luke Chesser on Unsplash
dbt 中級

SCD2 範例

  • 訂單狀態
  • 可用狀態:
    • Received
    • Packed
    • Shipped
id order_status last_updated
1 Shipped 2023-07-01 11:30
id order_status last_updated
1 Received 2023-07-01 10:45
1 Packed 2023-07-01 11:15
1 Shipped 2023-07-01 11:30
dbt 中級

dbt 中的 SCD2

  • dbt 透過快照實作 SCD2
  • 可自動追蹤變更
  • 在輸出中加入額外欄位
    • dbt_valid_from
    • dbt_valid_to
id order_status last_updated dbt_valid_from dbt_valid_to
1 Received 2023-07-01 10:45 2023-07-01 10:45 2023-07-01 11:15
1 Packed 2023-07-01 11:15 2023-07-01 11:15 2023-07-01 11:30
1 Shipped 2023-07-01 11:30 2023-07-01 11:30 null
dbt 中級

實作 dbt 快照

  • SQL 檔,snapshots/snapshot_name.sql
{% snapshot snapshot_orders %}

{{ config(
target_schema='snapshots',
strategy='timestamp',
unique_key='id',
updated_at='last_updated'
) }}
select * from {{ source('raw', 'orders') }}
{% endsnapshot %}
dbt 中級

dbt snapshot

  • 執行 dbt snapshot
  • 建立新模型,使用 ref() 查詢快照
    • select * from {{ ref('snapshot_orders') }}
  • 經常執行 dbt snapshot 以查看可能變更的資料
    • 可排程自動更新
dbt 中級

一起來練習吧!

dbt 中級

Preparing Video For Download...