如何使用 Great Expectations 连接 Redshift 并运行期望?

解读

国内数据团队普遍把 Great Expectations(GE)当作“数据质量门禁”,而 Redshift 又是 AWS 生态中最常用的云数仓。面试时,考官想确认三件事:

  1. 你是否熟悉 Redshift 的认证与网络配置(VPC、安全组、IAM、SSL);
  2. 你是否能把 GE 的 Datasource、Expectation Suite、Checkpoint 三大概念映射到 Redshift 表;
  3. 你能否在生产级场景下解决“并发、权限、性能、回退”四大痛点。
    因此,回答必须给出一条可落地的端到端路径,并穿插国内合规细节(如北京/宁夏区域、SSL 强制加密、RAM 子账号权限最小化)。

知识点

  • Great Expectations 0.18+ 插件式 Datasource:支持 SQLAlchemy,官方已内置 redshift+psycopg2 方言。
  • Redshift 连接串格式:redshift+psycopg2://username:password@host:5439/db?sslmode=require,sslmode 必须显式指定,否则国内部分区域会被拒绝。
  • IAM 角色链:GE 运行机(EC2、EKS、Airflow Worker)→ 附加 IAM Role → Redshift GetClusterCredentials,避免在代码里硬编码密码,符合等保要求。
  • Expectation 类型选择:
    – 列式分布:expect_column_quantile_values_to_be_between 对倾斜键做分位检测;
    – 业务语义:expect_column_values_to_be_in_set 结合国内字典表(如行政区划码)。
  • Checkpoint 隔离:为 Redshift 单独建一个 checkpoint_store 指向 S3,与 Snowflake、MySQL 的 checkpoint 物理隔离,防止跨库污染。
  • 并发扩展:Redshift 开启 Concurrency Scaling 后,GE 的验证 SQL 会被路由到临时集群,不影响 BI 报表 SLA;需在 Checkpoint 里加 max_query_slots=2 限制。
  • 失败回退:GE Action 里配置 sns_notify + Airflow on_failure_callback,触发回滚任务,重载昨日分区。

答案

步骤一:环境准备

  1. 在 requirements.txt 锁定版本:great-expectations==0.18.8 sqlalchemy-redshift==0.8.14 psycopg2-binary==2.9.9。
  2. 运行机使用 北京区域 EC2,安全组放行 5439 端口出站;Redshift 集群参数组开启 require_ssl;创建单独 DB 账号 ge_validator,默认权限只读,通过 IAM 插件生成临时口令:
import boto3
client = boto3.client('redshift', region_name='cn-north-1')
token = client.get_cluster_credentials(
    DbUser='ge_validator',
    DbName='analytics',
    ClusterIdentifier='redshift-cluster-1',
    AutoCreate=False,
    DurationSeconds=3600
)

步骤二:初始化 GE 项目

great_expectations init

选择 V3 API,store_backend 统一用 S3(北京区域 bucket),确保 expectations_store 与 validations_store 前缀分开,方便后续做生命周期。

步骤三:新建 Datasource
在 great_expectations.yml 追加:

datasources:
  redshift_analytics:
    class_name: Datasource
    execution_engine:
      class_name: SqlAlchemyExecutionEngine
      connection_string: "redshift+psycopg2://ge_validator:${token}@redshift-cluster-1.abc.cn-north-1.redshift.amazonaws.com.cn:5439/analytics?sslmode=require"
    data_connectors:
      default_inferred_data_connector_name:
        class_name: InferredAssetSqlDataConnector
        include_schema_name: true
        introspection_directives:
          schema_name: "dwh"

步骤四:生成 Expectation Suite
以订单表 dwh.fact_order 为例,先采样 5% 数据避免全表扫描:

great_expectations suite new \
  --datasource redshift_analytics \
  --data-asset dwh.fact_order \
  --profile \
  --sample-percent 5 \
  --suite-name fact_order_critical

在 Jupyter 里保留以下关键期望:

  • expect_column_values_to_be_unique(order_id)
  • expect_column_values_to_not_be_null(pay_amount)
  • expect_column_mean_to_be_between(pay_amount, min_value=50, max_value=5000)
    保存后 GE 会自动生成 JSON 到 S3。

步骤五:配置 Checkpoint
新建 redshift_fact_order_chk.yml:

name: redshift_fact_order_chk
config_version: 1
class_name: Checkpoint
validations:
  - batch_request:
      datasource_name: redshift_analytics
      data_connector_name: default_inferred_data_connector_name
      data_asset_name: dwh.fact_order
      partition_request:
        partition_identifiers:
          ds: "${DS}"
    expectation_suite_name: fact_order_critical
action_list:
  - name: store_validation_result
    action:
      class_name: StoreValidationResultAction
  - name: sns_notify
    action:
      class_name: SNSNotificationAction
      sns_topic_arn: arn:aws-cn:sns:cn-north-1:123456789012:ge-alert
      message_subject: "Redshift数据质量校验失败"
evaluation_parameters:
  DS: "$DS"
runtime_configuration:
  query_slots: 2          # 限制并发

步骤六:调度与监控
在 Airflow DAG 里调用:

from great_expectations_provider.operators.great_expectations import GreatExpectationsOperator

chk_task = GreatExpectationsOperator(
    task_id='ge_redshift_fact_order',
    data_context_root_dir='/opt/ge/',
    checkpoint_name='redshift_fact_order_chk',
    execution_engine='redshift+psycopg2',
    fail_task_on_validation_failure=True,
    env={
        'DS': '{{ ds }}',
        'token': get_redshift_token()  # 复用步骤一的函数
    }
)

上线前做三项检查:

  1. STV_SESSIONS 查看 GE 账号是否只产生只读查询;
  2. STL_QUERY 确认校验 SQL 被路由到 Concurrency Scaling 队列;
  3. S3 Server Access Log 验证 GE 写入 validation 结果时使用了 KMS 加密。

拓展思考

  1. 跨云混合架构:若公司部分数据在阿里云 MaxCompute,可通过 Redshift Spectrum 直接建 external schema 映射 OSS 外表,GE 的同一套 Checkpoint 既能测本地表也能测外表,实现“一码多云”质量门禁。
  2. 实时流校验:把 GE 的 RuntimeBatchRequest 指向 Materialized View(刷新间隔 1 min),结合 Kinesis Data Streams 的 Lambda 触发器,实现秒级数据质量告警,替代传统 T+1 抽样。
  3. 成本优化:国内 Redshift 按扫描字节计费,GE 校验 SQL 可通过 SET enable_result_cache_for_session TO off; 强制走冷路径,避免命中缓存导致费用估算失真;同时对大表采用 TABLESAMPLE BERNOULLI(1) 与 SVV_TABLE_INFO 的 unsorted 字段结合,只在排序键健康度低于 20% 时才触发全量期望,节省 70% 扫描费用。