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

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

新しい BigQuery テーブルとデータセットを作成する

CX Insights Exporter が正常に動作するには、BigQuery テーブルが必要です。ターゲットテーブルがない場合は、このサンプルを使用して bq コマンドライン ツールで新しいテーブルとデータセットを作成します。 出力スキーマと列の定義については、BigQuery スキーマのドキュメント をご覧ください。

BigQuery には、データソースの場所に関する制限があります。 ロケーションに関する考慮事項をご覧ください。Cloud Storage バケットに適用される制限は、CX インサイトにも適用されます。たとえば、BigQuery データセットが EU マルチリージョン ロケーションにある場合、europe-* ロケーションのいずれかからのみ CX インサイトのデータをエクスポートできます。

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 インサイト サービス アカウントに 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 インサイト データの書き込み先となる BigQuery テーブル名。
  • FILTER_QUERY: 特定のプロパティを持つ会話のみをエクスポートするために CX インサイトで使用されるクエリ。たとえば、「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 インサイトに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、 ローカル開発環境の認証の設定をご覧ください。

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 インサイトに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、 ローカル開発環境の認証の設定をご覧ください。


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 インサイトに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、 ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 インサイト BigQuery エクスポートは、CX インサイト データを所有するのと同じプロジェクトにデータを書き込みます。ただし、別のプロジェクトの BigQuery にエクスポートすることもできます。

Identity and Access Management(IAM)コンソールまたは gcloud を使用して、CX インサイト サービス アカウントに受信者プロジェクトへの BigQuery アクセス権があることを確認します。

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

特定のプロジェクトにデータをエクスポートするには、受信者プロジェクトの ID 番号を project_id フィールドに BigQueryDestination オブジェクトに入力します。

BigQuery でデータをクエリする

このコマンドを実行して、BigQuery でデータをクエリします。その他のクエリ オプションについては、 BigQuery クイックスタート のドキュメントをご覧ください。

gcloud config set project PROJECT
bq show DATASET.TABLE

エクスポートされた会話のクエリ:

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