将对话导出到 BigQuery

借助 CX Insights,您可以将 CX Insights 对话和分析数据导出到 BigQuery,以便执行自己的原始查询。导出过程会写入类似于语音分析框架的架构。本指南将详细介绍导出流程。

创建新的 BigQuery 表和数据集

CX Insights Exporter 需要 BigQuery 表才能成功运行。如果您没有目标表,请使用此示例通过 bq 命令行工具创建新表和数据集。 如需了解输出架构和列定义,请参阅 BigQuery 架构文档

BigQuery 对数据源的位置有一些限制。请参阅位置注意事项。 适用于 Cloud Storage 存储分区的限制也适用于 CX Insights。例如,如果您的 BigQuery 数据集位于 EU 多区域位置,则只能从 europe-* 位置之一导出 CX Insights 数据。

bq mk --dataset --location=LOCATION PROJECT:DATASET

bq mk --table PROJECT:DATASET.TABLE

将对话数据导出到 BigQuery

导出工具支持过滤数据,也支持将数据写入受客户管理的加密密钥 (CMEK) 保护的表。如果您不想启用此功能,可以跳过此步骤,直接将数据导出到 BigQuery

向请求添加过滤条件(可选)

导出到 BigQuery 的功能与可应用于对话查询的所有过滤条件组合兼容。例如,以下示例将导出 agent_id“007”在 2021 年 1 月 1 日至 2021 年 1 月 2 日(太平洋标准时间)之间处理的所有对话,这些对话的轮次不少于 10 轮:

FILTER='create_time>"2021-01-01T00:00:00-08:00" create_time<"2021-01-02T00:00:00-08:00" agent_id="007" turn_count>="10"'

将数据导出到受 CMEK 保护的表(可选)

为您的 CX Insights 服务账号提供 Cloud KMS CryptoKey Encrypter/Decrypter 角色。请参阅有关服务账号格式的已知问题文档。为服务账号提供正确的角色后,请将保护表的 KMS 密钥的完全限定名称添加到导出请求中:

KMS_KEY='projects/<project>/locations/<location>/keyRings/<key_ring>/cryptoKeys/<key_name>'

在请求中指定写入处置方式选项(可选)

CCAI Insights 导出支持以下 BigQuery 写入处置选项

  • WRITE_TRUNCATE:如果相关表已存在,BigQuery 会覆盖表数据并使用查询结果中的架构。这是默认选项。
  • WRITE_APPEND:如果相关表已存在,BigQuery 会将数据附加到此表中。

例如,以下示例会将导出的数据附加到现有目标表:

WRITE_DISPOSITION='WRITE_APPEND'

将数据导出到 BigQuery

以下代码示例演示了如何导出数据。如需了解完整详情,请参阅导出参考文档

导出操作会创建一个长时间运行的 Operation 对象。您可以轮询操作以检查其状态。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • DATASET:应将数据导出到的 BigQuery 数据集的名称。
  • TABLE:应将 CX Insights 数据写入到的 BigQuery 表名称。
  • FILTER_QUERY:CX 数据洞见用于仅导出具有特定属性的对话的查询。例如,输入值“agent_id=\"007\"”将仅导出与代理 007 关联的对话。

HTTP 方法和网址:

POST https://contactcenterinsights.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/insightsdata:export

请求 JSON 正文:

{
  "bigQueryDestination": {
    "projectId": "PROJECT_ID",
    "dataset": "DATASET",
    "table": "TABLE",
  },
  "filter": "FILTER_QUERY"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"
}

Python

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

from google.cloud import contact_center_insights_v1


def export_to_bigquery(
    project_id: str,
    bigquery_project_id: str,
    bigquery_dataset_id: str,
    bigquery_table_id: str,
) -> None:
    """Exports data to BigQuery.

    Args:
        project_id:
            The project identifier that owns the data source to be exported.
            For example, 'my-project'.
        bigquery_project_id:
            The project identifier that owns the BigQuery sink to export data to.
            For example, 'my-project'.
        bigquery_dataset_id:
            The BigQuery dataset identifier. For example, 'my-dataset'.
        bigquery_table_id:
            The BigQuery table identifier. For example, 'my-table'.

    Returns:
        None.
    """
    # Construct an export request.
    request = contact_center_insights_v1.ExportInsightsDataRequest()
    request.parent = (
        contact_center_insights_v1.ContactCenterInsightsClient.common_location_path(
            project_id, "us-central1"
        )
    )
    request.big_query_destination.project_id = bigquery_project_id
    request.big_query_destination.dataset = bigquery_dataset_id
    request.big_query_destination.table = bigquery_table_id
    request.filter = 'agent_id="007"'

    # Call the Insights client to export data to BigQuery.
    insights_client = contact_center_insights_v1.ContactCenterInsightsClient()
    export_operation = insights_client.export_insights_data(request=request)
    export_operation.result(timeout=600000)
    print("Exported data to BigQuery")

Java

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


import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient;
import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsSettings;
import com.google.cloud.contactcenterinsights.v1.ExportInsightsDataRequest;
import com.google.cloud.contactcenterinsights.v1.ExportInsightsDataResponse;
import com.google.cloud.contactcenterinsights.v1.LocationName;
import java.io.IOException;
import org.threeten.bp.Duration;

public class ExportToBigquery {

  public static void main(String[] args) throws Exception, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my_project_id";
    String bigqueryProjectId = "my_bigquery_project_id";
    String bigqueryDataset = "my_bigquery_dataset";
    String bigqueryTable = "my_bigquery_table";

    exportToBigquery(projectId, bigqueryProjectId, bigqueryDataset, bigqueryTable);
  }

  public static void exportToBigquery(
      String projectId, String bigqueryProjectId, String bigqueryDataset, String bigqueryTable)
      throws Exception, IOException {
    // Set the operation total polling timeout to 24 hours instead of the 5-minute default.
    // Other values are copied from the default values of {@link ContactCenterInsightsStubSettings}.
    ContactCenterInsightsSettings.Builder clientSettings =
        ContactCenterInsightsSettings.newBuilder();
    clientSettings
        .exportInsightsDataOperationSettings()
        .setPollingAlgorithm(
            OperationTimedPollAlgorithm.create(
                RetrySettings.newBuilder()
                    .setInitialRetryDelay(Duration.ofMillis(5000L))
                    .setRetryDelayMultiplier(1.5)
                    .setMaxRetryDelay(Duration.ofMillis(45000L))
                    .setInitialRpcTimeout(Duration.ZERO)
                    .setRpcTimeoutMultiplier(1.0)
                    .setMaxRpcTimeout(Duration.ZERO)
                    .setTotalTimeout(Duration.ofHours(24L))
                    .build()));

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ContactCenterInsightsClient client =
        ContactCenterInsightsClient.create(clientSettings.build())) {
      // Construct an export request.
      LocationName parent = LocationName.of(projectId, "us-central1");
      ExportInsightsDataRequest request =
          ExportInsightsDataRequest.newBuilder()
              .setParent(parent.toString())
              .setBigQueryDestination(
                  ExportInsightsDataRequest.BigQueryDestination.newBuilder()
                      .setProjectId(bigqueryProjectId)
                      .setDataset(bigqueryDataset)
                      .setTable(bigqueryTable)
                      .build())
              .setFilter("agent_id=\"007\"")
              .build();

      // Call the Insights client to export data to BigQuery.
      ExportInsightsDataResponse response = client.exportInsightsDataAsync(request).get();
      System.out.printf("Exported data to BigQuery");
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my_project_id';
// const bigqueryProjectId = 'my_bigquery_project_id';
// const bigqueryDataset = 'my_bigquery_dataset';
// const bigqueryTable = 'my_bigquery_table';

// Imports the Contact Center Insights client.
const {
  ContactCenterInsightsClient,
} = require('@google-cloud/contact-center-insights');

// Instantiates a client.
const client = new ContactCenterInsightsClient();

async function exportToBigquery() {
  const [operation] = await client.exportInsightsData({
    parent: client.locationPath(projectId, 'us-central1'),
    bigQueryDestination: {
      projectId: bigqueryProjectId,
      dataset: bigqueryDataset,
      table: bigqueryTable,
    },
    filter: 'agent_id="007"',
  });

  // Wait for the operation to complete.
  await operation.promise();
  console.info('Exported data to BigQuery');
}
exportToBigquery();

将数据导出到其他项目(可选)

默认情况下,CX Insights BigQuery Export 会将数据写入拥有 CX Insights 数据的同一项目。不过,您也可以导出到其他项目中的 BigQuery。

确保您的 CX Insights 服务账号可以使用 IAM 控制台或通过 gcloud 获得对接收方项目的 BigQuery 访问权限:

gcloud projects add-iam-policy-binding RECEIVER_PROJECT \
    --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-contactcenterinsights.iam.gserviceaccount.com \
    --role=roles/bigquery.admin

如需将数据导出到特定项目,请在 BigQueryDestination 对象的 project_id 字段中输入接收方项目的 ID 编号。

在 BigQuery 中查询数据

运行此命令以查询 BigQuery 中的数据。如需了解更多查询选项,请参阅 BigQuery 快速入门文档:

gcloud config set project PROJECT
bq show DATASET.TABLE

查询导出的对话:

bq query --use_legacy_sql=false \
   "SELECT conversationName FROM DATASET.TABLE"