数据仓库自动化
数据建模入门数据建模数据仓库
问题
如何实现数据仓库建模的自动化和CI/CD流程?
答题要点
使用dbt + Git + CI/CD工具实现自动化:
# dbt项目结构
models/
├── staging/ # 原始数据清洗
│ ├── stg_orders.sql
│ └── stg_customers.sql
├── intermediate/ # 中间转换
│ └── int_customer_orders.sql
├── marts/ # 业务数据集市
│ ├── dim_customer.sql
│ ├── dim_product.sql
│ └── fact_sales.sql
└── schema.yml # 模型定义和测试
# schema.yml - 模型文档和测试
version: 2
models:
- name: fact_sales
description: "销售事实表,粒度为每笔订单明细"
columns:
- name: sale_key
description: "代理主键"
tests:
- unique
- not_null
- name: customer_key
description: "客户外键"
tests:
- not_null
- relationships:
to: ref('dim_customer')
field: customer_key
- name: sales_amount
description: "销售金额"
tests:
- not_null
- dbt_utils.expression_is_true:
expression: ">= 0"
# .github/workflows/dbt_ci.yml - GitHub Actions CI/CD
name: dbt CI/CD
on:
pull_request:
branches: [ main ]
push:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dbt
run: pip install dbt-snowflake
- name: dbt deps
run: dbt deps
- name: dbt compile
run: dbt compile
- name: dbt test
run: dbt test
env:
DBT_PROFILES_DIR: .
SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT }}
SNOWFLAKE_USER: ${{ secrets.SNOWFLAKE_USER }}
SNOWFLAKE_PASSWORD: ${{ secrets.SNOWFLAKE_PASSWORD }}
- name: dbt run (if on main)
if: github.ref == 'refs/heads/main'
run: dbt run --target prod
# pre-commit hook (本地检查)
# .pre-commit-config.yaml
repos:
- repo: https://github.com/sqlfluff/sqlfluff
rev: 2.0.0
hooks:
- id: sqlfluff-lint
name: SQL Linting
- id: sqlfluff-fix
name: SQL Auto-fix
- repo: https://github.com/dbt-labs/dbt-core
rev: v1.5.0
hooks:
- id: dbt-compile
- id: dbt-test
-- 增量模型自动化(dbt)
-- models/marts/fact_sales.sql
{{
config(
materialized='incremental',
unique_key='sale_key',
on_schema_change='append_new_columns'
)
}}
SELECT
{{ dbt_utils.surrogate_key(['order_id', 'line_item']) }} AS sale_key,
date_key,
customer_key,
product_key,
sales_amount,
quantity,
created_at
FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE created_at > (SELECT MAX(created_at) FROM {{ this }})
{% endif %}
-- 自动化测试宏
-- macros/test_referential_integrity.sql
{% macro test_referential_integrity(model, column_name, to_table, to_column) %}
SELECT COUNT(*) AS orphan_records
FROM {{ model }}
LEFT JOIN {{ to_table }} ON {{ model }}.{{ column_name }} = {{ to_table }}.{{ to_column }}
WHERE {{ to_table }}.{{ to_column }} IS NULL
AND {{ model }}.{{ column_name }} IS NOT NULL
HAVING COUNT(*) > 0
{% endmacro %}
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题