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로 내보내기는 대화 쿼리에 적용할 수 있는 모든 필터 조합과 호환됩니다. 예를 들어 다음 샘플은 2021년 1월 1일과 2021년 1월 2일 사이에 agent_id '007'이 처리한 턴이 10개 이상인 모든 대화를 내보냅니다(PST).

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 통계에서 특정 속성이 있는 대화만 내보내는 데 사용하는 쿼리입니다. 예를 들어 '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"