dbt 測試入門

dbt 中級

Mike Metzger

Data Engineer

什麼是測試?

  • 對 dbt 物件的斷言/驗證
    • 模型
    • 來源與種子
  • 用於確認資料符合預期
    • Null 值
    • 值落在範圍內
    • 資料之間的關聯
    • 客製化測試(稍後介紹)
dbt 中級

測試類型

dbt 提供三種測試

  1. 內建(4 種預先定義)
  2. 單一(singular)*
  3. 泛型(generic)*

$$

  • 將在稍後介紹
dbt 中級

內建測試

  • unique
    • 驗證所有值皆唯一
  • not_null
    • 驗證所有值皆非空
  • accepted_values
    • 驗證所有值都在指定清單內
    • values: [a, b, c, d]
  • relationships
    • 驗證與特定資料表/欄位的關聯
    • to: ref('table')
    • field: id
dbt 中級

在哪裡加入測試?

  • models/model_properties.yml
    • 檔名可自訂
    • models/schema.yml
  • 定義在 tests: 子標題下
version: 2

models:
  - name: taxi_rides_raw
    columns:
      - name: tpep_pickup_datetime
        tests:
          - not_null
      - name: payment_type
        tests:
          - not_null
          - accepted_values:
              values: [1, 2, 3, 4, 5, 6]
dbt 中級

執行測試

  • dbt test
    • dbt test --select modelname
  • 檢查輸出是否通過
  • 若失敗,查看已編譯的 SQL

dbt 測試失敗輸出

dbt 中級

定位失敗

  1. 先找到已編譯的 SQL 程式碼
  2. 位置在 target/compiled/projectname/models/model_properties.yml 目錄
    • target/compiled/nyc_yellow_taxi/models/model_properties.yml/
  3. 找到對應的 .sql 檔(與失敗的測試相符)
  4. 複製內容到資料庫用戶端並查明問題位置
  5. 從資料中移除問題並重新執行 dbt rundbt test
dbt 中級

一起來練習吧!

dbt 中級

Preparing Video For Download...