通过建立自动剖析和数据质量规则,您可以使用信任信号和业务情境来丰富元数据。
借助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;或者,AI 智能体可能会根据有限的历史分布情况设置严格的数值范围。
- 操作:验证建议的边界(例如
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 辅助的元数据丰富功能奠定可验证的基础。这种方法可加快声明性规则的创建速度,让数据管家能够专注于 Human-in-the-Loop (HITL) 验证和根据业务逻辑优化规则,从而确保数据目录充当企业 AI 使用的可信上下文引擎。
后续步骤
- 如需详细了解此架构背后的理念,请参阅 AI 辅助治理:通过人工监督提高数据质量。
- 通过创建 CI/CD 流水线,以代码形式管理数据质量。
- 探索如何使用自定义 SQL 规则来强制执行特定于业务的逻辑。
- 通过使用过滤条件和抽样来优化扫描,以降低费用。
- 通过使用 Terraform 预配 Knowledge Catalog 资源来自动执行基础设施操作,从而大规模管理数据质量规范和元数据丰富。
- 如需了解详情,请参阅 Antigravity CLI 快速入门。
- 尝试其他 Knowledge Catalog 应用场景