Menggunakan kembali aturan kualitas data

Dokumen ini menjelaskan cara menggunakan kembali aturan kualitas data Knowledge Catalog (sebelumnya Dataplex Universal Catalog) untuk menentukan dan mengelola aturan bisnis standar.

Penggunaan ulang aturan memungkinkan Anda membagikan definisi aturan bisnis yang kompleks atau standar di beberapa aturan dan pemindaian kualitas data menggunakan template aturan. Dokumen ini juga menjelaskan cara menyiapkan, membuat, dan mengelola template aturan yang dapat digunakan kembali, serta cara melampirkan aturan kualitas data ke entri katalog sebagai aspek metadata.

Kasus penggunaan

Anda dapat menggunakan kemampuan penggunaan ulang aturan kualitas data untuk skenario berikut:

  • Menyeragamkan dan membagikan definisi aturan: Gunakan template aturan kustom untuk menyimpan definisi aturan bisnis yang kompleks atau standar. Hal ini mengurangi waktu dan upaya yang diperlukan untuk mendistribusikan definisi umum dengan menggunakan ekspresi SQL yang dibuat dalam template. Misalnya, tim tata kelola data pusat dapat menentukan template email yang valid atau SSN yang valid standar yang digunakan kembali di seluruh organisasi, sehingga memastikan konsistensi dan mengurangi beban operasional dalam mengelola aturan duplikat.
  • Menerapkan kualitas yang didorong tata kelola: Deklarasikan aturan data sebagai metadata dengan menggunakan aspek Knowledge Catalog pada tabel BigQuery dan entri istilah glosarium bisnis. Hal ini membuat aturan Anda dapat ditelusuri dan digunakan kembali. Misalnya, saat Anda menautkan kolom ke istilah glosarium, kolom tersebut dapat otomatis mewarisi aturan validasi yang ditentukan untuk istilah tersebut, sehingga memungkinkan kebijakan tata kelola otomatis melalui pewarisan metadata semantik.
  • Menelusuri dan menemukan aturan yang dapat digunakan kembali: Temukan aturan yang ada dalam organisasi Anda melalui penelusuran semantik. Hal ini memungkinkan analis dan engineer data menemukan set aturan standar yang terverifikasi (seperti "Konstanta Keuangan Dasar") dan mem-bootstrap kualitas data untuk project baru tanpa menulis SQL dari awal.
  • Menghilangkan masalah cold start: Manfaatkan template aturan sistem untuk evaluasi yang sering digunakan, seperti pemeriksaan null atau ekspektasi rentang. Dengan template bawaan ini, Anda dapat dengan cepat menyiapkan pemantauan kualitas data untuk skenario umum tanpa perlu menulis SQL kustom.
  • Mengaktifkan pemisahan tugas: Memungkinkan tim tata kelola pusat membuat template aturan terverifikasi, sementara tim engineering berfokus untuk menerapkan aturan ini ke aset data mereka tanpa harus menulis atau memelihara SQL yang kompleks. Pembagian tanggung jawab yang jelas ini meningkatkan ketangkasan organisasi dan memastikan bahwa standar kualitas data diterapkan secara konsisten di seluruh perusahaan.

Sebelum memulai

  1. Mengaktifkan Dataplex API.

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan izin serviceusage.services.enable. Jika Anda membuat project, kemungkinan Anda sudah memiliki izin ini melalui peran Pemilik (roles/owner). Jika tidak, Anda bisa mendapatkan izin ini melalui peran Admin Penggunaan Layanan (roles/serviceusage.serviceUsageAdmin). Pelajari cara memberikan peran.

    Mengaktifkan API

Sebelum menggunakan kemampuan penggunaan ulang aturan kualitas data, pastikan Anda telah menyelesaikan persyaratan berikut.

Menyiapkan lingkungan Dataplex API

Untuk menggunakan contoh REST API dalam dokumen ini, siapkan alias untuk gcurl dan konfigurasi variabel lingkungan ${DATAPLEX_API}.

  1. Tetapkan alias gcurl. Tindakan ini akan membuat pintasan yang menyertakan token autentikasi Anda dan menetapkan jenis konten JSON untuk permintaan API:

    alias gcurl='curl -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"'
    
  2. Tetapkan variabel DATAPLEX_API:

    DATAPLEX_API="dataplex.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION"

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda.
    • LOCATION: lokasi tempat pemindaian atau resource Anda berada (misalnya, us-central1).

Menyiapkan akun layanan

Akun layanan wajib ada untuk menjalankan pemindaian kualitas data dengan aturan yang dapat digunakan kembali. Buat akun layanan yang memiliki peran dan izin Identity and Access Management berikut:

  • Anda harus memiliki izin iam.serviceAccounts.actAs di project yang menghosting akun layanan (biasanya dengan menggunakan peran roles/iam.serviceAccountUser).
  • Berikan izin iam.serviceAccounts.getAccessToken pada akun layanan untuk project pemindaian kepada Agen Layanan Dataplex (service-PROJECT_ID@gcp-sa-dataplex.iam.gserviceaccount.com) (misalnya, dengan menggunakan peran roles/iam.serviceAccountTokenCreator).
  • Akun layanan harus memiliki izin berikut:
    • bigquery.tables.getData pada tabel yang akan dipindai (misalnya, dengan menggunakan roles/bigquery.dataViewer).
    • bigquery.jobs.insert dalam project pemindaian (misalnya, dengan menggunakan roles/bigquery.jobUser).
    • roles/bigquery.dataEditor pada set data ekspor (jika menggunakan ekspor).

Peran dan izin yang diperlukan

Pastikan Anda memiliki peran IAM berikut untuk tugas tertentu:

  • Pengelolaan pemindaian data: Peran pemindaian data yang diperlukan untuk mengelola resource pemindaian data.
  • Pengelolaan template aturan: Untuk membuat atau memperbarui template aturan, Anda harus memiliki izin yang diperlukan untuk mengelola entri dalam grup entri atau project template aturan. Secara khusus, roles/dataplex.catalogEditor atau roles/dataplex.entryOwner memberikan izin ini.
  • Mereferensikan template aturan dari aturan: Anda harus memiliki izin dataplex.entries.get dan dataplex.entries.getData pada grup entri template aturan atau project yang direferensikan oleh aturan.
  • Melampirkan aturan kualitas data ke tabel BigQuery: Untuk melampirkan aturan kualitas data sebagai metadata Knowledge Catalog, Anda harus memiliki salah satu hal berikut:
    • bigquery.tables.update atau roles/bigquery.dataEditor pada tabel dan dataplex.entryGroups.useDataRulesAspect pada grup entri @bigquery di lokasi tabel.
    • roles/dataplex.catalogEditor pada grup entri @bigquery.
  • Melampirkan aturan kualitas data ke istilah glosarium bisnis: Untuk melampirkan aturan kualitas data sebagai metadata Knowledge Catalog, Anda harus memiliki salah satu hal berikut:
    • dataplex.glossaryTerms.update pada istilah dan dataplex.entryGroups.useDataRulesAspect pada grup entri @dataplex.
    • roles/dataplex.catalogEditor pada grup entri @dataplex.
  • Membuat pemindaian kualitas data dengan aturan berbasis entri: Anda harus memiliki salah satu hal berikut:
    • bigquery.tables.get dan bigquery.tables.getData di atas meja.
    • dataplex.entries.get dan dataplex.entries.getData pada grup entri @bigquery di lokasi tabel.

Sintaksis kueri SQL untuk template aturan

Saat menulis logika SQL untuk template aturan, Anda harus memberikan pernyataan yang menampilkan baris yang tidak valid. Jika kueri menampilkan baris apa pun, aturan akan gagal. Untuk mengetahui informasi selengkapnya, lihat SqlAssertion.

Ikuti panduan berikut untuk menulis SQL template aturan:

  • Hapus titik koma di akhir pernyataan SQL.
  • Gunakan ${param(name)} untuk mereferensikan parameter input, misalnya, ${param(min_value)}.
  • Gunakan $${...} to escape a literal ${...} and prevent it from being replaced as a parameter.
  • Parameter variables are case-sensitive.

System-supported parameters

You can use the following system-supported parameters in your rule template SQL:

  • ${project()}: The project ID of the resource being scanned.
  • ${dataset()}: The BigQuery dataset ID of the resource being scanned, formatted as PROJECT_ID.DATASET_ID.
  • ${table()}: The BigQuery table ID of the resource being scanned, formatted as PROJECT_ID.DATASET_ID.TABLE_ID.
  • ${column()}: The column the rule is evaluated on. An error occurs during rule evaluation if the rule is attached to the table level but references ${column()}.
  • ${data()}: A reference to the data source table and all of its precondition filters like row filters, sampling percentages, and incremental filters defined in the scan specification. For more information, see Data reference parameter.

Example 1: Validate column values are between two values

The following example validates that all values in a column are between a minimum and maximum value:

SELECT *
FROM ${data()}
WHERE
  NOT ((${column()}>=${param(min_value)} AND ${column()}<=${param(max_value)}) IS TRUE)

Note the following:

  • Using NOT(condition) IS TRUE returns invalid rows, including rows with NULL values in the column.
  • Using ${data()} limits the scope of rows evaluated to the source table and its filters, such as row filters, sampling percentages, and incremental filters.
  • Using ${column()} lets you reference the column that the rule using this template is evaluated on.

Example 2: Foreign key validation

The following example verifies that each value in a column exists in a primary key column of another table:

SELECT t.*
FROM ${data()} AS t
LEFT JOIN `${param(reference_table)}` AS s
  ON t.${column()} = s.`${param(reference_column)}`
WHERE s.`${param(reference_column)}` IS NULL

Input parameters for this template are as follows:

  • reference_table: The name of the reference table containing the primary keys. Use the format PROJECT_ID.DATASET_ID.TABLE_ID.

  • reference_column: The name of the primary key column in the reference table.

System rule templates

Knowledge Catalog provides system rule templates that can be used in any region. Knowledge Catalog manages these templates in the dataplex-templates project under the rule-library entry group. An example of a full resource name is projects/dataplex-templates/locations/global/entryGroups/rule-library/entries/non_null_expectation.

To view the list of all the available system rule templates, see System rule templates list.

To find the available list of system rule templates, select one of the following options:

Console

  1. In the Google Cloud console, go to the Data profiling & quality page.

    Go to Data profiling & quality

  2. Click Rule libraries > System.

  3. To see the list of available system rule templates, click rule-library.

When creating a new rule, you can select the system rule templates in the Choose rule types menu.

REST

To find the available list of system rule templates, use the entries.list method:

gcurl "https://dataplex.googleapis.com/v1/projects/dataplex-templates/locations/global/entryGroups/rule-library/entries"

Known differences between system rule templates and built-in rules

The following table describes the differences between system rule templates and built-in rules:

Feature System rule templates Built-in rules
Source Reusable templates in the catalog Built-in in the API
Referencing Can be referenced by catalog entries and scans Can only be used in scans

The following list describes additional differences in how metrics are calculated for system rule templates:

  • Assertion Row Count metric: This metric is populated for all template reference rules, not just SQL assertion rules.
  • Statistic Range Expectation rule template: Rule metrics from evaluation of rules referencing this template wouldn't contain the nullCount metric. Because it is an aggregate rule, the ignore null capability isn't supported, and rule success is determined by the aggregate statistic being within the defined range.
  • Uniqueness Expectation rule template: This template calculates passedCount differently than the built-in UniquenessExpectation rule. The rule template returns all rows for which duplicate values or null rows exist, which can result in fewer passing rows if duplicates are present.

    For example, if a column contains the values (a, a, b, b, c, d, e):

    • Built-in uniqueness rule: Returns 5 passing rows: (a, b, c, d, e).
    • Uniqueness rule template: Returns 4 failing rows: (a, a, b, b). The number of passing rows is 3 (7 total rows minus 4 failed rows): (c, d, e).

Metadata aspects

This section describes the fields and values for the data-rules and data-quality-rule-template aspect types.

data-rules aspect fields

To define data rules, use the dataplex-types.global.data-rules aspect. The following table describes the fields for this aspect.

Field Type Description
rules Array Required. A list of data quality rules.
rules[].name String Required. A name for the rule.
rules[].dimension String Optional. The data quality dimension for the rule.
rules[].description String Optional. The description of the rule.
rules[].suspended Boolean Optional. Whether the rule is active or suspended. Default is false.
rules[].threshold Double Optional. The passing threshold for the rule, from 0.0 to 1.0. Default is 1.0.
rules[].type Enum Required. The type of the rule. The only supported value is TEMPLATE_REFERENCE.
rules[].ignore_null Boolean Optional. If true, rows with null values in the column are ignored when determining the success criteria.
rules[].attributes Map Optional. Custom key-value pairs associated with the rule.
rules[].templateReference Object Required. A reference to the rule template.
rules[].templateReference.name String Required. The resource name of the rule template.
rules[].templateReference.values Map Optional. The parameter names and values for the rule template.
rules[].templateReference.values[].parameterValue.value String Required. The value for the parameter.

The following example shows a data-rules aspect in a payload.json file:

{
  "aspects": {
    "dataplex-types.global.data-rules": {
      "data": {
        "rules": [
          {
            "name": "valid-email",
            "dimension": "VALIDITY",
            "type": "TEMPLATE_REFERENCE",
            "templateReference": {
              "name": "projects/my-project/locations/us-central1/entryGroups/my-rules/entries/email-check",
              "values": {
                "column_name": {
                    "value": "email"
                }
              }
            }
          }
        ]
      }
    }
  }
}

data-quality-rule-template aspect fields

Use the data-quality-rule-template aspect to define a custom data quality rule template. The following table describes the fields for the dataplex-types.global.data-quality-rule-template aspect.

Field Type Description
dimension String Required. The dimension for the rule template.
sqlCollection Array Required. A list of SQL queries for the rule template.
sqlCollection[].sql.query String Required. The SQL query that returns invalid rows.
inputParameters Map Optional. A map of input parameters for the rule template.
inputParameters[].parameterDescription.description String Optional. The description of the input parameter.
inputParameters[].parameterDescription.defaultValue String Optional. The default value for the parameter if no value is provided.
capabilities Array Optional. A list of template capabilities, such as THRESHOLD or IGNORE_NULL.

The following example displays the structure of a data-quality-rule-template aspect:

{
  "entryType": "projects/dataplex-types/locations/global/entryTypes/data-quality-rule-template",
  "aspects": {
    "dataplex-types.global.data-quality-rule-template": {
      "data": {
        "dimension": "COMPLETENESS",
        "sqlCollection": [
          {
              "query": "SELECT * FROM ${data()} WHERE ${column()} > ${param(p1)}"
          }
        ],
        "inputParameters": {
          "p1": {
              "description": "The parameter description"
          }
        },
        "capabilities": [
          "THRESHOLD",
          "IGNORE_NULL"
        ]
      }
    }
  }
}

Manage data quality rule templates

This section describes how to create, edit, and delete rule templates.

Create a rule library

To create a rule library, you must create a Knowledge Catalog entry group.

Console

  1. In the Google Cloud console, go to the Data profiling & quality page.

    Go to Data profiling & quality

  2. Go to Rule libraries > Custom, and click Create.

  3. In the Create rule library window, fill in the following fields:

    1. Optional: Enter a display name.
    2. In Rule library ID, enter an ID. For more information, see the resource naming conventions.
    3. Optional: Enter a description.
    4. In the Location menu, select a location. It can't be changed later.
    5. Optional: Add labels. Labels are key-value pairs that let you group related objects together or with other Google Cloud resources.
    6. Click Save.

REST

To create a rule library by using the API, you must create an entry group with the required label goog-dataplex-entry-group-type: rule_library:

gcurl -X POST "https://${DATAPLEX_API}/entryGroups?entryGroup_id=RULE_LIBRARY_ID" \
--data @- << EOF
{
"labels": {
  "goog-dataplex-entry-group-type": "rule_library"
},
"description": "DESCRIPTION"
}
EOF

Replace the following:

  • RULE_LIBRARY_ID: a unique ID for your rule library.
  • DESCRIPTION: an optional description for the rule library.

Terraform

To create a rule library, use the google_dataplex_entry_group resource:

resource "google_dataplex_entry_group" "rule_library" {