SCD2 กับ dbt snapshots

dbt ระดับกลาง

Mike Metzger

Data Engineer

Snapshot คืออะไร?

  • ติดตามการเปลี่ยนแปลงของชุดข้อมูลตามเวลา
  • แสดงสถานะต่างๆ ของ object เช่น
    • สถานะคำสั่งซื้อ
    • สถานะการผลิต
    • สถานะการจัดส่ง

คำสั่งซื้อ

1 ภาพโดย micheile henderson จาก Unsplash
dbt ระดับกลาง

SCD2

  • Slowly changing dimension
  • ติดตามการเปลี่ยนแปลงตามเวลา
  • dbt ใช้ snapshots เพื่อรองรับ 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 ระดับกลาง

SCD2 ใน dbt

  • dbt ใช้ snapshots เพื่อรองรับ 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 snapshots

  • ไฟล์ 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() เพื่อ query snapshot
    • select * from {{ ref('snapshot_orders') }}
  • รัน dbt snapshot บ่อยๆ เพื่อติดตามข้อมูลที่อาจเปลี่ยนแปลง
    • ตั้งกำหนดการอัปเดตอัตโนมัติ
dbt ระดับกลาง

มาฝึกกันเถอะ!

dbt ระดับกลาง

Preparing Video For Download...