將對話匯出至 BigQuery

您可以將 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 功能與所有可套用至對話查詢的篩選條件組合相容。舉例來說,以下範例會匯出 2021 年 1 月 1 日至 2021 年 1 月 2 日 (太平洋標準時間) 期間,agent_id「007」處理的所有對話,且對話輪次達 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 Insights 用來只匯出具有特定屬性的對話。舉例來說,輸入「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 匯出作業會將資料寫入擁有 CX Insights 資料的專案。不過,您也可以匯出至其他專案的 BigQuery。

請使用 IAM 控制台或 gcloud,確保 CX Insights 服務帳戶具備收件者專案的 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"