建構以程式碼即政策為基礎的資料品質工作流程

建立以程式碼做為政策的資料品質和中繼資料擴充工作流程。本教學課程將說明如何定義宣告式、設有版本管控的檔案,藉此定義資料品質期望,擺脫手動程序。

建立自動剖析和資料品質規則,並使用信任信號和業務脈絡資訊充實中繼資料。

採用「人機迴圈」Human-in-the-Loop方法,由 AI 草擬初始規則,您負責審查、修正及驗證,即可快速將剖析檔統計資料轉換為資料品質架構。

目標

  • 使用具體化檢視區塊將巢狀 BigQuery 資料攤平,以啟用 Knowledge Catalog 剖析功能。
  • 使用 Python 用戶端程式庫執行 Knowledge Catalog 剖析掃描作業。
  • 使用 Antigravity CLI 根據剖析統計資料生成資料品質規則。
  • 透過人機迴圈審查程序,驗證並部署 AI 生成的規則,做為 Knowledge Catalog 品質掃描作業。

事前準備

開始之前,請確認您已啟用專案的計費功能。 Google Cloud

準備環境

下列步驟使用 Cloud Shell,這是可在雲端執行的指令列環境。

  1. 在 Google Cloud 控制台,按一下右上工具列中的「啟用 Cloud Shell」。佈建並連線至環境預計只需要幾分鐘。

  2. 在 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 查詢,來源資料和目的地資料表必須位於相同位置。

  3. 啟用必要服務:

    gcloud services enable dataplex.googleapis.com \
                           bigquery.googleapis.com \
                           serviceusage.googleapis.com \
                           aiplatform.googleapis.com
    
  4. 建立 BigQuery 資料集,用於儲存範例資料和結果:

    bq --location=us mk --dataset $PROJECT_ID:$DATASET_ID
    
  5. 準備範例資料,這些資料來自 Google 商品網路商店的公開電子商務資料集。

    下列 bq 指令會在 kc_dq_codelab 資料集中建立新的資料表 ga4_transactions。為確保掃描作業快速執行,系統只會複製一天的資料 (2021 年 1 月 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`'
    
  6. 複製包含本教學課程資料夾結構和支援檔案的 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 會找出頂層資料欄的統計資料,例如資料中的空值百分比、唯一性和值分布情形,協助您瞭解資料。

如要取得巢狀欄位的統計資料,可以使用一組具體化檢視區塊整併資料。這會將每個巢狀欄位轉換為 Knowledge Catalog 可剖析的頂層資料欄。

取得巢狀結構定義

取得來源資料表的完整結構定義 (包括所有巢狀結構),並將輸出內容儲存為 JSON 檔案:

bq show --schema --format=json $PROJECT_ID:$DATASET_ID.$TABLE_ID > bq_schema.json

查看結構定義:

jq < bq_schema.json

bq_schema.json 檔案會顯示複雜的結構。

使用具體化檢視表將資料扁平化

攤平巢狀資料時,請勿在同一個檢視區塊中取消巢狀結構的多個獨立陣列。這麼做會在陣列之間執行隱含的 cross join (笛卡爾乘積),導致資料列相乘時發生錯誤,進而損毀資料。

建議您改為建立多個資料檢視,每個資料檢視都用於特定用途。每個檢視畫面都應維持單一且清楚的詳細程度。在這個步驟中,您會建立下列具體化檢視區塊:

  • 工作階段平面檢視畫面 (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 指令碼。這項指令碼會為三個具體化檢視區建立並執行掃描作業,藉此剖析這些檢視區。完成後,系統會輸出豐富的統計摘要,您可以在下一個步驟中使用這些摘要,生成 AI 輔助的資料品質規則。

從 Cloud Shell 終端機執行指令碼。

python3 1_run_scan.py

查看剖析掃描作業

您可以在 Google Cloud 控制台查看新的設定檔掃描結果。

  1. 在導覽選單中,前往「管理」部分的「Knowledge Catalog」和「資料剖析與品質」
  2. 畫面上會列出三項商家檔案掃描結果,以及最新的工作狀態。按一下掃描結果即可查看詳細資料。

將設定檔結果匯出為 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) 審查。代理程式生成的計畫完全是根據資料中的統計模式。代理程式無法瞭解您的業務脈絡、未來的資料變更,或資料背後的具體意圖。您是人類專家,負責驗證、修正及核准這項計畫,再將其轉換為程式碼。

人機迴圈審查期間的驗證項目

根據下列核心業務條件,檢查代理程式提出的計畫:

  • 統計異常與實際業務情況
    • 原因:AI 代理程式可能會假設一日樣本中空值為 0% 的資料欄絕不應包含空值,或根據有限的過往分布情況設定嚴格的數值範圍。
    • 動作:確認建議的界線 (例如 rangeExpectationnonNullExpectation) 是否反映真實的業務限制,或只是樣本集構件。
  • 不穩定指標 (例如列數)
    • 原因:在活躍的企業環境中,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 檔案。

建立及執行資料品質掃描作業

您現在有一組由代理程式生成並經過人工驗證的資料品質規則,可以註冊並部署為掃描作業。

  1. 輸入 /quit 或按兩次 Ctrl+C,即可退出 Antigravity CLI。

  2. 接著,在 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"
    
  3. 執行掃描:

    gcloud dataplex datascans run $DQ_SCAN --location=$LOCATION --project=$PROJECT_ID
    

    這個指令會建立名為 dq-scan 的資料品質掃描作業。

  4. 在 Google Cloud 控制台的 Knowledge Catalog 部分,查看掃描進度。

    1. 在導覽選單中,前往「管理」部分的「Knowledge Catalog」和「資料剖析與品質」
    2. 找出 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 消耗的可靠脈絡引擎。

後續步驟