通过建立自动化分析和数据质量规则,您可以使用信任信号和业务上下文来丰富元数据。
通过Human-in-the-Loop方法,AI 会起草初始规则,您则负责审核、优化和验证这些规则,从而快速将分析统计信息转化为数据质量框架。
目标
- 使用物化视图展平嵌套的 BigQuery 数据,以便进行 Knowledge Catalog 分析。
- 使用 Python 客户端库运行 Knowledge Catalog 分析扫描。
- 使用 Antigravity CLI 根据分析统计信息生成数据质量规则。
- 通过人机协同审核流程,验证 AI 生成的规则并将其部署为 Knowledge Catalog 质量扫描。
准备工作
在开始之前,请确保您有一个已启用结算功能的 Google Cloud 项目。
准备环境
以下步骤使用 Cloud Shell,它是在云端运行的命令行环境。
在 Google Cloud 控制台中,点击右上角工具栏中的激活 Cloud Shell。预配和连接到环境需要一些时间。
在 Cloud Shell 中,设置您的项目 ID 和环境变量:
export PROJECT_ID=$(gcloud config get-value project) gcloud config set project $PROJECT_ID export LOCATION="us-central1" export BQ_LOCATION="us" export DATASET_ID="kc_dq_codelab" export TABLE_ID="ga4_transactions"由于公开示例数据也位于
us(多区域),因此请使用us(多区域)作为位置。对于 BigQuery 查询,源数据和目标表必须位于同一位置。启用所需的服务:
gcloud services enable dataplex.googleapis.com \ bigquery.googleapis.com \ serviceusage.googleapis.com \ aiplatform.googleapis.com创建 BigQuery 数据集来存储示例数据和结果:
bq --location=us mk --dataset $PROJECT_ID:$DATASET_ID准备示例数据,这些数据来自 Google Merchandise Store 的公开电子商务数据集。
以下
bq命令会在kc_dq_codelab数据集中创建一个新表ga4_transactions。为确保扫描快速运行,它只会复制一天(2021-01-31)的数据。bq query \ --use_legacy_sql=false \ --destination_table=$PROJECT_ID:$DATASET_ID.$TABLE_ID \ --replace=true \ 'SELECT * FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20210131`'克隆包含本教程的文件夹结构和支持文件的 GitHub 代码库:
# Perform a shallow clone to get only the latest repository structure without the full history git clone --depth 1 --filter=blob:none --sparse https://github.com/GoogleCloudPlatform/devrel-demos.git cd devrel-demos # Specify and download only the folder we need for this lab git sparse-checkout set data-analytics/programmatic-dq cd data-analytics/programmatic-dq此目录是您的活跃工作区。
剖析嵌套数据
借助数据分析,Knowledge Catalog 可查找顶级列的统计信息,例如数据中的 null 百分比、唯一性和值分布,以帮助您了解数据。
如需获取嵌套字段的统计信息,您可以使用一组物化视图来展平数据。这会将每个嵌套字段转换为 Knowledge Catalog 可以分析的顶级列。
获取嵌套架构
获取源表的完整架构(包括所有嵌套结构),并将输出保存为 JSON 文件:
bq show --schema --format=json $PROJECT_ID:$DATASET_ID.$TABLE_ID > bq_schema.json
查看架构:
jq < bq_schema.json
bq_schema.json 文件揭示了复杂的结构。
使用具体化视图展平数据
在展平嵌套数据时,请务必不要在同一视图中对多个独立数组进行非嵌套处理。这样做会在数组之间执行隐式交叉联接(笛卡尔积),从而导致行数错误地成倍增加并损坏数据。
最好创建多个视图,每个视图都针对特定目的而构建。每个视图都应保持单一、清晰的细节级别。在此步骤中,您将创建以下物化视图:
- 会话平面视图 (
mv_ga4_user_session_flat.sql):每个事件一行。 - “交易”视图 (
mv_ga4_ecommerce_transactions.sql):每行对应一笔交易。 - “商品”视图 (
mv_ga4_ecommerce_items.sql):每行对应一件商品。
项目代码库在 devrel-demos/data-analytics/programmatic-dq 目录中提供了三个 SQL 文件,用于定义这些视图。
使用以下 BigQuery 命令从 Cloud Shell 运行这些文件。
envsubst < mv_ga4_user_session_flat.sql | bq query --use_legacy_sql=false
envsubst < mv_ga4_ecommerce_transactions.sql | bq query --use_legacy_sql=false
envsubst < mv_ga4_ecommerce_items.sql | bq query --use_legacy_sql=false
使用 Python 客户端运行配置文件扫描
现在,您可以为每个具体化视图创建并运行 Knowledge Catalog 数据分析扫描。以下 Python 脚本使用 google-cloud-dataplex 客户端库来自动执行此过程。
在运行脚本之前,请在项目目录中创建一个独立的 Python 虚拟环境。
# Create the virtual environment
python3 -m venv dq_venv
# Activate the environment
source dq_venv/bin/activate
在虚拟环境中安装 Knowledge Catalog 客户端库。
# Install the Knowledge Catalog client library
pip install google-cloud-dataplex
现在,您已设置好环境并安装了库,可以开始使用 1_run_scan.py 脚本了。此脚本会为每个物化视图创建并运行扫描,从而对这三个物化视图进行分析。完成后,它会输出一份丰富的统计摘要,供您在下一步中用于生成 AI 赋能的数据质量规则。
从 Cloud Shell 终端运行该脚本。
python3 1_run_scan.py
查看您的分析扫描
您可以在 Google Cloud 控制台中查看新的分析扫描。
- 在导航菜单中,前往治理部分中的 Knowledge Catalog 和数据分析和质量评估。
- 您会看到列出的三个配置文件扫描作业,以及它们的最新作业状态。点击扫描即可查看其详细结果。
将性能分析结果导出为 JSON
为了让 Antigravity CLI 能够读取您的配置文件扫描结果,您需要将其内容提取到本地文件中。
使用 2_dq_profile_save.py 脚本查找 mv_ga4_user_session_flat 视图的最新成功扫描,下载分析数据,并将其保存到名为 dq_profile_results.json 的文件中。
python3 2_dq_profile_save.py
脚本运行完毕后,会在该目录中创建一个 dq_profile_results.json 文件。此文件包含生成数据质量规则所需的详细统计元数据。运行以下命令,查看其内容:
cat dq_profile_results.json
使用 Antigravity CLI 生成数据质量规则
现在,您可以使用 Antigravity CLI 读取本地配置文件扫描结果。
为复杂数据集手动编写数据质量规范既耗时又容易出错。使用生成式 AI 智能体,可以在几秒钟内起草初始声明式配置,从而加快此工作流。这使数据团队能够从手动语法起草转向高级、与业务一致的人机协同 (HITL) 监督。
如需启动 Antigravity CLI,请使用以下命令:
agy
现在,您可以开始生成质量规则了。由于 CLI 可以读取当前目录中的文件,因此可以直接使用新的配置文件扫描数据。
输入提示,让智能体创建方案
首先,让智能体分析统计概况并提出行动计划。指示它先不要编写 YAML 文件,而是专注于分析和理由说明。
在交互式 Antigravity CLI 会话中,输入以下结构化提示:
# Context
You are preparing a data quality rule configuration plan for Google Cloud Knowledge Catalog based on data profile statistics.
# Input
- File Path: `./dq_profile_results.json` (contains metrics like null percentage, distinct counts, and distributions)
# Task
Analyze the input statistics and propose a step-by-step plan for establishing automated data quality rules.
*Do not write any YAML code in this step.* Focus only on analytical planning.
# Rule Mapping Strategy
For candidate columns, match the statistical metrics to the most appropriate expectations:
- `nonNullExpectation`: Propose for columns with 0% null values in the profile.
- `setExpectation`: Propose for columns with a highly limited, stable set of categorical values.
- `rangeExpectation`: Propose for numeric columns with consistent and predictable value boundaries.
# Guidelines
- Provide a metric-based justification for each proposed rule (for example, "Recommend nonNullExpectation for column 'user_pseudo_id' because its null percentage is 0%").
- Flag volatile metrics such as hardcoded row counts that could cause false-positive alerts in production.
# Output Format
Provide your analysis and proposed rules as a structured, step-by-step markdown plan with clear headings.
智能体会分析 JSON 文件,并返回如下所示的结构化方案:
Automated Data Quality Rule Configuration Plan
Google Cloud Knowledge Catalog (Dataplex Data Quality)
──────
## Executive Summary
This analytical planning document outlines a step-by-step strategy for
configuring automated data quality (DQ) rules in Google Cloud
Knowledge Catalog (formerly Dataplex Data Quality) based on profiling
statistics.
The dataset contains 26,489 rows representing GA4 event logs. Based on
statistical metrics (null ratios, distinct value distributions, and data
types), candidate columns are mapped to appropriate expectation rules.
──────
## 1. Data Profile Overview & Statistical Highlights
Column Name │ Data Type │ Null Ratio │ Distinct Count │ Key Value Range / Categories
─────────────────┼───────────┼────────────────┼────────────────┼──────────────────────────────────────────────────
event_date │ STRING │ 0.0% (0) │ 1 (3.78e-05) │ "20210131" (100%)
event_timestamp │ INTEGER │ 0.0% (0) │ ~16,539 (0.62) │ Min: 1612051200657906, Max: 1612137595412363
event_name │ STRING │ 0.0% (0) │ 16 (0.0006) │ page_view (35.8%), user_engagement (18.9%), etc.
user_pseudo_id │ STRING │ 0.0% (0) │ ~2,545 (0.09) │ 18-21 characters string identifiers
user_id │ STRING │ 100.0% (1.0) │ 0 (0.0) │ Entirely NULL
device_category │ STRING │ 0.0% (0) │ 3 (0.0001) │ desktop (57.5%), mobile (40.1%), tablet (2.4%)
... │ ... │ ... │ ... │ ...
──────
## 2. Rule Mapping Strategy & Analytical Justifications
### Step 1: Nullability Rules (nonNullExpectation)
Propose nonNullExpectation for mandatory columns where the data profile
demonstrates 0% null values.
• user_pseudo_id, event_timestamp, event_name, event_date, stream_id,
platform, device_category (Metric Justification: nullRatio is 0.0%)
│ [!NOTE] Exclusions:
│ • user_id: Has a nullRatio of 100.0% (unauthenticated traffic).
│ • device_language: Has a nullRatio of 37.53%.
──────
### Step 2: Categorical Value Set Validation (setExpectation)
Propose setExpectation for columns with a highly limited, stable set of
categorical domain values.
• device_category: Distinct count is exactly 3. Allowed set:
['desktop', 'mobile', 'tablet']
• platform: Distinct count is 1. Allowed set expanded to:
['WEB', 'ANDROID', 'IOS'] to avoid over-fitting.
• geo_continent: Distinct count is 6. Allowed set:
['Americas', 'Asia', 'Europe', 'Africa', 'Oceania', 'Antarctica', '(not set)']
──────
### Step 3: Numeric & Timestamp Boundary Validation (rangeExpectation)
Propose rangeExpectation for numeric columns with consistent and predictable
value boundaries.
• event_timestamp: rangeExpectation requiring event_timestamp > 0 (avoid
dynamic microsecond range hardcoding)
• stream_id: rangeExpectation requiring positive integer stream IDs
(stream_id > 0)
──────
## 3. Risk Warning: Volatile Metrics & Production False Positives
│ [!WARNING] Volatile Metrics Flagged for Risk Mitigation:
1. Hardcoded Total Row Count (rowCount = 26,489) -> Daily event volume
fluctuates. Use dynamic volume thresholds.
2. Hardcoded Partition Date (event_date = '20210131') -> Breaks on future
runs. Validate against YYYYMMDD regex patterns.
3. Exact Timestamp Range Bounds -> Enforcing these microsecond limits on
incoming live pipelines will reject all future data.
4. Single-Value Domain Restrictions -> Single profile sample might lack
active streams. Set sets according to enterprise schema.
──────
## Summary Table of Proposed Rules
Target Column │ Rule Type │ Metric-Based Justification │ Operational Considerations
─────────────────┼────────────────────┼────────────────────────────┼──────────────────────────────────────────────────
user_pseudo_id │ nonNullExpectation │ Null Ratio: 0.0% │ Core identifier, strictly required
event_timestamp │ nonNullExpectation │ Null Ratio: 0.0% │ Temporal key, strictly required
event_timestamp │ rangeExpectation │ Min: > 0 (Microseconds) │ Avoid hardcoding epoch min/max
event_name │ nonNullExpectation │ Null Ratio: 0.0% │ Required event taxonomy key
event_name │ setExpectation │ Categorical distribution │ Map to standard GA4 event taxonomy
device_category │ nonNullExpectation │ Null Ratio: 0.0% │ Required form-factor dimension
device_category │ setExpectation │ Distinct Count: 3 values │ ['desktop', 'mobile', 'tablet']
... │ ... │ ... │ ...
生成数据质量规则
这是整个工作流中最关键的一步:人机协同 (HITL) 审核。智能体生成的计划完全基于数据中的统计模式。智能体不了解您的业务背景、未来的数据变化或数据背后的具体意图。作为人类专家,您的职责是在将此方案转化为代码之前,对其进行验证、更正和批准。
在 HITL 审核期间要验证的内容
根据以下核心业务标准检查智能体提出的方案:
- 统计异常与业务实际情况:
- 原因:AI 智能体可能会假设,如果某列在一天样本中的 null 值为 0%,则该列永远不应包含 null 值;或者,它可能会根据有限的历史分布设置严格的数值范围。
- 操作:验证建议的边界(例如
rangeExpectation或nonNullExpectation)是反映了真实的业务限制,还是仅仅是样本集伪影。
- 易变指标(例如行数):
- 原因:在活跃的企业环境中,
rowCount或表增长等指标每天都会发生变化。静态规则会导致误报。 - 操作:拒绝或修改对动态事务表强制执行静态阈值的规则。
- 原因:在活跃的企业环境中,
- 分类完整性 (
setExpectation):- 原因:分析数据仅显示扫描的样本窗口中存在的值。它无法预测未在该时间范围内发生的有效类别。
- 操作:对照官方业务术语库或参考数据检查分类列表,添加样本中省略的所有有效值(例如,添加缺失的区域代码或商品类别)。
根据提示反馈优化方案
向智能体提供反馈,并向其发出生成代码的最终命令。根据您实际收到的方案和您要进行的更正,调整以下提示。
提示只是一个模板。第一行用于添加具体更正内容。
此提示要求遵循 DataQualityRule 规范,因为 Knowledge Catalog 需要精确的 YAML 结构,以防止语法错误或架构版本过时。
# Feedback & Approvals
[YOUR CORRECTIONS AND APPROVAL GO HERE. Examples:
- "The plan looks good. Please proceed."
- "The rowCount rule is not necessary, as the table size changes daily. The rest of the plan is approved. Please proceed."
- "For the setExpectation on the geo_continent column, please also include 'Antarctica'."]
# Objective
Based on the approved analysis plan and the provided feedback, generate the final `dq_rules.yaml` file conforming to the standard `DataQualityRule` schema.
# Instructions
1. **Rule Justifications**: For every generated rule, add a YAML comment (`#`) on the line directly above it, briefly explaining the justification established in the plan.
2. **Schema Alignment**: Ensure the structure strictly adheres to the required Knowledge Catalog data quality scan specification. Refer to the `sample_rule.yaml` file in the current directory and the `DataQualityRule` class definition as the schema authority. Search for the `data_quality.py` file inside the `./dq_venv/lib/` directory to read this class definition.
3. **Data-Driven Values**: Derive all rule parameters, such as thresholds or expected values, directly from the statistical metrics in `dq_profile_results.json`.
# Constraints
- **Output Purity**: Return ONLY the raw, valid, and properly formatted YAML code block.
- Do not include conversational preambles, introductory sentences, explanations, or markdown blocks around the YAML.
现在,智能体会根据您验证过的指令,在您的工作目录中生成一个名为 dq_rules.yaml 的 YAML 文件。
创建并运行数据质量扫描
现在,您已有一组由智能体生成、经人工验证的数据质量规则,可以将其注册并部署为扫描。
输入
/quit或按两次Ctrl+C即可退出 Antigravity CLI。然后,在 Knowledge Catalog 中创建数据扫描:
export DQ_SCAN="dq-scan" gcloud dataplex datascans create data-quality $DQ_SCAN \ --project=$PROJECT_ID \ --location=$LOCATION \ --data-quality-spec-file=dq_rules.yaml \ --data-source-resource="//bigquery.googleapis.com/projects/$PROJECT_ID/datasets/$DATASET_ID/tables/mv_ga4_user_session_flat"运行扫描:
gcloud dataplex datascans run $DQ_SCAN --location=$LOCATION --project=$PROJECT_ID此命令会创建一个名为
dq-scan的数据质量扫描。在 Google Cloud 控制台的“Knowledge Catalog”部分中查看扫描进度。
- 在导航菜单中,前往治理部分中的 Knowledge Catalog 和数据分析和质量评估。
- 找到
dq-scan。扫描完成后,点击扫描以查看结果。
清理
为避免因您在本教程中创建的资源而产生定期结算费用,请删除这些资源。
删除 Knowledge Catalog 扫描
使用此 Codelab 中的特定扫描名称删除您的分析和质量扫描:
# Delete the Data Quality Scan
gcloud dataplex datascans delete dq-scan \
--location=us-central1 \
--project=$PROJECT_ID --quiet
# Delete the Data Profile Scans
gcloud dataplex datascans delete profile-scan-mv-ga4-user-session-flat \
--location=us-central1 \
--project=$PROJECT_ID --quiet
gcloud dataplex datascans delete profile-scan-mv-ga4-ecommerce-transactions \
--location=us-central1 \
--project=$PROJECT_ID --quiet
gcloud dataplex datascans delete profile-scan-mv-ga4-ecommerce-items \
--location=us-central1 \
--project=$PROJECT_ID --quiet
删除示例数据集
删除临时 BigQuery 数据集及其表。
bq rm -r -f --dataset $PROJECT_ID:kc_dq_codelab
删除本地文件
停用 Python 虚拟环境,并移除克隆的代码库及其内容:
deactivate
cd ../../..
rm -rf devrel-demos
总结
恭喜!您已构建了一个端到端的程序化数据质量和元数据丰富工作流。
通过将 Antigravity CLI 智能体与 Knowledge Catalog 配对,您可以为 AI 辅助元数据丰富建立可验证的基础。这种方法可加快声明式规则的创建速度,让数据管理员能够专注于人机协同 (HITL) 验证和根据业务逻辑优化规则,从而确保数据目录充当企业 AI 使用的可信上下文引擎。
后续步骤
- 如需详细了解此架构背后的理念,请参阅 AI 辅助治理:通过人工监督提高数据质量。
- 通过创建 CI/CD 流水线,以代码形式管理数据质量。
- 探索如何使用自定义 SQL 规则来强制执行特定业务逻辑。
- 使用过滤和抽样功能优化扫描,以降低费用。
- 通过使用 Terraform 预配 Knowledge Catalog 资源,实现基础设施自动化,从而大规模管理数据质量规范和元数据丰富。
- 如需了解详情,请参阅 Antigravity CLI 快速入门。
- 尝试其他 Knowledge Catalog 应用场景。