BigQuery로 대화 내보내기

고객 경험 인사이트 (CX 인사이트)를 사용하면 자체 원시 쿼리를 수행할 수 있도록 CX 인사이트 대화 및 분석 데이터를 BigQuery로 내보낼 수 있습니다. 내보내기 프로세스는 음성 분석 프레임워크와 유사한 스키마를 작성합니다. 이 가이드에서는 내보내기 프로세스를 자세히 설명합니다.

새 BigQuery 테이블 및 데이터 세트 만들기

CX Insights 내보내기 도구가 성공적으로 작동하려면 BigQuery 테이블이 필요합니다. 대상 테이블이 없으면 이 샘플을 사용하여 bq 명령줄 도구로 새 테이블과 데이터 세트를 만듭니다.

내보내기 프로세스에서 스키마를 작성하므로 테이블의 스키마를 지정할 필요가 없습니다. 하지만 스키마를 지정하는 경우 버전을 명시적으로 정의해야 합니다. EXPORT_VERSION_LATEST_AVAILABLE 명령어는 최신 버전을 안정적으로 제공하지 않으며 테이블에서 열을 삭제할 수 있습니다. 스키마가 있지만 버전이 없는 쿼리를 전송하면 기본적으로 초기 버전이 제공됩니다. 출력 스키마 및 열 정의는 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일(PST) 사이에 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 Key Management Service CryptoKey 암호화/복호화 역할을 부여합니다. 서비스 계정 형식에 관한 알려진 문제 문서를 참고하세요. 서비스 계정에 올바른 역할을 제공한 후 테이블을 보호하는 KMS 키의 정규화된 이름을 내보내기 요청에 추가합니다.

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

요청에 쓰기 처리 옵션 지정 (선택사항)

CX 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로 내보낼 수도 있습니다.

Identity and Access Management (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"