使用 dbt 快照实现 SCD2

dbt 中级

Mike Metzger

Data Engineer

什么是快照?

  • 随时间查看数据集的变更
  • 展示对象的不同状态,例如
    • 订单状态
    • 生产状态
    • 发货状态

订单

1 照片作者:micheile henderson(来自 Unsplash)
dbt 中级

SCD2

数据变更

1 照片作者:Luke Chesser(来自 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 中级

Passons à la pratique !

dbt 中级

Preparing Video For Download...