BigQuery に会話をエクスポートする

CX Insights を使用すると、CX Insights の会話と分析データを BigQuery にエクスポートし、独自の未加工クエリを実行できます。エクスポート プロセスでは、Speech Analysis Framework に似たスキーマが書き込まれます。このガイドでは、エクスポート プロセスについて詳しく説明します。

新しい 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 の暗号化/復号ロールを付与します。サービス アカウントの形式については、既知の問題に関するドキュメントをご覧ください。サービス アカウントに正しいロールを付与したら、テーブルを保護する 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 メソッドと URL:

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 にエクスポートすることもできます。

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"