Consulte os conetores suportados para a solução Application Integration.

Insira dados no BigQuery através de uma tarefa For Each Parallel

Neste tutorial, vai criar uma integração de aplicações e uma subintegração para processar uma série de registos. Para cada registo, a integração principal invoca de forma assíncrona a subintegração, que recebe os dados de cada registo e insere-os como uma linha numa tabela num conjunto de dados do BigQuery.

Neste tutorial, vai concluir as seguintes tarefas:

Antes de começar

  • Certifique-se de que tem acesso à solução Application Integration.
  • Faça o seguinte no seu projeto do Google Cloud:

    • Conceda as seguintes funções à conta de serviço que quer usar para criar a associação:
      • roles/bigquery.dataEditor
      • roles/bigquery.readSessionUser
      • roles/secretmanager.viewer
      • roles/secretmanager.secretAccessor
    • Ative os seguintes serviços:
      • secretmanager.googleapis.com (Secret Manager API)
      • connectors.googleapis.com (API Connectors)

      Se estes serviços não tiverem sido ativados anteriormente para o seu projeto, é-lhe pedido que os ative quando criar a associação na página Criar associação.

Configure uma associação do BigQuery

Comece por criar o conjunto de dados e a tabela do BigQuery a usar neste tutorial. Depois de criar o conjunto de dados e a tabela, crie uma ligação do BigQuery. Vai usar esta ligação numa integração mais tarde neste tutorial.

Configure um conjunto de dados e uma tabela do BigQuery

Siga estes passos para configurar o conjunto de dados e a tabela do BigQuery:

  1. Na página da Cloud Console, selecione o seu Google Cloud projeto.
  2. Para iniciar uma sessão do Cloud Shell a partir da Google Cloud consola, clique no ícone Ícone Ativar Cloud Shell Ativar Cloud Shell na Cloud Console. Esta ação inicia uma sessão no painel inferior da consola do Google Cloud .
  3. Para ativar as APIs BigQuery, introduza os seguintes comandos no terminal do Cloud Shell:
    export PROJECT_ID=project_id
    export REGION=region
    gcloud services enable --project "${PROJECT_ID}" \
        bigquery.googleapis.com \
        bigquerystorage.googleapis.com
    Neste comando, substitua:
    • project_id com o ID do projeto do seu Google Cloud projeto.
    • region com a região que quer usar para criar o seu conjunto de dados do BigQuery.
  4. Para criar um conjunto de dados do BigQuery com o nome bq_tutorial, introduza o seguinte comando no terminal do Cloud Shell:
          bq  --project_id ${PROJECT_ID} --location ${REGION} mk bq_tutorial
        
  5. Para criar uma tabela do BigQuery com o nome tutorial, introduza o seguinte comando no terminal do Cloud Shell:
          bq --project_id ${PROJECT_ID} \
            query  \
            --nouse_legacy_sql \
          'create table bq_tutorial.tutorial (
          unique_key STRING NOT NULL,
          created_date STRING,
          closed_date STRING,
          agency STRING,
          agency_name STRING,
          complaint_type STRING,
          descriptor STRING,
          location_type STRING,
          incident_zip STRING,
          incident_address STRING,
          street_name STRING,
          cross_street_1 STRING,
          cross_street_2 STRING,
          intersection_street_1 STRING,
          intersection_street_2 STRING,
          address_type STRING,
          city STRING,
          landmark STRING,
          facility_type STRING,
          status STRING,
          due_date STRING,
          resolution_action_updated_date STRING,
          community_board STRING,
          borough STRING,
          x_coordinate_state_plane STRING,
          y_coordinate_state_plane STRING,
          park_facility_name STRING,
          park_borough STRING,
          school_name STRING,
          school_number STRING,
          school_region STRING,
          school_code STRING,
          school_phone_number STRING,
          school_address STRING,
          school_city STRING,
          school_state STRING,
          school_zip STRING,
          school_not_found STRING,
          school_or_citywide_complaint STRING,
          vehicle_type STRING,
          taxi_company_borough STRING,
          taxi_pick_up_location STRING,
          bridge_highway_name STRING,
          bridge_highway_direction STRING,
          bridge_highway_segment STRING,
          road_ramp STRING,
          garage_lot_name STRING,
          ferry_direction STRING,
          ferry_terminal_name STRING,
          latitude STRING,
          longitude STRING,
          location STRING
          ) '
      
  6. Verify that your BigQuery table is created.
    1. In the Cloud console page, click the Navigation menu.
    2. In the Analytics section, click BigQuery.
    3. Expand your project and confirm that the bq_tutorial dataset is listed.
    4. Expand the bq_tutorial dataset and confirm that the tutorial table is listed.
    5. Click the documents table to view the schema.

Create a BigQuery connection

Next, you'll create a BigQuery connection. A BigQuery connection lets you insert, read, update and delete rows in a BigQuery table and use the resulting output in an integration. After creating the BigQuery connection, you'll use this connection in an integration later in this tutorial to add rows to the BigQuery table.

To create a BigQuery connection, complete the following steps:

  1. In the Cloud console page, select your Google Cloud project.
  2. Open the connections page.
  3. Click + CREATE NEW to open the Create Connection page.
  4. Configure the connection:
    1. In the Create Connection section, complete the following:
      • Connector: Select BigQuery from the drop down list of available Connectors.
      • Connector version: Select the latest Connector version from the drop down list of available versions.
      • In the Connection Name field, enter a name for the Connection instance. For this tutorial, enter connector-bq-tutorial.
      • Optionally, add a Description of the connection instance.
      • Service Account: Select a service account that has the required roles.
      • Project ID: Enter the ID of the Google Cloud project where the BigQuery data resides.
      • Dataset ID: Enter the ID of the BigQuery dataset that you want to use. For this tutorial, enter bq_tutorial.
      • Optionally, click + ADD LABEL to add a label in the form of a key/value pair.
      • Click Next.
    2. Location: Select a region from where the connection will run. Supported regions for connectors include:

        For the list of all the supported regions, see Locations.

      • Click Next.
    3. Authentication: The BigQuery connection does not require authentication configuration. Click Next.
    4. Review: Review your connection's configuration details. In this section, the connection and authentication details of the new connection are displayed for your review.
  5. Click Create.

Set up a sub-integration

In this tutorial, the sub-integration takes each record sent to it by the main integration and inserts it as a row in the tutorial table in the bq_tutorial dataset.

Create a sub-integration

To create the sub-integration, complete the following steps:

  1. In the Google Cloud console, go to the Application Integration page.

    Go to Application Integration

  2. Click Integrations from the left navigation menu to open the Integrations page.
  3. Click Create integration.
  4. In the Create Integration dialog, do the following:
    • Enter a name, for example, enter Process-each-record
    • Optionally, enter a description. For example, enter API Trigger to process each record (sub-integration)
    • Select the region where you want to create your integration.
  5. Click Create to open the integration editor.

Add an API Trigger

To add an API Trigger to the integration, do the following:

  1. In the integration editor, select Add a task/trigger > Triggers to display a list of available triggers.
  2. Drag the API Trigger element to the integration editor.

Add a Data Mapping task

To add a Data Mapping task in the integration, complete the following steps:

  1. Select +Add a task/trigger > Tasks in the integration editor to display the list of available tasks.
  2. Drag the Data Mapping element to the integration editor.

Configure the BigQuery connection

Now you are ready to use the BigQuery connection that you created earlier in the sub-integration. To configure the BigQuery connection in this integration, complete the following steps:

  1. Select +Add a task/trigger > Tasks in the integration editor to display the list of available tasks.
  2. Drag the Connectors element to the integration editor.
  3. Click the Connectors task element on the designer to view the task configuration pane.
  4. Click the edit icon on the right panel and update the Label to Insert row to BigQuery.
  5. Click Configure task.

    The Configure connector task dialog appears.

  6. In the Configure connector task dialog, do the following:
    1. Select the connection region where you created your BigQuery connection.
    2. Select the BigQuery connection that you want to use. For this tutorial, select connector-bq-tutorial.
    3. Once a connection is chosen, the Type column appears. Select Entities and then tutorial from the list of available entities.
    4. Once a type is chosen, the Operation column appears. Select Create.
    5. Click Done to complete the connection configuration and close the dialog.

Connect the integration elements

Next, add edge connections to connect the API Trigger to the Data Mapping task and the Data Mapping task to the Connectors task. An edge connection is a connection between any two elements in an integration. For more information on edges and edge conditions, see Edges.

To add the edge connections, complete the following steps:

  1. Click the Fork control point at the bottom of the API Trigger element. Drag and drop the edge connection at the Join control point at the top of the Data Mapping element.
  2. Click the Fork control point at the bottom of the Data Mapping element. Drag and drop the edge connection at the Join control point at the top of the Connectors element.

Configure the Data Mapping task

To configure the Data Mapping task, complete the following steps:

  1. In the integration editor, click the Data Mapping task to view the task configuration pane.
  2. Click Open Data Mapping Editor.
  3. In the Data Mapping Editor, click Add to add a new variable.
  4. In the Create Variable dialog, enter the following information:
    • Name: Enter record.
    • Data Type: Select JSON.
    • Schema: Select Infer from a sample JSON payload. Enter the following sample JSON payload:
                  {
                    "unique_key":"304271",
                    "created_date":"02/06/2007 12:00:00 AM",
                    "closed_date":"03/01/2007 12:00:00 AM",
                    "agency":"TLC",
                    "agency_name":"Taxi and Limousine Commission",
                    "complaint_type":"Taxi Complaint",
                    "descriptor":"Driver Complaint",
                    "location_type":"Street",
                    "incident_zip":"10001",
                    "incident_address":"",
                    "street_name":"",
                    "cross_street_1":"",
                    "cross_street_2":"",
                    "intersection_street_1":"WEST 29 STREET",
                    "intersection_street_2":"7 AVENUE",
                    "address_type":"INTERSECTION",
                    "city":"NEW YORK",
                    "landmark":"",
                    "facility_type":"N/A",
                    "status":"Closed",
                    "due_date":"02/28/2007 12:00:00 AM",
                    "resolution_action_updated_date":"03/01/2007 12:00:00 AM",
                    "community_board":"05 MANHATTAN",
                    "borough":"MANHATTAN",
                    "x_coordinate_state_plane":"986215",
                    "y_coordinate_state_plane":"211740",
                    "park_facility_name":"",
                    "park_borough":"MANHATTAN",
                    "school_name":"",
                    "school_number":"",
                    "school_region":"",
                    "school_code":"",
                    "school_phone_number":"",
                    "school_address":"",
                    "school_city":"",
                    "school_state":"",
                    "school_zip":"",
                    "school_not_found":"",
                    "school_or_citywide_complaint":"",
                    "vehicle_type":"",
                    "taxi_company_borough":"",
                    "taxi_pick_up_location":"Other",
                    "bridge_highway_name":"",
                    "bridge_highway_direction":"",
                    "road_ramp":"",
                    "bridge_highway_segment":"",
                    "garage_lot_name":"",
                    "ferry_direction":"",
                    "ferry_terminal_name":"",
                    "latitude":"40.74785373937869",
                    "longitude":"-73.99290823133913",
                    "location":"(40.74785373937869, -73.99290823133913)"
                  }
                
    • Clique em Criar.
    • Quando a variável é criada, no editor de mapeamento de dados, conclua os seguintes passos:
      • Arraste a nova variável de registo para a coluna Entrada.
      • Arraste a variável connectorInputPayload para a coluna Saída.
    • Feche o editor de mapeamento de dados para voltar ao editor de integração.

Publique a subintegração

Para publicar a subintegração, no editor de integração, clique em Publicar.

Configure a integração principal

Nesta secção, configura a integração principal, que usa uma tarefa For Each Parallel para processar cada registo. Esta integração principal invoca a subintegração uma vez para cada registo.

Crie a integração principal

Para criar a integração principal, conclua os seguintes passos:

  1. Na Google Cloud Console, aceda à página Integração de aplicações.

    Aceda à solução Application Integration

  2. Clique em Integrações no menu de navegação do lado esquerdo para abrir a página Integrações.
  3. Clique em Criar integração.
  4. Na caixa de diálogo Criar integração, faça o seguinte:
    • Introduza um nome, por exemplo, process-records.
    • Opcionalmente, introduza uma descrição. Por exemplo, introduza Acionador de API para processar registos (integração principal)
    • Selecione a região onde quer criar a integração.
  5. Clique em Criar para abrir o editor de integração.

Adicione um acionador de API

Para adicionar um acionador de API à integração, faça o seguinte:

  1. No editor de integração, selecione Adicionar uma tarefa/acionador > Acionadores para apresentar uma lista de acionadores disponíveis.
  2. Arraste o elemento Acionador da API para o editor de integração.

Adicione uma tarefa Para cada paralelo

Para adicionar uma tarefa Para cada paralelo na integração, conclua os seguintes passos:

  1. Selecione +Adicionar uma tarefa/acionador > Tarefas no editor de integração para apresentar a lista de tarefas disponíveis.
  2. Arraste o elemento For Each Parallel para o editor de integração.

Ligue os elementos de integração

Em seguida, adicione uma ligação de aresta para ligar o acionador da API à tarefa paralela For Each.

Para adicionar a ligação de limite, clique no ponto de controlo Fork na parte inferior do elemento Acionador de API. Arraste e largue a ligação de aresta no ponto de controlo Join na parte superior do elemento de tarefa For Each Parallel.

Configure a tarefa Para cada paralelo

Para configurar a tarefa Para cada paralelo, conclua os seguintes passos:

  1. No editor de integração, clique na tarefa Para cada paralelo para ver o painel de configuração da tarefa.
  2. Em Seleção de matriz > Lista a iterar, clique em Adicionar nova variável para adicionar uma nova variável.
  3. Na caixa de diálogo Criar variável, introduza as seguintes informações:
    • Nome: introduza records
    • Tipo de dados: selecione JSON.
    • Esquema: selecione Inferir a partir de um payload JSON de exemplo. Introduza o seguinte payload JSON de exemplo:
                    [{
                      "unique_key":"304271",
                      "created_date":"02/06/2007 12:00:00 AM",
                      "closed_date":"03/01/2007 12:00:00 AM",
                      "agency":"TLC",
                      "agency_name":"Taxi and Limousine Commission",
                      "complaint_type":"Taxi Complaint",
                      "descriptor":"Driver Complaint",
                      "location_type":"Street",
                      "incident_zip":"10001",
                      "incident_address":"",
                      "street_name":"",
                      "cross_street_1":"",
                      "cross_street_2":"",
                      "intersection_street_1":"WEST 29 STREET",
                      "intersection_street_2":"7 AVENUE",
                      "address_type":"INTERSECTION",
                      "city":"NEW YORK",
                      "landmark":"",
                      "facility_type":"N/A",
                      "status":"Closed",
                      "due_date":"02/28/2007 12:00:00 AM",
                      "resolution_action_updated_date":"03/01/2007 12:00:00 AM",
                      "community_board":"05 MANHATTAN",
                      "borough":"MANHATTAN",
                      "x_coordinate_state_plane":"986215",
                      "y_coordinate_state_plane":"211740",
                      "park_facility_name":"",
                      "park_borough":"MANHATTAN",
                      "school_name":"",
                      "school_number":"",
                      "school_region":"",
                      "school_code":"",
                      "school_phone_number":"",
                      "school_address":"",
                      "school_city":"",
                      "school_state":"",
                      "school_zip":"",
                      "school_not_found":"",
                      "school_or_citywide_complaint":"",
                      "vehicle_type":"",
                      "taxi_company_borough":"",
                      "taxi_pick_up_location":"Other",
                      "bridge_highway_name":"",
                      "bridge_highway_direction":"",
                      "road_ramp":"",
                      "bridge_highway_segment":"",
                      "garage_lot_name":"",
                      "ferry_direction":"",
                      "ferry_terminal_name":"",
                      "latitude":"40.74785373937869",
                      "longitude":"-73.99290823133913",
                      "location":"(40.74785373937869, -73.99290823133913)"
                    }]
                  
  4. Clique em Criar.
  5. Na secção Detalhes da subintegração, introduza as seguintes informações:
    • ID do acionador da API: selecione o elemento do acionador da API na subintegração. Por exemplo, selecione Process-each-record_API_1.
    • Estratégia de execução: selecione ASYNC.
    • Selecione Executar uma única integração.
  6. Na secção Em cada execução, para Onde mapear elementos individuais da matriz, introduza o nome da variável na tarefa de mapeamento de dados na subintegração. Neste caso, introduza record. As variáveis de subintegração são apresentadas apenas para integrações publicadas. Se as variáveis não estiverem listadas, atualize a página, uma vez que as variáveis demoram algum tempo a ficar visíveis após a publicação da subintegração.

Publique a integração principal

Para publicar a integração principal, no editor de integração, clique em Publicar.

Teste a integração

Para testar a integração, conclua os seguintes passos:

  1. Transfira dados de exemplo para o Cloud Shell:
    1. Para iniciar uma sessão do Cloud Shell a partir da Google Cloud consola, clique no ícone Ícone Ativar Cloud Shell Ativar Cloud Shell na Cloud Console. Esta ação inicia uma sessão no painel inferior da consola do Google Cloud .
    2. Introduza o seguinte comando no terminal do Cloud Shell:
      wget https://raw.githubusercontent.com/GoogleCloudPlatform/application-integration-samples/main/assets/bq-sample-dataset.json
              
    3. Para verificar se os dados de amostra foram transferidos, introduza o seguinte comando no terminal do Cloud Shell:
      ls -la bq-sample-dataset.json
      O ficheiro transferido é apresentado no terminal do Cloud Shell.
  2. Para selecionar três entradas aleatórias do conjunto de dados de amostra e armazená-las de forma que as possa transmitir à integração, introduza os seguintes comandos no terminal do Cloud Shell:
    AUTH=$(gcloud auth print-access-token)
    export SAMPLE_DOCS=$(jq $(r=$((RANDOM % 1000)) ; echo ".[$r:$((r + 3))]") < bq-sample-dataset.json | jq -Rs '.')
                
    generate_post_data()
      {
        cat <<EOF
          {
            "triggerId": "api_trigger/process-records_API_1",
            "inputParameters": 
              {
                "records": 
                  {
                    "jsonValue": $SAMPLE_DOCS
                  }
              }
          }
          EOF
      }
  3. Para iniciar os testes, introduza o seguinte comando no terminal do Cloud Shell:
    curl -X POST \
      https://integrations.googleapis.com/v1/projects/project_id/locations/region/integrations/process-records:execute \
      -H "Authorization: Bearer $AUTH" \
      -H "Content-Type: application/json" \
      -d "$(generate_post_data)"
    Neste comando, substitua:
    • project_id com o ID do projeto do seu Google Cloud projeto.
    • region com a região onde criou a integração.
    Este comando invoca a integração principal e passa as entradas do conjunto de dados de exemplo para a integração principal. A integração principal passa, em seguida, cada entrada para a subintegração, que adiciona os dados como uma linha na sua tabela do BigQuery.
  4. Para verificar se a tabela do BigQuery contém agora estes registos, siga estes passos:
    1. Na página Consola do Google Cloud, clique no menu de navegação.
    2. Na secção Analytics, clique em BigQuery.
    3. Expanda o projeto e clique no conjunto de dados bq_tutorial.
    4. Expanda o conjunto de dados bq_tutorial e clique na tabela tutorial.
    5. Clique no separador Explorador de tabelas para ver os registos inseridos.

O que se segue?

Experimente criar integrações com outros conetores. Para ver a lista de todos os conetores suportados, consulte a referência do conetor.