Esportazione di conversazioni in BigQuery

Customer Experience Insights (CX Insights) ti consente di esportare i dati di conversazione e analisi di CX Insights in BigQuery per eseguire le tue query non elaborate. Il processo di esportazione scrive uno schema simile al framework di analisi del parlato. Questa guida descrive in dettaglio la procedura di esportazione.

Crea una nuova tabella e un nuovo set di dati BigQuery

Per il corretto funzionamento dell'esportatore di CX Insights è necessaria una tabella BigQuery. Se non hai una tabella di destinazione, utilizza questo esempio per creare una nuova tabella e un nuovo set di dati utilizzando lo strumento a riga di comando bq.

Non è necessario specificare uno schema per la tabella perché il processo di esportazione ne scrive uno. Tuttavia, se specifichi uno schema, devi definire esplicitamente la versione. Il comando EXPORT_VERSION_LATEST_AVAILABLE non fornisce in modo affidabile la versione più recente e potrebbe rimuovere colonne dalla tabella. L'invio di una query con uno schema, ma senza versione, fornisce una versione precedente per impostazione predefinita. Consulta la documentazione dello schema BigQuery per lo schema di output e le definizioni delle colonne.

BigQuery presenta alcune limitazioni relative alla località dell'origine dati. Consulta la sezione Considerazioni sulla posizione. Le limitazioni che si applicano ai bucket Cloud Storage si applicano anche a CX Insights. Ad esempio, se il set di dati BigQuery si trova nella località multiregionale EU, puoi esportare i dati di CX Insights solo da una delle località europe-*.

bq mk --dataset --location=LOCATION PROJECT:DATASET

bq mk --table PROJECT:DATASET.TABLE

Esporta i dati delle conversazioni in BigQuery

Lo strumento di esportazione supporta sia il filtro che la scrittura dei dati in tabelle protette da chiavi di crittografia gestite dal cliente (CMEK). Se non vuoi attivare questa funzionalità, puoi andare avanti ed esportare i dati in BigQuery.

(Facoltativo) Aggiungi filtri alla richiesta

L'esportazione in BigQuery è compatibile con tutte le combinazioni di filtri che possono essere applicate alle query di conversazione. Ad esempio, l'esempio seguente esporta tutte le conversazioni con 10 o più turni gestiti da agent_id "007" tra il 1° gennaio 2021 e il 2 gennaio 2021 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"'

Esporta i dati in una tabella protetta da CMEK (facoltativo)

Fornisci al tuo account di servizio CX Insights il ruolo Cloud Key Management Service CryptoKey Encrypter/Decrypter. Consulta la documentazione sui problemi noti relativi al formato dei account di servizio. Dopo aver assegnato il ruolo corretto al account di servizio, aggiungi il nome completo della chiave KMS che protegge la tabella alla richiesta di esportazione:

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

Specifica l'opzione di disposizione di scrittura nella richiesta (facoltativo)

L'esportazione di CX Insights supporta le seguenti opzioni di disposizione di scrittura di BigQuery:

  • WRITE_TRUNCATE: se la tabella esiste già, BigQuery sovrascrive i dati della tabella e utilizza lo schema del risultato della query. Questa è l'opzione predefinita.
  • WRITE_APPEND: se la tabella esiste già, BigQuery aggiunge i dati alla tabella.

Ad esempio, l'esempio seguente aggiunge i dati esportati a una tabella di destinazione esistente:

WRITE_DISPOSITION='WRITE_APPEND'

Esporta i dati in BigQuery

Il seguente esempio di codice mostra come esportare i dati. Per informazioni dettagliate, consulta la documentazione di riferimento sull'esportazione.

L'esportazione crea un oggetto Operation a lunga esecuzione. Puoi eseguire il polling dell'operazione per verificarne lo stato.

REST

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT_ID: l'ID del tuo progetto Google Cloud.
  • DATASET: il nome del set di dati BigQuery in cui esportare i dati.
  • TABLE: il nome della tabella BigQuery in cui devono essere scritti i dati di CX Insights.
  • FILTER_QUERY: una query utilizzata da CX Insights per esportare solo le conversazioni con proprietà specifiche. Ad esempio, l'inserimento del valore "agent_id=\"007\"" comporterà l'esportazione solo delle conversazioni associate all'agente 007.

Metodo HTTP e URL:

POST https://contactcenterinsights.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/insightsdata:export

Corpo JSON della richiesta:

{
  "bigQueryDestination": {
    "projectId": "PROJECT_ID",
    "dataset": "DATASET",
    "table": "TABLE"
  },
  "filter": "FILTER_QUERY"
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"
}

Python

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in CX Insights, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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();

Esporta i dati in un altro progetto (facoltativo)

Per impostazione predefinita, BigQuery Export di CX Insights scrive i dati nello stesso progetto proprietario dei dati di CX Insights. Tuttavia, puoi anche eseguire l'esportazione in BigQuery in un altro progetto.

Assicurati che il tuo account di servizio CX Insights disponga dell'accesso BigQuery al progetto destinatario utilizzando la console Identity and Access Management (IAM) o con gcloud:

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

Per esportare i dati in un progetto specifico, inserisci il numero ID del progetto destinatario nel campo project_id dell'oggetto BigQueryDestination.

Esegui query sui dati in BigQuery

Esegui questo comando per eseguire una query sui dati in BigQuery. Per altre opzioni di query, consulta la documentazione della guida rapida di BigQuery:

gcloud config set project PROJECT
bq show DATASET.TABLE

Esecuzione di query sulle conversazioni esportate:

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