使用自动数据质量

本文档介绍了如何使用 Knowledge Catalog(以前称为 Dataplex Universal Catalog)数据质量扫描来衡量、监控和管理数据质量。数据质量扫描有助于您自动执行验证数据完整性、有效性和一致性的流程。

借助数据质量扫描,您可以定义规则来检查缺失值、确保值与正则表达式匹配或属于某个集合、验证唯一性,或者使用自定义 SQL 进行更复杂的验证(例如异常检测)。本文档介绍了如何创建和管理数据质量扫描。

详细了解数据质量扫描。 详细了解如何在多次扫描中重复使用数据质量规则

准备工作

  1. 启用 Dataplex API。

    启用 API 所需的角色

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

    启用 API

  2. 可选:如需根据数据分析扫描的结果生成数据质量规则的建议,请创建并运行数据分析扫描

所需的角色和权限

本部分介绍了使用 Knowledge Catalog 数据质量扫描所需的 IAM 角色和权限。

用户角色和权限

如需获得运行和管理数据质量扫描所需的权限,请让您的管理员为您授予以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

这些预定义角色包含运行和管理数据质量扫描所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需运行和管理数据质量扫描,您需要具备以下权限:

  • 对 BigQuery 表运行数据质量扫描:
    • 项目的 bigquery.jobs.create 权限(用于运行扫描作业)
    • 要扫描的 BigQuery 表的 bigquery.tables.get 权限
    • 要扫描的 BigQuery 表的 bigquery.tables.getData 权限
  • 将数据质量扫描结果发布到 Knowledge Catalog:
    • 针对扫描表的 bigquery.tables.update
    • dataplex.entryGroups.useDataQualityScorecardAspect 针对与表位于同一位置的 @bigquery 条目组
  • 创建 DataScandataplex.datascans.create 针对项目的
  • 删除DataScandataplex.datascans.delete 对项目的权限
  • 查看 DataScan 元数据:针对项目的 dataplex.datascans.get 权限
  • 查看 DataScan 详细信息(包括规则和结果): 项目的 dataplex.datascans.getData
  • 列出 DataScan: 针对项目的 dataplex.datascans.list 权限
  • 运行 DataScandataplex.datascans.run 在项目上
  • 更新 DataScan: 项目上的 dataplex.datascans.update
  • DataScan 上获取或设置 IAM 政策:
    • 针对项目的 dataplex.datascans.getIamPolicy 权限
    • 针对项目的 dataplex.datascans.setIamPolicy 权限

您也可以使用自定义角色或其他预定义角色来获取这些权限。

如果您需要访问受 BigQuery 列级访问权限政策保护的列,则还需要拥有这些列的权限。

Knowledge Catalog 服务账号角色和权限

如果您尚未创建任何数据质量或数据分析扫描,或者此项目中没有 Knowledge Catalog 数据湖,请运行以下命令来创建服务标识符:gcloud beta services identity create --service=dataplex.googleapis.com。如果 Knowledge Catalog 服务标识符存在,此命令会返回该标识符。

如需确保包含数据质量扫描的项目中的 Knowledge Catalog 服务账号拥有从各种来源读取数据和导出结果所需的权限,请让您的管理员为包含数据质量扫描的项目中的 Knowledge Catalog 服务账号授予以下 IAM 角色:

  • 读取 BigQuery 表数据: 针对要扫描的表和规则中引用的任何其他表的 BigQuery Data Viewer (roles/bigquery.dataViewer)
  • 读取 Iceberg REST 目录、SAP Business Data Cloud Delta Lake 和 Apache Hive 上的 Google Cloud 湖仓一体表数据: 相应待扫描表和规则中引用的任何其他表上的 BigLake Viewer (roles/biglake.viewer)
  • 将扫描结果导出到 BigQuery 表:结果数据集和表的 BigQuery Data Editor (roles/bigquery.dataEditor)
  • 扫描在 Knowledge Catalog 湖中整理的 BigQuery 数据:
  • 从 Cloud Storage 中扫描 BigQuery 外部表: Cloud Storage 存储桶的 Storage Object Viewer (roles/storage.objectViewer)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

这些预定义角色可提供从各种来源读取数据和导出结果所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

您需要拥有以下权限才能从各种来源读取数据并导出结果:

  • 读取 BigQuery 表数据:
    • bigquery.tables.get 针对 BigQuery 表
    • bigquery.tables.getData 针对 BigQuery 表
  • 将扫描结果导出到 BigQuery 表:
    • 针对结果数据集和表的 bigquery.datasets.get 权限
    • 针对结果数据集和表的 bigquery.tables.create 权限
    • 针对结果数据集和表的 bigquery.tables.get 权限
    • 针对结果数据集和表的 bigquery.tables.getData 权限
    • 针对结果数据集和表的 bigquery.tables.update 权限
    • 针对结果数据集和表的 bigquery.tables.updateData 权限
  • 扫描在 Knowledge Catalog 湖中整理的 BigQuery 数据:
    • dataplex.lakes.list 对 Dataplex 资源
    • dataplex.lakes.get 对 Dataplex 资源
    • dataplex.zones.list 对 Dataplex 资源
    • dataplex.zones.get 对 Dataplex 资源
    • dataplex.entities.list 对 Dataplex 资源
    • dataplex.entities.get 对 Dataplex 资源
    • dataplex.operations.get 对 Dataplex 资源
  • 从 Cloud Storage 扫描 BigQuery 外部表:
    • Cloud Storage 存储桶的 storage.buckets.get 权限
    • Cloud Storage 存储桶的 storage.objects.get 权限

您的管理员也可以使用自定义角色或其他预定义角色为包含数据质量扫描的项目中的 Knowledge Catalog 服务账号授予这些权限。

如果您需要访问受 BigQuery 列级访问权限政策保护的列,请为 Knowledge Catalog 服务账号分配这些列的权限。

如果某个表启用了 BigQuery 行级访问权限政策,则您只能扫描对 Knowledge Catalog 服务账号可见的行。请注意,系统不会针对行级政策评估单个用户的访问权限。

网络要求

如需运行扫描,您必须在用于扫描的 VPC 子网上启用专用 Google 访问通道。如果您未指定子网,请确保您的默认子网已启用专用 Google 访问通道。

定义数据质量规则

您可以使用以下方式定义数据质量规则:

如果您使用的是 Google Cloud CLI,则可以在 JSON 或 YAML 文件中定义这些规则。

以下各部分中的示例展示了如何定义各种数据质量规则。这些规则用于验证包含客户交易数据的示例表。假设该表具有以下架构:

列名 列类型 列说明
transaction_timestamp 时间戳 交易的时间戳。该表按此字段进行分区。
customer_id 字符串 客户 ID,格式为 8 个字母后跟 16 位数字。
transaction_id 字符串 交易 ID 在整个表格中必须是唯一的。
currency_id 字符串 支持的币种之一。货币类型必须与维度表 dim_currency 中的可用货币之一相匹配。
amount float 交易金额。
discount_pct float 折扣百分比。此值必须介于 0 到 100 之间。

使用内置规则类型定义数据质量规则

以下示例基于内置规则类型。您可以使用 Google Cloud 控制台或 API 基于内置规则类型创建规则。Knowledge Catalog 可能会建议其中一些规则。

列名 规则类型 建议的维度 规则参数
transaction_id 唯一性检查 唯一性 阈值:Not Applicable
amount Null 检查 完整性 阈值:100%
customer_id 正则表达式检查 有效期 正则表达式:^[a-zA-Z]{8}[0-9]{16}$
阈值:100%
currency_id 值设置检查 有效期 一组:USD,JPY,INR,GBP,CAN
阈值:100%

使用自定义 SQL 规则定义数据质量规则

如需构建自定义 SQL 规则,请使用以下框架:

  • 创建一次评估一行的规则时,请创建在 Knowledge Catalog 评估查询 SELECT COUNTIF(CUSTOM_SQL_EXPRESSION) FROM TABLE 时生成成功行的数量的表达式。Knowledge Catalog 会根据阈值检查成功行的数量。

  • 创建在多行之间进行评估或使用表条件的规则时,请创建在 Knowledge Catalog 评估查询 SELECT IF(CUSTOM_SQL_EXPRESSION) FROM TABLE 时返回成功或失败结果的表达式。

  • 创建用于评估数据集无效状态的规则时,请提供返回无效行的语句。如果系统返回了任何行,表示此规则失败。从 SQL 语句中省略末尾的英文分号。

  • 您可以使用规则中的数据引用参数 ${data()} 来引用数据源表及其所有前提过滤条件,而无需明确提及源表及其过滤条件。前提过滤条件的示例包括行过滤条件、采样百分比和增量过滤条件。${data()} 参数区分大小写。

以下示例基于自定义 SQL 规则。

规则类型 规则说明 SQL 表达式
行条件 检查 discount_pct 的值是否介于 0 到 100 之间。 0 <discount_pctdiscount_pct < 100
行条件 用于验证 currency_id 是否为支持的货币之一的引用检查。 currency_id in (select id from my_project_id.dim_dataset.dim_currency)
表条件 用于检查平均 discount_pct 是否介于 30% 到 50% 之间的汇总 SQL 表达式。 30<avg(discount) AND avg(discount) <50
行条件 检查日期是否不是将来的日期。 TIMESTAMP(transaction_timestamp) < CURRENT_TIMESTAMP()
表条件 用于检查每个国家/地区的平均交易金额是否低于预定义值的 BigQuery 用户定义的函数 (UDF)。通过运行以下命令创建 (JavaScript) UDF:
        CREATE OR REPLACE FUNCTION
        myProject.myDataset.average_by_country (
          country STRING, average FLOAT64)
        RETURNS BOOL LANGUAGE js AS R"""
        if (country = "CAN" && average < 5000){
          return 1
        } else if (country = "IND" && average < 1000){
          return 1
        } else { return 0 }
        """;
       
用于检查 country=CAN 的平均交易金额的示例规则。
        myProject.myDataset.average_by_country(
        "CAN",
        (SELECT avg(amount) FROM
          myProject.myDataset.transactions_table
            WHERE currency_id = 'CAN'
        ))
      
表条件 用于识别 discount_pct 中异常值的 BigQuery ML 预测子句。它会根据 customercurrencytransaction 检查是否应该应用折扣。该规则会检查预测值与实际值是否至少 99% 的时间都匹配。假设:在使用该规则之前已创建机器学习模型。使用以下命令创建机器学习模型:
  CREATE MODEL
  model-project-id.dataset-id.model-name
        OPTIONS(model_type='logistic_reg') AS
  SELECT
  IF(discount_pct IS NULL, 0, 1) AS label,
  IFNULL(customer_id, "") AS customer,
  IFNULL(currency_id, "") AS currency,
  IFNULL(amount, 0.0) AS amount
  FROM
  `data-project-id.dataset-id.table-names`
  WHERE transaction_timestamp < '2022-01-01';
  
以下规则会检查预测准确率是否高于 99%。
      SELECT
        accuracy > 0.99
      FROM
       ML.EVALUATE
        (MODEL model-project-id.dataset-id.model-name,
         (
          SELECT
            customer_id,
            currency_id,
            amount,
            discount_pct
          FROM
            data-project-id.dataset-id.table-names
          WHERE transaction_timestamp > '2022-01-01';
         )
        )
    
行条件 用于识别 discount_pct 中异常情况的 BigQuery ML 预测函数。该函数会根据 customercurrencytransaction 检查是否应该应用折扣。该规则可识别所有预测不匹配的情况。 假设:在使用该规则之前已创建机器学习模型。使用以下命令创建机器学习模型:
  CREATE MODEL
  model-project-id.dataset-id.model-name
        OPTIONS(model_type='logistic_reg') AS
  SELECT
  IF(discount_pct IS NULL, 0, 1) AS label,
  IFNULL(customer_id, "") AS customer,
  IFNULL(currency_id, "") AS currency,
  IFNULL(amount, 0.0) AS amount
  FROM
  `data-project-id.dataset-id.table-names`
  WHERE transaction_timestamp < '2022-01-01';
  
以下规则会检查每行的折扣预测值是否与实际值匹配。
       IF(discount_pct > 0, 1, 0)
          =(SELECT predicted_label FROM
           ML.PREDICT(
            MODEL model-project-id.dataset-id.model-name,
              (
                SELECT
                  customer_id,
                  currency_id,
                  amount,
                  discount_pct
                FROM
                  data-project-id.dataset-id.table-names AS t
                    WHERE t.transaction_timestamp =
                     transaction_timestamp
                   LIMIT 1
              )
            )
         )
    
SQL 断言 通过检查是否存在折扣百分比小于或等于 30 的任何行,验证当天的 discount_pct 是否大于 30%。 SELECT * FROM my_project_id.dim_dataset.dim_currency WHERE discount_pct <= 30 AND transaction_timestamp >= current_date()
SQL 断言(具有数据引用参数

检查当天所有受支持货币的 discount_pct 是否都大于 30%。

日期过滤条件 transaction_timestamp >= current_date() 会作为行过滤条件应用于数据源表。

数据引用参数 ${data()} 用作 my_project_id.dim_dataset.dim_currency WHERE transaction_timestamp >= current_date() 的占位符,并应用行过滤条件。

SELECT * FROM ${data()} WHERE discount_pct > 30

使用 gcloud CLI 定义数据质量规则

以下示例 YAML 文件使用了一些与使用内置类型的示例规则示例自定义 SQL 规则相同的规则。此 YAML 文件还包含数据质量扫描的其他规范,例如过滤条件和采样率。使用 gcloud CLI 创建或更新数据质量扫描时,您可以将如下所示的 YAML 文件用作 --data-quality-spec-file 参数的输入。

rules:
- uniquenessExpectation: {}
  column: transaction_id
  dimension: UNIQUENESS
- nonNullExpectation: {}
  column: amount
  dimension: COMPLETENESS
  threshold: 1
- regexExpectation:
    regex: '^[a-zA-Z]{8}[0-9]{16}$'
  column : customer_id
  ignoreNull : true
  dimension : VALIDITY
  threshold : 1
- setExpectation :
    values :
    - 'USD'
    - 'JPY'
    - 'INR'
    - 'GBP'
    - 'CAN'
  column : currency_id
  ignoreNull : true
  dimension : VALIDITY
  threshold : 1
- rangeExpectation:
    minValue : '0'
    maxValue : '100'
  column : discount_pct
  ignoreNull : true
  dimension : VALIDITY
  threshold : 1
- rowConditionExpectation:
    sqlExpression : 0 < `discount_pct` AND `discount_pct` < 100
  column: discount_pct
  dimension: VALIDITY
  threshold: 1
- rowConditionExpectation:
    sqlExpression : currency_id in (select id from `my_project_id.dim_dataset.dim_currency`)
  column: currency_id
  dimension: VALIDITY
  threshold: 1
- tableConditionExpectation:
    sqlExpression : 30 < avg(discount_pct) AND avg(discount_pct) < 50
  dimension: VALIDITY
- rowConditionExpectation:
    sqlExpression : TIMESTAMP(transaction_timestamp) < CURRENT_TIMESTAMP()
  column: transaction_timestamp
  dimension: VALIDITY
  threshold: 1
- sqlAssertion:
    sqlStatement : SELECT * FROM `my_project_id.dim_dataset.dim_currency` WHERE discount_pct > 100
  dimension: VALIDITY
  debugQueries:
  - sqlStatement: SELECT MAX(discount_pct) FROM `my_project_id.dim_dataset.dim_currency`
samplingPercent: 50
rowFilter: discount_pct > 100
postScanActions:
  bigqueryExport:
    resultsTable: projects/my_project_id/datasets/dim_dataset/tables/dim_currency
  notificationReport:
    recipients:
      emails:
      - '222larabrown@gmail.com'
      - 'cloudysanfrancisco@gmail.com'
    scoreThresholdTrigger:
      scoreThreshold: 50
    jobFailureTrigger: {}
    jobEndTrigger: {}
catalogPublishingEnabled: true

配置执行身份

默认情况下,数据质量扫描使用 Knowledge Catalog 服务账号运行。您可以替换此设置,以使用自定义服务账号或您自己的最终用户凭据 (EUC)。

使用自定义执行身份会改变扫描的结算方式。指定自定义执行身份后,与扫描相关的计算和存储费用将直接计入您的 BigQuery 项目,而不会使用标准的 Knowledge Catalog Premium SKU。

自定义执行身份所需的权限

如需配置自定义服务账号或使用最终用户凭据,您必须拥有以下额外的 Identity and Access Management (IAM) 权限:

  • 如需使用自定义服务账号,您需要:
    • 为包含服务账号的项目(例如 roles/iam.serviceAccountUser)授予的 iam.serviceAccounts.actAs 权限。
    • 您项目的服务代理 (service-PROJECT_NUMBER@gcp-sa-dataplex.) 需要对自定义服务账号拥有 iam.serviceAccounts.getAccessToken 权限(例如,通过拥有 roles/iam.serviceAccountTokenCreator 角色)。
    • 自定义服务账号需要对表具有 bigquery.tables.getData 权限才能扫描,需要对扫描项目具有 bigquery.jobs.insert 权限,并且需要对导出数据集具有 bigquery.dataEditor 权限(如果使用导出功能)。
  • 如需使用最终用户凭据,您需要:
    • bigquery.tables.getData 扫描表。
    • 扫描项目中的 bigquery.jobs.insert
    • 导出数据集中的 bigquery.dataEditor(如果使用导出)。

如需配置执行身份,请选择以下选项之一:

控制台

如需在 Google Cloud 控制台中配置执行身份,请在创建数据质量扫描时选择相应身份。

执行身份部分中,选择以下选项之一:

  • Dataplex Service Agent:默认行为。
  • 服务账号:输入您要使用的服务账号的电子邮件地址。
  • 用户凭据:使用您自己的凭据运行扫描。

REST

如需使用自定义服务账号,请在 create 请求期间将 executionIdentity 对象添加到 DataScan 资源定义中:

"executionIdentity": {
  "serviceAccount": {
     "email": "YOUR_SERVICE_ACCOUNT_EMAIL"
  }
}
  

替换以下内容:

  • YOUR_SERVICE_ACCOUNT_EMAIL:您要使用的服务账号的电子邮件地址。

如需使用最终用户凭据,请改用 userCredential 对象:

"executionIdentity": {
  "userCredential": {}
}
  

创建数据质量扫描

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击创建数据质量扫描

  3. 定义扫描窗口中,填写以下字段:

    1. 可选:输入显示名称

    2. 输入 ID。请参阅资源命名惯例

    3. (可选)输入说明

    4. 字段中,点击浏览。选择要扫描的表,然后点击选择。仅支持标准 BigQuery、Iceberg REST Catalog、SAP BDC Delta 和 Hive on Google CloudLakehouse 表。

      对于多区域数据集中的表,请选择要在其中创建数据扫描的区域。

      如需浏览在 Knowledge Catalog 数据湖中整理的表,请点击在 Knowledge Catalog 数据湖中浏览

    5. 范围字段中,选择增量所有数据

      • 如果您选择增量:在时间戳列字段中,从 BigQuery 表中选择类型为 DATETIMESTAMP 且可随新记录的添加而递增的列,该列可用于识别新记录。它可以是用于对表进行分区的列。
    6. 可选:如需过滤数据,请选中过滤行复选框。提供一个行过滤条件,该过滤条件包含一个有效的 SQL 表达式,该表达式可用于 GoogleSQL 语法中的 WHERE 子句。例如 col1 >= 0。过滤条件可以是多个列条件的组合。例如 col1 >= 0 AND col2 < 10

    7. 如需对数据进行采样,请在采样规模列表中选择采样百分比。选择一个范围介于 0.0% 到 100.0% 之间的百分比值,最多精确到小数点后 3 位。对于较大的数据集,请选择一个较低的采样百分比。例如,对于一个 1 PB 的表,如果您输入的值介于 0.1% 到 1.0% 之间,则数据质量扫描会采样 1-10 TB 的数据。对于增量数据扫描,数据质量扫描会对最新增量应用采样。

    8. 可选:如需将数据质量扫描结果作为 Knowledge Catalog 元数据发布,请选中将结果发布到 Knowledge Catalog 复选框。

      您可以在源表的 BigQuery 和 Knowledge Catalog 页面中的数据质量标签页上查看最新扫描结果。如需使用户能够访问已发布的扫描结果,请参阅本文档的授予对数据质量扫描结果的访问权限部分。

    9. 如需了解凭据类型,请参阅配置执行身份

    10. 如需使用规则创建数据质量扫描,请依次选择“规则类型”图标 >“使用基于条目的规则创建”

    11. 时间表部分中,选择以下选项之一:

      • 重复:按时间表(每小时、每天、每周、每月或自定义)运行数据质量扫描。指定扫描的运行频率和时间。如果您选择自定义,请使用 cron 格式指定时间表。

      • 按需:按需运行数据质量扫描。

      • 一次性运行:立即运行一次数据质量扫描,并在自动删除时间过后移除该扫描。此功能处于预览阶段。

        • 设置扫描后结果自动删除:自动删除时间是指从执行扫描到删除扫描之间的时间跨度。未指定自动删除时间的数据质量扫描会在执行 24 小时后自动删除。自动删除时间可以介于 0 秒(立即删除)到 365 天之间。
    12. 点击继续

  4. 数据质量规则窗口中,定义要为此数据质量扫描配置的规则。

    1. 点击添加规则,然后从以下选项中进行选择。

      • 基于数据分析的建议:根据现有数据分析扫描,基于建议构建规则。

        1. 选择列:选择要获取其建议规则的列。

        2. 选择扫描项目:如果数据分析扫描与您要创建数据质量扫描的项目不在同一项目中,请选择要从中拉取数据分析扫描的项目。

        3. 选择分析结果:选择一个或多个分析结果,然后点击确定。系统会填充一个建议规则列表,您可以从这些规则入手。

        4. 选中要添加的规则对应的复选框,然后点击选择。选择后,这些规则会添加到当前的规则列表中。然后,您可以修改规则。

      • 内置规则类型:根据预定义规则构建规则。请参阅预定义规则列表。

        1. 选择列:选择要为其选择规则的列。

        2. 选择规则类型:选择要从中选择的规则类型,然后点击确定。显示的规则类型取决于您选择的列。

        3. 选中要添加的规则对应的复选框,然后点击选择。选择后,这些规则会添加到当前的规则列表中。然后,您可以修改规则。

      • SQL 行检查规则:创建要应用于每行的自定义 SQL 规则。

        1. 维度中,选择一个维度。

        2. 通过阈值中,选择必须通过检查的记录所占的百分比。

        3. 列名称中,选择一列。

        4. 提供 SQL 表达式字段中,输入一个计算结果为布尔值 true(通过)或 false(未通过)的 SQL 表达式。如需了解详情,请参阅支持的自定义 SQL 规则类型以及定义数据质量规则中的示例。

        5. 点击添加

      • SQL 聚合检查规则:创建自定义 SQL 表条件规则。

        1. 维度中,选择一个维度。

        2. 列名称中,选择一列。

        3. 提供 SQL 表达式字段中,输入一个计算结果为布尔值 true(通过)或 false(未通过)的 SQL 表达式。如需了解详情,请参阅支持的自定义 SQL 规则类型以及定义数据质量规则中的示例。

        4. 点击添加

      • SQL 断言规则:创建自定义 SQL 断言规则,以检查数据的无效状态。

        1. 维度中,选择一个维度。

        2. 可选:在列名称中,选择一列。

        3. 提供 SQL 语句字段中,输入一个 SQL 语句,以返回与无效状态匹配的行。如果系统返回了任何行,表示此规则失败。从 SQL 语句中省略末尾的英文分号。如需了解详情,请参阅支持的自定义 SQL 规则类型以及定义数据质量规则中的示例。

        4. 点击添加

    2. 可选:对于任何数据质量规则,您都可以分配一个自定义规则名称以用于监控和提醒,还可以添加说明。为此,请修改规则并指定以下详细信息:

      • 规则名称:输入自定义规则名称,最多 63 个字符。规则名称可以包含字母(a-z、A-Z)、数字 (0-9) 和连字符 (-),且必须以字母开头,以数字或字母结尾。
      • 说明:输入规则说明,长度上限为 1,024 个字符。
    3. 重复上述步骤,向数据质量扫描添加其他规则。完成后,点击继续

  5. 可选:将扫描结果导出到 BigQuery 标准表。在将扫描结果导出到 BigQuery 表部分中,执行以下操作:

    1. 选择 BigQuery 数据集字段中,点击浏览。选择一个 BigQuery 数据集来存储数据质量扫描结果。

    2. BigQuery 表字段中,指定用于存储数据质量扫描结果的表。如果您使用的是现有表,请确保该表与导出表架构兼容。如果指定的表不存在,Knowledge Catalog 会为您创建该表。

  6. 可选:添加标签。标签是键值对,可用于将相关对象组合在一起或者与其他 Google Cloud 资源组合在一起。

  7. 可选:设置邮件通知报告,以提醒相关人员数据质量扫描作业的状态和结果。在通知报告部分,点击 添加邮件 ID,然后输入最多五个邮箱。然后,选择要针对其发送报告的场景:

    • 质量得分 (<=):当作业成功完成但数据质量得分低于指定的目标得分时发送报告。输入介于 0 到 100 之间的目标质量得分。
    • 作业失败:当作业本身失败时发送报告,无论数据质量结果如何。
    • 作业完成(成功或失败):当作业结束时发送报告,无论数据质量结果如何。
  8. 点击创建

    创建扫描后,您可以随时点击立即运行来运行扫描。

gcloud

如需创建数据质量扫描,请使用 gcloud dataplex datascans create data-quality 命令

如果源数据在 Knowledge Catalog 数据湖中整理,请添加 --data-source-entity 标志:

gcloud dataplex datascans create data-quality DATASCAN \
    --location=LOCATION \
    --data-quality-spec-file=DATA_QUALITY_SPEC_FILE \
    --data-source-entity=DATA_SOURCE_ENTITY

如果源数据未在 Knowledge Catalog 数据湖中整理,请添加 --data-source-resource 标志:

gcloud dataplex datascans create data-quality DATASCAN \
    --location=LOCATION \
    --data-quality-spec-file=DATA_QUALITY_SPEC_FILE \
    --data-source-resource=DATA_SOURCE_RESOURCE

执行以下变量替换操作:

  • DATASCAN:数据质量扫描的名称。
  • LOCATION:要在其中创建数据质量扫描的 Google Cloud 区域。
  • DATA_QUALITY_SPEC_FILE:包含数据质量扫描规范的 JSON 或 YAML 文件的路径。该文件可以是本地文件,也可以是带有前缀 gs:// 的 Cloud Storage 路径。使用此文件可为扫描指定数据质量规则。您还可以在此文件中指定其他详细信息,例如过滤条件、采样百分比和扫描后操作(例如导出到 BigQuery 或发送邮件通知报告)。请参阅 JSON 表示法文档YAML 表示法示例
  • DATA_SOURCE_ENTITY:包含数据质量扫描所用数据的 Knowledge Catalog 实体。例如 projects/test-project/locations/test-location/lakes/test-lake/zones/test-zone/entities/test-entity
  • DATA_SOURCE_RESOURCE:包含数据质量扫描所用数据的资源的名称。例如 //bigquery.googleapis.com/projects/test-project/datasets/test-dataset/tables/test-table

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dataplex.V1;
using Google.LongRunning;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for CreateDataScan</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void CreateDataScanRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        CreateDataScanRequest request = new CreateDataScanRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
            DataScan = new DataScan(),
            DataScanId = "",
            ValidateOnly = false,
        };
        // Make the request
        Operation<DataScan, OperationMetadata> response = dataScanServiceClient.CreateDataScan(request);

        // Poll until the returned long-running operation is complete
        Operation<DataScan, OperationMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        DataScan result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<DataScan, OperationMetadata> retrievedResponse = dataScanServiceClient.PollOnceCreateDataScan(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            DataScan retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.CreateDataScanRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#CreateDataScanRequest.
	}
	op, err := c.CreateDataScan(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.CreateDataScanRequest;
import com.google.cloud.dataplex.v1.DataScan;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.LocationName;

public class SyncCreateDataScan {

  public static void main(String[] args) throws Exception {
    syncCreateDataScan();
  }

  public static void syncCreateDataScan() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      CreateDataScanRequest request =
          CreateDataScanRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setDataScan(DataScan.newBuilder().build())
              .setDataScanId("dataScanId1260787906")
              .setValidateOnly(true)
              .build();
      DataScan response = dataScanServiceClient.createDataScanAsync(request).get();
    }
  }
}

Node.js

Node.js

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Node.js API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **



'use strict';

function main(parent, dataScan) {
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The resource name of the parent location:
   *  `projects/{project}/locations/{location_id}`
   *  where `project` refers to a *project_id* or *project_number* and
   *  `location_id` refers to a Google Cloud region.
   */
  // const parent = 'abc123'
  /**
   *  Required. DataScan resource.
   */
  // const dataScan = {}
  /**
   *  Optional. DataScan identifier. If not provided, a unique ID will be
   *  generated with the prefix "data-scan-".
   *  * Must contain only lowercase letters, numbers and hyphens.
   *  * Must start with a letter.
   *  * Must end with a number or a letter.
   *  * Must be between 1-63 characters.
   *  * Must be unique within the customer project / location.
   */
  // const dataScanId = 'abc123'
  /**
   *  Optional. Only validate the request, but do not perform mutations.
   *  The default is `false`.
   */
  // const validateOnly = true

  // Imports the Dataplex library
  const {DataScanServiceClient} = require('@google-cloud/dataplex').v1;

  // Instantiates a client
  const dataplexClient = new DataScanServiceClient();

  async function callCreateDataScan() {
    // Construct request
    const request = {
      parent,
      dataScan,
    };

    // Run request
    const [operation] = await dataplexClient.createDataScan(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callCreateDataScan();
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import google.api_core.exceptions
from google.cloud import dataplex_v1


def create_data_quality_scan_global(
    project_id: str,
    dataset_id: str,
    table_id: str,
    location: str,
    column_id_1: str,
    column_id_2: str,
) -> None:
    """Creates a Dataplex Data Quality Scan using global API endpoint routing.

    Args:
        project_id (str): Google Cloud project ID where the scan is created.
        dataset_id (str): Target BigQuery dataset ID.
        table_id (str): Target BigQuery table ID to scan.
        location (str): Google Cloud region where serverless compute runs.
        column_id_1 (str): Name of the first column to evaluate.
        column_id_2 (str): Name of the second column to evaluate.
    """
    client = dataplex_v1.DataScanServiceClient()

    parent = client.common_location_path(project=project_id, location=location)

    # A bigquery table with at least 2 columns is assumed.
    bigquery_table = (
        f"//bigquery.googleapis.com/projects/{project_id}"
        f"/datasets/{dataset_id}/tables/{table_id}"
    )

    data_quality_spec = dataplex_v1.DataQualitySpec(
        rules=[
            dataplex_v1.DataQualityRule(
                name="global-null-assertion",
                dimension="COMPLETENESS",
                description="Fails if any row contains a null value",
                sql_assertion=dataplex_v1.DataQualityRule.SqlAssertion(
                    # Use ${data()} as the placeholder for the table Dataplex is scanning
                    sql_statement=(
                        "SELECT * FROM ${data()} "
                        f"WHERE {column_id_1} IS NULL OR {column_id_2} IS NULL"
                    )
                ),
            )
        ]
    )

    data_scan = dataplex_v1.DataScan(
        display_name="Global Data Quality Scan",
        data=dataplex_v1.DataSource(resource=bigquery_table),
        data_quality_spec=data_quality_spec,
    )

    request = dataplex_v1.CreateDataScanRequest(parent=parent, data_scan=data_scan)

    try:
        operation = client.create_data_scan(request=request)
        print(operation.result())
    except google.api_core.exceptions.AlreadyExists:
        print("A scan with this ID already exists.")
    except google.api_core.exceptions.InvalidArgument as e:
        print(f"Your scan configuration is invalid: {e}")
    except google.api_core.exceptions.GoogleAPIError as e:
        print(f"Unexpected exception: {e}")

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the create_data_scan call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#create_data_scan.
#
def create_data_scan
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::CreateDataScanRequest.new

  # Call the create_data_scan method.
  result = client.create_data_scan request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

REST

如需创建数据质量扫描,请使用 dataScans.create 方法

以下请求会创建一次性数据质量扫描:

POST https://dataplex.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/dataScans?data_scan_id=DATASCAN_ID

{
"data": {
  "resource": "//bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID"
},
"type": "DATA_QUALITY",
"executionSpec": {
  "trigger": {
    "oneTime": {
      "ttl_after_scan_completion": "120s"
    }
  }
},
"dataQualitySpec": {
  "rules": [
    {
      "nonNullExpectation": {},
      "column": "COLUMN_NAME",
      "dimension": "DIMENSION",
      "threshold": 1
    }
  ],
  "filter": "FILTER_CONDITION"
}
}

替换以下内容:

  • PROJECT_ID:您的项目 ID。
  • LOCATION:要在其中创建数据质量扫描的区域。
  • DATASCAN_ID:数据质量扫描的 ID。
  • DATASET_ID:BigQuery 数据集的 ID。
  • TABLE_ID:BigQuery 表的 ID。
  • COLUMN_NAME:规则的列名称。
  • DIMENSION:规则的维度,例如 VALIDITY
  • FILTER_CONDITION:一个可选的 AIP-160 过滤字符串,用于选择性地运行规则(例如,name = \"RULE_NAME\")。

如果您想使用基于数据分析扫描结果的规则建议来构建数据质量扫描的规则,请通过对数据分析扫描调用 dataScans.jobs.generateDataQualityRules 方法来获取建议。

导出表架构

如需将数据质量扫描结果导出到现有 BigQuery 表,请确保该表与以下表架构兼容:

列名 列数据类型 子字段名称
(如果适用)
子字段数据类型 模式 示例
data_quality_scan struct/record resource_name string nullable //dataplex.googleapis.com/projects/test-project/locations/europe-west2/datascans/test-datascan
project_id string nullable dataplex-back-end-dev-project
location string nullable us-central1
data_scan_id string nullable test-datascan
display_name string nullable datascan-display-name
data_source struct/record resource_name string nullable 实体大小写:
//dataplex.googleapis.com/projects/dataplex-back-end-dev-project/locations/europe-west2/lakes/a0-datascan-test-lake/zones/a0-datascan-test-zone/entities/table1

表大小写: //bigquery.googleapis.com/projects/test-project/datasets/test-dataset/tables/test-table
dataplex_entity_project_id string nullable dataplex-back-end-dev-project
dataplex_entity_project_number integer nullable 123456789
dataplex_lake_id string nullable (仅在来源为实体时有效)
test-lake
dataplex_zone_id string nullable (仅在来源为实体时有效)
test-zone
dataplex_entity_id string nullable (仅在来源为实体时有效)
test-entity
table_project_id string nullable test-project
table_project_number integer nullable 987654321
dataset_id string nullable (仅在来源为表时有效)
test-dataset
table_id string nullable (仅在来源为表时有效)
test-table
data_quality_job_id string nullable caeba234-cfde-4fca-9e5b-fe02a9812e38
data_quality_job_configuration json nullable {"trigger": "ondemand", "incremental": true}
job_labels json nullable {"key1":value1}
job_start_time timestamp nullable 2023-01-01 00:00:00 UTC
job_end_time timestamp nullable 2023-01-01 00:00:00 UTC
job_quality_result struct/record passed boolean nullable true/false
score float nullable 90.8
incremental_start string nullable 2023-01-01T00:00:00
incremental_end string nullable 2024-01-01T00:00:00
job_dimension_result json nullable {"ACCURACY":{"passed":true,"score":100},"CONSISTENCY":{"passed":false,"score":60}}
job_rows_scanned integer nullable 7500
rule_name string nullable test-rule
rule_description string nullable Test rule description
rule_type string nullable Range Check
rule_evaluation_type string nullable Per row
rule_column string nullable Rule only attached to a certain column
rule_dimension string nullable UNIQUENESS
rule_threshold_percent float nullable (0.0-100.0)
Rule-threshold-pct in API * 100
rule_parameters json nullable {min: 24, max:5345}
rule_passed boolean nullable true
rule_rows_evaluated integer nullable 7400
rule_rows_passed integer nullable 3
rule_rows_passed_percent float nullable (0.0-100.0)
80.0(表示 80%)
rule_rows_null integer nullable 4
rule_failed_records_query string nullable "SELECT * FROM `test-project.test-dataset.test-table` WHERE (NOT((`cTime` >= '15:31:38.776361' and `cTime` <= '19:23:53.754823') IS TRUE));"
created_on timestamp nullable 2023-01-01 00:00:00 UTC
last_updated timestamp nullable 2023-01-01 00:00:00 UTC
rule_assertion_row_count integer nullable 10
debug_queries struct/record description string nullable Test debug query description
sql_statement string nullable SELECT MIN(col1) AS min_col1, AVG(col1) FROM ${data()}
debug_query_results struct/record repeated [{"name": "min_col1", "type": "INTEGER", "value": "5"}, {"type": "FLOAT", "value": "7"}]
name string nullable 查询结果列的名称,例如 min_col1
type string nullable 查询结果列的类型,例如 INTEGER
value string nullable 查询结果列的值,例如 5
rule_attributes json nullable {"key": "value"}
rule_source struct/record rule_path_elements struct/record repeated [{"entry_source": {"entry_type": "bigquery_table"}}]
entry_source struct/record nullable {"entry_type": "bigquery_table"}
  ↳ entry_type string nullable bigquery_table
  ↳ entry string nullable projects/test-project/locations/us/entryGroups/@bigquery/entries/test-table
  ↳ display_name string nullable test-table
entry_link_source struct/record nullable {"entry_link_type": "table_spec"}
  ↳ entry_link_type string nullable table_spec
  ↳ entry_link string nullable projects/test-project/locations/us/entryLinks/test-link

为数据质量扫描作业配置 BigQueryExport 时,请遵循以下准则:

  • 对于字段 resultsTable,请使用以下格式://bigquery.googleapis.com/projects/{project-id}/datasets/{dataset-id}/tables/{table-id}
  • 使用 BigQuery 标准表。
  • 如果在创建或更新扫描时该表不存在,Knowledge Catalog 会为您创建该表。
  • 默认情况下,该表按 job_start_time 列每天进行分区。
  • 如果您希望以其他配置对表进行分区,或者不希望进行分区,请使用所需的架构和配置重新创建表,然后将预先创建的表作为结果表提供。
  • 请确保结果表与源表位于同一位置。
  • 如果为项目配置了 VPC-SC,则结果表必须与源表位于同一 VPC-SC 边界内。
  • 如果在扫描执行阶段修改了表,则当前正在运行的作业会导出到之前的结果表,并且表更改会从下一个扫描作业开始生效。
  • 请勿修改表架构。如果您需要自定义列,请基于表创建视图。
  • 为了降低费用,请根据您的应用场景为分区设置失效时间。如需了解详情,请参阅如何设置分区失效时间

运行数据质量扫描

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击要运行的数据质量扫描。

  3. 点击立即运行

gcloud

如需运行数据质量扫描,请使用 gcloud dataplex datascans run 命令

gcloud dataplex datascans run DATASCAN \
--location=LOCATION \

执行以下变量替换操作:

  • LOCATION:在其中创建数据质量扫描的 Google Cloud 区域。
  • DATASCAN:数据质量扫描的名称。

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Dataplex.V1;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for RunDataScan</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void RunDataScanRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        RunDataScanRequest request = new RunDataScanRequest
        {
            DataScanName = DataScanName.FromProjectLocationDataScan("[PROJECT]", "[LOCATION]", "[DATASCAN]"),
        };
        // Make the request
        RunDataScanResponse response = dataScanServiceClient.RunDataScan(request);
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.RunDataScanRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#RunDataScanRequest.
	}
	resp, err := c.RunDataScan(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.DataScanName;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.RunDataScanRequest;
import com.google.cloud.dataplex.v1.RunDataScanResponse;

public class SyncRunDataScan {

  public static void main(String[] args) throws Exception {
    syncRunDataScan();
  }

  public static void syncRunDataScan() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      RunDataScanRequest request =
          RunDataScanRequest.newBuilder()
              .setName(DataScanName.of("[PROJECT]", "[LOCATION]", "[DATASCAN]").toString())
              .build();
      RunDataScanResponse response = dataScanServiceClient.runDataScan(request);
    }
  }
}

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_run_data_scan():
    # Create a client
    client = dataplex_v1.DataScanServiceClient()

    # Initialize request argument(s)
    request = dataplex_v1.RunDataScanRequest(
        name="name_value",
    )

    # Make the request
    response = client.run_data_scan(request=request)

    # Handle the response
    print(response)

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the run_data_scan call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#run_data_scan.
#
def run_data_scan
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::RunDataScanRequest.new

  # Call the run_data_scan method.
  result = client.run_data_scan request

  # The returned object is of type Google::Cloud::Dataplex::V1::RunDataScanResponse.
  p result
end

REST

如需运行数据质量扫描,请使用 dataScans.run 方法

Airflow

如需在 Managed Service for Apache Airflow (Cloud Composer) 中使用有向无环图 (DAG) 运行数据质量扫描,请使用 DataplexRunDataQualityScanOperator

from datetime import datetime
from airflow import DAG
from airflow.providers.google.cloud.operators.dataplex import DataplexRunDataQualityScanOperator

with DAG(
  "dataplex_auto_dq_scan",
  start_date=datetime(2026, 1, 1),
  schedule_interval="@daily",
  catchup=False,
) as dag:

  run_dq_scan = DataplexRunDataQualityScanOperator(
      task_id="run_dataplex_dq_scan",
      project_id="PROJECT_ID",
      region="REGION",
      data_scan_id="DATASCAN_ID",
  )

替换以下内容:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • REGION:在其中创建数据质量扫描的 Google Cloud 区域。
  • DATASCAN_ID:数据质量扫描的 ID。

取消数据质量扫描作业

如果数据质量扫描作业的运行时间超出预期,或者启动时配置不正确,您可以取消该作业。这是一项尽力而为的操作。如果作业已处于终止状态(例如 SUCCEEDEDFAILED),则系统会忽略取消请求。

所需的角色和权限

如需获得取消数据质量扫描作业所需的权限,请让您的管理员为您授予项目的 Dataplex Editor (roles/dataplex.editor) 或 Dataplex DataScan Administrator (roles/dataplex.dataScanAdmin) IAM 角色。

取消作业

您可以使用 REST API 取消正在运行或待处理的数据质量扫描作业。

控制台

  1. 在 Google Cloud 控制台中,前往数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击包含要取消的作业的数据质量扫描的名称。

  3. 作业历史记录标签页中,找到状态为正在运行待处理的作业。

  4. 点击与相应作业关联的取消

REST

使用 projects.locations.dataScans.jobs.cancel 方法。

POST https://dataplex.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/dataScans/DATASCAN_ID/jobs/JOB_ID:cancel

替换以下内容:

  • PROJECT_ID:项目 ID。
  • LOCATION:数据扫描所在的区域。
  • DATASCAN_ID:数据扫描的 ID。
  • JOB_ID:要取消的作业的 ID。

查看数据质量扫描结果

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击数据质量扫描的名称。

    • 概览部分显示有关最近作业的信息,包括扫描运行时间、每个作业中扫描的记录数、是否通过了所有数据质量检查,以及失败的数据质量检查数量(如果存在失败情况)。

    • 数据质量扫描配置部分显示有关扫描的详细信息。

  3. 如需查看作业的详细信息(例如指示通过的规则百分比的数据质量得分、失败的规则以及作业日志),请点击作业历史记录标签页。然后,点击作业 ID。

gcloud

如需查看数据质量扫描作业的结果,请使用 gcloud dataplex datascans jobs describe 命令

gcloud dataplex datascans jobs describe JOB \
--location=LOCATION \
--datascan=DATASCAN \
--view=FULL

执行以下变量替换操作:

  • JOB:数据质量扫描作业的作业 ID。
  • LOCATION:在其中创建数据质量扫描的 Google Cloud 区域。
  • DATASCAN:作业所属的数据质量扫描的名称。
  • --view=FULL:如需查看扫描作业结果,请指定 FULL

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Dataplex.V1;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for GetDataScan</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void GetDataScanRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        GetDataScanRequest request = new GetDataScanRequest
        {
            DataScanName = DataScanName.FromProjectLocationDataScan("[PROJECT]", "[LOCATION]", "[DATASCAN]"),
            View = GetDataScanRequest.Types.DataScanView.Unspecified,
        };
        // Make the request
        DataScan response = dataScanServiceClient.GetDataScan(request);
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.GetDataScanRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#GetDataScanRequest.
	}
	resp, err := c.GetDataScan(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.DataScan;
import com.google.cloud.dataplex.v1.DataScanName;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.GetDataScanRequest;

public class SyncGetDataScan {

  public static void main(String[] args) throws Exception {
    syncGetDataScan();
  }

  public static void syncGetDataScan() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      GetDataScanRequest request =
          GetDataScanRequest.newBuilder()
              .setName(DataScanName.of("[PROJECT]", "[LOCATION]", "[DATASCAN]").toString())
              .build();
      DataScan response = dataScanServiceClient.getDataScan(request);
    }
  }
}

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_get_data_scan():
    # Create a client
    client = dataplex_v1.DataScanServiceClient()

    # Initialize request argument(s)
    request = dataplex_v1.GetDataScanRequest(
        name="name_value",
    )

    # Make the request
    response = client.get_data_scan(request=request)

    # Handle the response
    print(response)

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the get_data_scan call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#get_data_scan.
#
def get_data_scan
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::GetDataScanRequest.new

  # Call the get_data_scan method.
  result = client.get_data_scan request

  # The returned object is of type Google::Cloud::Dataplex::V1::DataScan.
  p result
end

REST

如需查看数据质量扫描的结果,请使用 dataScans.get 方法

查看已发布的结果

如果数据质量扫描结果作为 Knowledge Catalog 元数据发布,则您可以在Google Cloud 控制台的 BigQuery 和 Knowledge Catalog 页面中源表的数据质量标签页上查看最新扫描结果。

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 搜索页面。

    转到搜索

  2. 搜索并选择表格。

  3. 点击数据质量标签页。

    系统会显示最新发布的结果。

查看历史扫描结果

Knowledge Catalog 会保存最近 300 个作业或过去一年(以先到者为准)的数据质量扫描历史记录。

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击数据质量扫描的名称。

  3. 点击作业历史记录标签页。

    作业历史记录标签页提供有关过去作业的信息,例如每个作业中扫描的记录数、作业状态、作业运行时间以及每个规则是通过还是未通过。

  4. 如需查看有关作业的详细信息,请点击作业 ID 列中的任何作业。

gcloud

如需查看历史数据质量扫描作业,请使用 gcloud dataplex datascans jobs list 命令

gcloud dataplex datascans jobs list \
--location=LOCATION \
--datascan=DATASCAN \

执行以下变量替换操作:

  • LOCATION:在其中创建数据质量扫描的 Google Cloud 区域。
  • DATASCAN:要查看其历史作业的数据质量扫描的名称。

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Api.Gax;
using Google.Cloud.Dataplex.V1;
using System;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for ListDataScanJobs</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void ListDataScanJobsRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        ListDataScanJobsRequest request = new ListDataScanJobsRequest
        {
            ParentAsDataScanName = DataScanName.FromProjectLocationDataScan("[PROJECT]", "[LOCATION]", "[DATASCAN]"),
            Filter = "",
        };
        // Make the request
        PagedEnumerable<ListDataScanJobsResponse, DataScanJob> response = dataScanServiceClient.ListDataScanJobs(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (DataScanJob item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (ListDataScanJobsResponse page in response.AsRawResponses())
        {
            // Do something with each page of items
            Console.WriteLine("A page of results:");
            foreach (DataScanJob item in page)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<DataScanJob> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
        foreach (DataScanJob item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.ListDataScanJobsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#ListDataScanJobsRequest.
	}
	it := c.ListDataScanJobs(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp

		// If you need to access the underlying RPC response,
		// you can do so by casting the `Response` as below.
		// Otherwise, remove this line. Only populated after
		// first call to Next(). Not safe for concurrent access.
		_ = it.Response.(*dataplexpb.ListDataScanJobsResponse)
	}
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.DataScanJob;
import com.google.cloud.dataplex.v1.DataScanName;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.ListDataScanJobsRequest;

public class SyncListDataScanJobs {

  public static void main(String[] args) throws Exception {
    syncListDataScanJobs();
  }

  public static void syncListDataScanJobs() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      ListDataScanJobsRequest request =
          ListDataScanJobsRequest.newBuilder()
              .setParent(DataScanName.of("[PROJECT]", "[LOCATION]", "[DATASCAN]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .setFilter("filter-1274492040")
              .build();
      for (DataScanJob element : dataScanServiceClient.listDataScanJobs(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_list_data_scan_jobs():
    # Create a client
    client = dataplex_v1.DataScanServiceClient()

    # Initialize request argument(s)
    request = dataplex_v1.ListDataScanJobsRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_data_scan_jobs(request=request)

    # Handle the response
    for response in page_result:
        print(response)

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the list_data_scan_jobs call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#list_data_scan_jobs.
#
def list_data_scan_jobs
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::ListDataScanJobsRequest.new

  # Call the list_data_scan_jobs method.
  result = client.list_data_scan_jobs request

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Cloud::Dataplex::V1::DataScanJob.
    p item
  end
end

REST

如需查看历史数据质量扫描作业,请使用 dataScans.jobs.list 方法

作业状态

数据扫描作业可能具有以下状态:

  • PENDING:作业已创建,但尚未开始运行。在此状态下,扫描会主动设置基础设施或获取 slot。此阶段可能需要 10 到 20 秒或更长时间,具体取决于架构复杂性和资源争用情况。

  • RUNNING:作业正在运行。

  • CANCELING:作业正在取消。

  • CANCELLED:作业已成功取消。

  • SUCCEEDED:作业成功完成。由于存在后期处理步骤(例如聚合和元数据同步),完成状态可能会比实际查询完成时间晚最多 60 秒。

  • FAILED:作业因错误而失败。由于存在后期处理步骤(例如聚合和元数据同步),完成状态可能会比实际查询完成时间晚最多 60 秒。

  • SUCCEEDED_WITH_ERRORS:作业成功完成,但在执行期间出现了一些错误。

监控最佳实践

在监控数据扫描作业时,请牢记以下最佳实践:

  • 避免频繁轮询:避免频繁轮询(例如,每 1 到 5 秒调用一次 GetJob 或等效函数)。频繁轮询会浪费 API 配额,并且不会加快状态转换。

  • 使用指数退避算法:如果无法避免重复轮询,请使用指数退避算法,从 10 到 15 秒开始。

  • 使用异步事件驱动型解耦(推荐):使用侦听 Cloud Audit Logs (cloudaudit.googleapis.com) 的 Eventarc 触发器,而不是同步 API 轮询。您可以使用这些触发器在 DataScan 作业完成事件发生后立即启动下游工作流。这种方法可绕过 API 轮询限制,节省配额并缩短感知延迟时间。

授予对数据质量扫描结果的访问权限

如需让贵组织中的用户查看扫描结果,请执行以下操作:

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击您要共享其结果的数据质量扫描。

  3. 点击权限标签页。

  4. 执行以下操作:

    • 如需向主账号授予访问权限,请点击 授予访问权限。向关联的主账号授予 Dataplex DataScan DataViewer 角色。
    • 如需移除主账号的访问权限,请选择要从中移除 Dataplex DataScan DataViewer 角色的主账号。点击 移除访问权限,然后在系统提示时进行确认。

在 Logging 中设置提醒

如需使用 Cloud Logging 中的日志针对数据质量失败设置提醒,请按照以下步骤操作:

控制台

  1. 在 Google Cloud 控制台中,前往 Logging Logs Explorer

    转到日志浏览器

  2. 查询窗口中,输入您的查询。请参阅示例查询

  3. 点击运行查询

  4. 点击创建提醒。 系统会打开一个侧边栏。

  5. 输入提醒政策名称,然后点击下一步

  6. 查看查询。

    1. 点击预览日志以测试查询。此视图会显示符合条件的日志。

    2. 点击下一步

  7. 设置通知间隔时间,然后点击下一步

  8. 定义应向哪些人发送提醒通知,然后点击保存以创建提醒政策。

或者,您也可以在Google Cloud 控制台中前往 Monitoring > 提醒,以配置和修改提醒。

gcloud

不受支持。

REST

了解如何在 Logging 中设置提醒

用于设置作业级或维度级提醒的示例查询

  • 用于针对数据质量扫描的总体数据质量失败设置提醒的示例查询:

    resource.type="dataplex.googleapis.com/DataScan"
    AND labels."dataplex.googleapis.com/data_scan_state"="SUCCEEDED"
    AND resource.labels.resource_container="projects/112233445566"
    AND resource.labels.datascan_id="a0-test-dec6-dq-3"
    AND NOT jsonPayload.dataQuality.passed=true
    
  • 用于针对给定数据质量扫描维度(例如唯一性)的数据质量失败设置提醒的示例查询:

    resource.type="dataplex.googleapis.com/DataScan"
    AND labels."dataplex.googleapis.com/data_scan_state"="SUCCEEDED"
    AND resource.labels.resource_container="projects/112233445566"
    AND resource.labels.datascan_id="a0-test-dec6-dq-3"
    AND jsonPayload.dataQuality.dimensionPassed.UNIQUENESS=false
    
  • 用于针对表的数据质量失败设置提醒的示例查询。

    • 针对未在 Knowledge Catalog 数据湖中整理的 BigQuery 表的数据质量失败设置提醒:

      resource.type="dataplex.googleapis.com/DataScan"
      AND jsonPayload.dataSource="//bigquery.googleapis.com/projects/test-project/datasets/testdataset/table/chicago_taxi_trips"
      AND labels."dataplex.googleapis.com/data_scan_state"="SUCCEEDED"
      AND resource.labels.resource_container="projects/112233445566"
      AND NOT jsonPayload.dataQuality.passed=true
      
    • 针对在 Knowledge Catalog 数据湖中整理的 BigQuery 表的数据质量失败设置提醒:

      resource.type="dataplex.googleapis.com/DataScan"
      AND jsonPayload.dataSource="projects/test-project/datasets/testdataset/table/chicago_taxi_trips"
      AND labels."dataplex.googleapis.com/data_scan_state"="SUCCEEDED"
      AND resource.labels.resource_container="projects/112233445566"
      AND NOT jsonPayload.dataQuality.passed=true
      

用于针对规则设置提醒的示例查询

  • 用于针对数据质量扫描中所有失败的数据质量规则(具有指定自定义规则名称)设置提醒的示例查询:

    resource.type="dataplex.googleapis.com/DataScan"
    AND jsonPayload.ruleName="custom-name"
    AND jsonPayload.result="FAILED"
    
  • 用于针对数据质量扫描中特定评估类型的所有失败数据质量规则设置提醒的示例查询:

    resource.type="dataplex.googleapis.com/DataScan"
    AND jsonPayload.evalutionType="PER_ROW"
    AND jsonPayload.result="FAILED"
    
  • 用于针对数据质量扫描所用表中列的所有失败数据质量规则设置提醒的示例查询:

    resource.type="dataplex.googleapis.com/DataScan"
    AND jsonPayload.column="CInteger"
    AND jsonPayload.result="FAILED"
    

排查数据质量失败问题

对于每个包含失败的行级规则的作业,Knowledge Catalog 都会提供一个查询来获取失败的记录。运行此查询可查看与您的规则不匹配的记录。

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击要排查其记录问题的数据质量扫描的名称。

  3. 点击作业历史记录标签页。

  4. 点击确定数据质量失败的作业的 ID。

  5. 在随即打开的作业结果窗口的规则部分中,找到查询以获取失败的记录列。点击失败规则对应的将查询复制到剪贴板

  6. 在 BigQuery 中运行查询,以查看导致作业失败的记录。

gcloud

不受支持。

REST

  1. 如需获取确定数据质量失败的作业,请使用 dataScans.get 方法

    在响应对象中,failingRowsQuery 字段显示查询。

  2. 在 BigQuery 中运行查询,以查看导致作业失败的记录。

Knowledge Catalog 还会运行调试查询(如果在创建规则时包含该查询)。调试查询结果包含在每个规则的输出中。此功能处于预览版阶段。

控制台

不受支持。

gcloud

不受支持。

REST

如需获取确定数据质量失败的作业,请使用 dataScans.get 方法。在响应对象中,debugQueriesResultSets 字段显示调试查询的结果。

管理特定表的数据质量扫描

本文档中的步骤介绍了如何使用 Google Cloud 控制台中的 Knowledge Catalog 数据分析和质量评估页面来管理项目中的数据分析扫描。

您还可以在使用特定表时创建和管理数据分析扫描。在 Google Cloud 控制台中,在相应表的 Knowledge Catalog 页面上,使用数据质量标签页。执行以下操作:

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 搜索页面。

    转到搜索

    搜索并选择表格。

  2. 点击数据质量标签页。

  3. 根据表是否具有已将结果发布为 Knowledge Catalog 元数据的数据质量扫描,您可以通过以下方式处理表的数据质量扫描:

    • 数据质量扫描结果已发布:页面上会显示最新的扫描结果。

      如需管理此表的数据质量扫描,请点击数据质量扫描,然后从以下选项中进行选择:

      • 创建新扫描:创建新的数据质量扫描。如需了解详情,请参阅本文档中的创建数据质量扫描部分。从表的详情页面创建扫描时,系统会预先选择该表。

      • 立即运行:运行扫描。

      • 修改扫描配置:修改设置,包括显示名称、过滤条件和时间表。

        如需修改数据质量规则,请在数据质量标签页上点击规则标签页。点击修改规则。更新规则,然后点击保存

      • 管理扫描权限:控制哪些人可以访问扫描结果。 如需了解详情,请参阅本文档的授予对数据质量扫描结果的访问权限部分。

      • 查看历史结果:查看之前的数据质量扫描作业的详细信息。如需了解详情,请参阅本文档中的查看数据质量扫描结果查看历史扫描结果部分。

      • 查看所有扫描:查看适用于相应表的数据质量扫描列表。

    • 不发布数据质量扫描结果:从以下选项中进行选择:

      • 创建数据质量扫描:创建新的数据质量扫描。如需了解详情,请参阅本文档中的创建数据质量扫描部分。从表的详情页面创建扫描时,系统会预先选择该表。

      • 查看现有扫描:查看适用于此表的数据质量扫描列表。

更新数据质量扫描

您可以修改现有数据质量扫描的各种设置,例如显示名称、过滤条件、时间表和数据质量规则。

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击数据质量扫描的名称。

  3. 如需修改设置(包括显示名称、过滤条件和时间表),请点击修改。修改值,然后点击保存

  4. 如需修改数据质量规则,请在扫描详情页面上点击当前规则标签页。点击修改规则。更新规则,然后点击保存

gcloud

如需更新数据质量扫描的说明,请使用 gcloud dataplex datascans update data-quality 命令

gcloud dataplex datascans update data-quality DATASCAN \
--location=LOCATION \
--description=DESCRIPTION

替换以下内容:

  • DATASCAN:要更新的数据质量扫描的名称。
  • LOCATION:在其中创建数据质量扫描的 Google Cloud 区域。
  • DESCRIPTION:数据质量扫描的新说明。

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Dataplex.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for UpdateDataScan</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void UpdateDataScanRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        UpdateDataScanRequest request = new UpdateDataScanRequest
        {
            DataScan = new DataScan(),
            UpdateMask = new FieldMask(),
            ValidateOnly = false,
        };
        // Make the request
        Operation<DataScan, OperationMetadata> response = dataScanServiceClient.UpdateDataScan(request);

        // Poll until the returned long-running operation is complete
        Operation<DataScan, OperationMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        DataScan result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<DataScan, OperationMetadata> retrievedResponse = dataScanServiceClient.PollOnceUpdateDataScan(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            DataScan retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.UpdateDataScanRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#UpdateDataScanRequest.
	}
	op, err := c.UpdateDataScan(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.DataScan;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.UpdateDataScanRequest;
import com.google.protobuf.FieldMask;

public class SyncUpdateDataScan {

  public static void main(String[] args) throws Exception {
    syncUpdateDataScan();
  }

  public static void syncUpdateDataScan() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      UpdateDataScanRequest request =
          UpdateDataScanRequest.newBuilder()
              .setDataScan(DataScan.newBuilder().build())
              .setUpdateMask(FieldMask.newBuilder().build())
              .setValidateOnly(true)
              .build();
      DataScan response = dataScanServiceClient.updateDataScanAsync(request).get();
    }
  }
}

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_update_data_scan():
    # Create a client
    client = dataplex_v1.DataScanServiceClient()

    # Initialize request argument(s)
    data_scan = dataplex_v1.DataScan()
    data_scan.data.entity = "entity_value"

    request = dataplex_v1.UpdateDataScanRequest(
        data_scan=data_scan,
    )

    # Make the request
    operation = client.update_data_scan(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the update_data_scan call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#update_data_scan.
#
def update_data_scan
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::UpdateDataScanRequest.new

  # Call the update_data_scan method.
  result = client.update_data_scan request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

REST

如需修改数据质量扫描,请使用 dataScans.patch 方法

删除数据质量扫描

控制台

控制台

  1. 在 Google Cloud 控制台中,前往 Knowledge Catalog 数据分析和质量评估页面。

    前往“数据分析和质量评估”

  2. 点击要删除的扫描。

  3. 点击删除,然后在系统提示时进行确认。

gcloud

gcloud

如需删除数据质量扫描,请使用 gcloud dataplex datascans delete 命令

gcloud dataplex datascans delete DATASCAN \
--location=LOCATION \
--async

执行以下变量替换操作:

  • DATASCAN:要删除的数据质量扫描的名称。
  • LOCATION:在其中创建数据质量扫描的 Google Cloud 区域。

C#

C#

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 C# 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog C# API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.Dataplex.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedDataScanServiceClientSnippets
{
    /// <summary>Snippet for DeleteDataScan</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void DeleteDataScanRequestObject()
    {
        // Create client
        DataScanServiceClient dataScanServiceClient = DataScanServiceClient.Create();
        // Initialize request argument(s)
        DeleteDataScanRequest request = new DeleteDataScanRequest
        {
            DataScanName = DataScanName.FromProjectLocationDataScan("[PROJECT]", "[LOCATION]", "[DATASCAN]"),
            Force = false,
        };
        // Make the request
        Operation<Empty, OperationMetadata> response = dataScanServiceClient.DeleteDataScan(request);

        // Poll until the returned long-running operation is complete
        Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        Empty result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<Empty, OperationMetadata> retrievedResponse = dataScanServiceClient.PollOnceDeleteDataScan(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            Empty retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Go

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Go 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Go API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


//go:build examples

package main

import (
	"context"

	dataplex "cloud.google.com/go/dataplex/apiv1"
	dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := dataplex.NewDataScanClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &dataplexpb.DeleteDataScanRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/dataplex/apiv1/dataplexpb#DeleteDataScanRequest.
	}
	op, err := c.DeleteDataScan(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	err = op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
}

Java

Java

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Java 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Java API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.dataplex.v1.DataScanName;
import com.google.cloud.dataplex.v1.DataScanServiceClient;
import com.google.cloud.dataplex.v1.DeleteDataScanRequest;
import com.google.protobuf.Empty;

public class SyncDeleteDataScan {

  public static void main(String[] args) throws Exception {
    syncDeleteDataScan();
  }

  public static void syncDeleteDataScan() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataScanServiceClient dataScanServiceClient = DataScanServiceClient.create()) {
      DeleteDataScanRequest request =
          DeleteDataScanRequest.newBuilder()
              .setName(DataScanName.of("[PROJECT]", "[LOCATION]", "[DATASCAN]").toString())
              .setForce(true)
              .build();
      dataScanServiceClient.deleteDataScanAsync(request).get();
    }
  }
}

Python

Python

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Python 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Python API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_delete_data_scan():
    # Create a client
    client = dataplex_v1.DataScanServiceClient()

    # Initialize request argument(s)
    request = dataplex_v1.DeleteDataScanRequest(
        name="name_value",
    )

    # Make the request
    operation = client.delete_data_scan(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Ruby

试用此示例之前,请按照《Knowledge Catalog 快速入门:使用客户端库》中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Knowledge Catalog Ruby API 参考文档

如需向 Knowledge Catalog 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/dataplex/v1"

##
# Snippet for the delete_data_scan call in the DataScanService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Dataplex::V1::DataScanService::Client#delete_data_scan.
#
def delete_data_scan
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dataplex::V1::DataScanService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dataplex::V1::DeleteDataScanRequest.new

  # Call the delete_data_scan method.
  result = client.delete_data_scan request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

REST

REST

如需删除数据质量扫描,请使用 dataScans.delete 方法

后续步骤