建立自動剖析和資料品質規則,即可在中繼資料加入信任信號和業務背景資訊。
採用Human-in-the-Loop方法,由 AI 擬定初始規則,再由您審查、修正及驗證,即可快速將剖析統計資料轉換為資料品質架構。
目標
- 使用 materialized view 簡化巢狀 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 商品網路商店的公開電子商務資料集。
下列
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 可找出頂層資料欄的統計資料,例如資料中的空值百分比、不重複性和值分布,協助您瞭解資料。
如要取得巢狀欄位的統計資料,可以使用一組 materialized view 將資料扁平化。這會將每個巢狀欄位轉換為 Knowledge Catalog 可剖析的頂層資料欄。
取得巢狀結構定義
取得來源資料表的完整結構定義 (包括所有巢狀結構),並將輸出內容儲存為 JSON 檔案:
bq show --schema --format=json $PROJECT_ID:$DATASET_ID.$TABLE_ID > bq_schema.json
查看結構定義:
jq < bq_schema.json
bq_schema.json 檔案會顯示複雜的結構。
使用 materialized view 簡維資料
將巢狀資料扁平化時,請務必避免在同一個檢視表中取消巢狀結構的多個獨立陣列。這樣做會對陣列執行隱含 cross join (笛卡爾乘積),導致資料列不正確地相乘,並損毀資料。
建議您建立多個檢視表,每個檢視表都用於特定用途。每個檢視畫面都應維持單一、清楚的詳細程度。在這個步驟中,您會建立下列 materialized view:
- 工作階段平面檢視 (
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 用戶端執行設定檔掃描
您現在可以為各個 materialized view 建立及執行 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 指令碼。這個指令碼會為三個 materialized view 分別建立及執行掃描作業,藉此剖析這些檢視表。完成後,系統會輸出豐富的統計摘要,您可以在下一個步驟中使用這項摘要,生成 AI 輔助資料品質規則。
從 Cloud Shell 終端機執行指令碼。
python3 1_run_scan.py
查看剖析掃描作業
您可以在 Google Cloud 控制台查看新的設定檔掃描作業。
- 在導覽選單中,依序前往「Knowledge Catalog」和「Govern」(管理) 專區中的「Data profiling & quality」(資料剖析與品質)。
- 找出列出的三項個人資料掃描作業,以及最新工作狀態。點選掃描作業,即可查看詳細結果。
將設定檔結果匯出為 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 可以讀取目前目錄中的檔案,因此能直接使用新的設定檔掃描資料。
提示代理建立計畫
首先,請代理分析統計資料,並提出行動計畫。指示 Gemini 先不要編寫 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 代理可能會假設,如果某個資料欄在一天樣本中的空值比例為 0%,就不應包含空值,或根據有限的歷來分布情形設定嚴格的數值範圍。
- 動作:確認建議的界限 (例如
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」和「Govern」(管理) 專區中的「Data profiling & quality」(資料剖析與品質)。
- 找出
dq-scan。掃描完成後,按一下掃描作業即可查看結果。
清除所用資源
為避免系統向您收取本教學課程所建立資源的週期性付款,請刪除這些資源。
刪除 Knowledge Catalog 掃描作業
使用本程式碼實驗室中的特定掃描名稱,刪除設定檔和品質掃描:
# 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 應用實例。