重复使用数据质量规则

本文档介绍了如何重复使用 Knowledge Catalog(以前称为 Dataplex Universal Catalog)数据质量规则来定义和管理标准化业务规则。

借助规则模板,您可以在多个数据质量规则和扫描之间共享复杂或标准化的业务规则定义,从而实现规则的可重复使用性。本文档还介绍了如何设置、创建和管理可重复使用的规则模板,以及如何将数据质量规则作为元数据方面附加到目录条目。

使用场景

您可以在以下场景中使用数据质量规则的可重复使用性:

  • 标准化和共享规则定义:使用自定义规则模板存储复杂或标准化的业务规则定义。这可以通过使用模板化的 SQL 表达式来减少分发常见定义所需的时间和精力。例如,中央数据治理团队可以定义一个标准 有效电子邮件有效 SSN 模板,该模板可在整个组织中重复使用,从而确保一致性并减少管理重复规则的运营开销。
  • 实现治理驱动的质量:通过在 BigQuery 表和业务术语库术语条目中使用 Knowledge Catalog 方面,将 数据规则声明为元数据。这使得您的规则可搜索且可重复使用。例如,当您将列链接到术语库术语时,该列可以自动继承为该术语定义的验证规则,从而通过语义元数据继承实现自动化治理政策。
  • 搜索和发现可重复使用的规则:通过语义搜索在组织内查找现有规则。这使得数据分析师和工程师能够发现经过验证的标准化规则集(例如“基准财务常量”),并为新项目启动数据质量,而无需从头编写 SQL。
  • 消除冷启动问题:利用 系统规则模板 进行常用评估,例如 null 检查或范围预期。借助这些内置模板,您可以快速为常见场景设置数据质量监控,而无需编写自定义 SQL。
  • 实现关注点分离:允许中央治理团队编写经过验证的规则模板,而工程团队则专注于将这些规则应用于其数据资产,而无需编写或维护复杂的 SQL。这种明确的职责划分提高了组织的敏捷性,并确保在整个企业中一致应用数据质量标准。

准备工作

  1. 启用 Dataplex API。

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您 创建了项目,则可能已通过 所有者角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获得此权限。 了解如何授予角色

    启用 API

在使用数据质量规则的可重用性之前,请确保您已完成以下要求。

设置 Dataplex API 环境

如需使用本文档中的 REST API 示例,请为 gcurl 设置别名,并配置 ${DATAPLEX_API} 环境变量。

  1. 设置 gcurl 的别名。这会创建一个快捷方式,其中包含您的身份验证令牌,并为 API 请求设置 JSON 内容类型:

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

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

    替换以下内容:

    • PROJECT_ID:您的项目 ID。
    • LOCATION:扫描或资源所在的位置(例如,us-central1)。

设置服务帐号

必须使用服务帐号才能运行具有可重复使用规则的数据质量扫描。 创建服务账号,该账号具有 以下 Identity and Access Management 角色和权限:

  • 您必须对托管服务帐号的项目拥有 iam.serviceAccounts.actAs 权限(通常通过使用 roles/iam.serviceAccountUser 角色)。
  • 为扫描项目的 Dataplex 服务代理 (service-PROJECT_ID@gcp-sa-dataplex.iam.gserviceaccount.com) 授予服务帐号的 iam.serviceAccounts.getAccessToken 权限(例如,通过使用 roles/iam.serviceAccountTokenCreator 角色)。
  • 该服务帐号必须具有以下权限:
    • 要扫描的表的 bigquery.tables.getData 权限(例如,通过使用 roles/bigquery.dataViewer)。
    • 扫描项目中的 bigquery.jobs.insert 权限(例如,通过使用 roles/bigquery.jobUser)。
    • 导出数据集的 roles/bigquery.dataEditor 权限(如果使用导出)。

所需的角色和权限

确保您拥有以下 IAM 角色,以执行特定任务:

  • 数据扫描管理管理数据扫描资源所需的数据扫描角色
  • 规则模板管理:如需创建或更新规则模板,您必须 拥有管理规则模板的 条目组或项目中的条目所需的权限。具体而言,roles/dataplex.catalogEditorroles/dataplex.entryOwner 授予这些权限。
  • 从规则引用规则模板:您必须对规则引用的规则模板的条目组或 项目拥有 dataplex.entries.getdataplex.entries.getData 权限。
  • 将数据质量规则附加到 BigQuery 表:如需将数据 质量规则作为 Knowledge Catalog 元数据附加,您必须拥有 以下权限之一:
    • 表的 bigquery.tables.updateroles/bigquery.dataEditor 权限,以及表位置中 @bigquery 条目组的 dataplex.entryGroups.useDataRulesAspect 权限。
    • @bigquery 条目组的 roles/dataplex.catalogEditor 权限。
  • 将数据质量规则附加到业务术语库术语:如需将数据 质量规则作为 Knowledge Catalog 元数据附加,您必须拥有以下权限之一:
    • 术语的 dataplex.glossaryTerms.update 权限,以及 @dataplex 条目组的 dataplex.entryGroups.useDataRulesAspect 权限。
    • @dataplex 条目组的 roles/dataplex.catalogEditor 权限。
  • 使用基于条目的规则创建数据质量扫描:您必须拥有以下权限之一:
    • 表的 bigquery.tables.getbigquery.tables.getData 权限。
    • dataplex.entries.getdataplex.entries.getData 权限,位于表位置中 @bigquery 条目组。

规则模板的 SQL 查询语法

为规则模板编写 SQL 逻辑时,您必须提供返回无效行的语句。如果查询返回任何行,则规则失败。如需了解详情,请参阅 SqlAssertion

请遵循以下准则编写规则模板 SQL:

  • 从 SQL 语句中省略末尾的英文分号。
  • 使用 ${param(name)} 引用输入参数,例如 ${param(min_value)}
  • 使用 $${...} 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":