Consulte os conectores compatíveis com a integração de aplicativos.
Inserir dados no BigQuery usando uma tarefa Para cada paralelo
Neste tutorial, você vai criar uma integração de app e uma subintegração para processar uma série de registros. Para cada registro, a integração principal invoca de maneira assíncrona a subintegração, que usa os dados de cada registro e os insere como uma linha em uma tabela de um conjunto de dados do BigQuery.
Neste tutorial, você concluirá as seguintes tarefas:
- Configurar uma conexão do BigQuery
- Configurar uma subintegração
- Configurar a integração principal
- Testar sua integração
Antes de começar
- Verifique se você tem acesso à integração da Apigee.
-
Faça o seguinte no seu projeto do Google Cloud:
- Conceda os seguintes papéis à conta de serviço que você quer usar para criar a conexão:
roles/bigquery.dataEditor
roles/bigquery.readSessionUser
roles/secretmanager.viewer
roles/secretmanager.secretAccessor
- Ative os seguintes serviços:
secretmanager.googleapis.com
(API Secret Manager)connectors.googleapis.com
(API Connectors)
Se esses serviços não tiverem sido ativados no projeto anteriormente, será solicitado que você os ative ao criar a conexão na página Criar conexão.
- Conceda os seguintes papéis à conta de serviço que você quer usar para criar a conexão:
Configurar uma conexão do BigQuery
Comece criando o conjunto de dados e a tabela do BigQuery para usar neste tutorial. Depois de criar o conjunto de dados e a tabela, crie uma conexão do BigQuery. Você usará essa conexão em uma integração mais adiante neste tutorial.
Configurar um conjunto de dados e uma tabela do BigQuery
Para configurar o conjunto de dados e a tabela do BigQuery, siga estas etapas:
- Na página Console do Cloud, selecione seu projeto Google Cloud .
- Para iniciar uma sessão do Cloud Shell no console do Google Cloud,
clique no ícone
Ativar o Cloud Shell no console do Cloud. Isso inicia uma sessão no painel inferior do console do Google Cloud.
-
Para ativar as APIs BigQuery, digite os seguintes comandos no terminal do Cloud Shell:
Neste comando, substitua:export PROJECT_ID=project_id export REGION=region gcloud services enable --project "${PROJECT_ID}" \ bigquery.googleapis.com \ bigquerystorage.googleapis.com
project_id
pelo ID do projeto Google Cloud .region
pela região que você quer usar para criar o conjunto de dados do BigQuery.
- Para criar um conjunto de dados do BigQuery com o nome
bq_tutorial
, digite o seguinte comando no terminal do Cloud Shell:bq --project_id ${PROJECT_ID} --location ${REGION} mk bq_tutorial
- Para criar uma tabela do BigQuery com o nome
tutorial
, digite 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 ) '
-
Verify that your BigQuery table is created.
- In the Cloud console page, click the Navigation menu.
- In the Analytics section, click BigQuery.
-
Expand your project and confirm that the
bq_tutorial
dataset is listed. -
Expand the bq_tutorial dataset and confirm that the
tutorial
table is listed. - 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:
- In the Cloud console page, select your Google Cloud project.
- Open the connections page.
- Click + CREATE NEW to open the Create Connection page.
- Configure the connection:
- 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.
- Location: Select a region from where the connection will run. Supported
regions for connectors include:
- Click Next.
For the list of all the supported regions, see Locations.
- Authentication: The BigQuery connection does not require authentication configuration. Click Next.
- Review: Review your connection's configuration details. In this section, the connection and authentication details of the new connection are displayed for your review.
- In the Create Connection section, complete the following:
- 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:
- In the Google Cloud console, go to the Application Integration page.
- In the navigation menu, click Integrations. The Integrations page appears.
- Click Create integration.
- 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.
- Click Create to open the integration editor.
Add an API Trigger
To add an API Trigger to the integration, do the following:
- In the integration editor, select Add a task/trigger > Triggers to display a list of available triggers.
- 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:
- Select +Add a task/trigger > Tasks in the integration editor to display the list of available tasks.
- 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:
- Select +Add a task/trigger > Tasks in the integration editor to display the list of available tasks.
- Drag the Connectors element to the integration editor.
- Click the Connectors task element on the designer to view the task configuration pane.
- Click the edit icon on the right panel and update the Label to Insert row to BigQuery.
- Click Configure task.
The Configure connector task dialog appears.
- In the Configure connector task dialog, do the following:
- Select the connection region where you created your BigQuery connection.
- Select the BigQuery connection that you want to use. For this tutorial, select connector-bq-tutorial.
- Once a connection is chosen, the Type column appears. Select Entities and then tutorial from the list of available entities.
- Once a type is chosen, the Operation column appears. Select Create.
- 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:
- 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.
- 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:
- In the integration editor, click the Data Mapping task to view the task configuration pane.
- Click Open Data Mapping Editor.
- In the Data Mapping Editor, click Add to add a new variable.
- 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 for criada, no Editor de mapeamento de dados, siga estas etapas:
- Arraste a nova variável registro para a coluna Saída.
- Arraste a variável connectorInputPayload para a coluna Saída.
- Feche o Editor de mapeamento de dados para retornar ao editor de integração.
Publicar a subintegração
Para publicar a subintegração, clique em Publicar no editor de integração.
Configurar a integração principal
Nesta seção, você vai configurar a integração principal, que usa uma tarefa Para cada paralelo para processar cada registro. Em seguida, essa integração principal invoca a subintegração uma vez para cada registro.
Criar a integração principal
Para criar a integração principal, siga estas etapas:
- No console do Google Cloud, acesse a página Application Integration.
- No menu de navegação, clique em Integrações. A página Integrations aparece.
- Clique em CRIAR INTEGRAÇÃO.
- Na caixa de diálogo Criar integração, execute as ações a seguir:
- Digite um nome como, por exemplo, process-records.
- Opcionalmente, insira uma descrição. Por exemplo, digite o Gatilho da API para processar registros (integração principal).
- Selecione a região em que você quer criar a integração.
- Clique em Criar para abrir o editor de integração.
Adicionar um gatilho de API
Para adicionar um gatilho de API à integração, faça o seguinte:
- No designer de integração, selecione Adicionar uma tarefa/gatilho > Gatilhos para exibir uma lista de gatilhos disponíveis.
- Arraste o elemento Gatilho da API para o designer de integração.
Adicionar uma tarefa Para cada paralelo
Para adicionar uma tarefa para cada paralelo na integração, siga estas etapas:
- Selecione Adicionar uma tarefa/gatilho > Tarefas no designer de integração para exibir a lista de tarefas disponíveis.
- Arraste o elemento Para cada paralelo até o designer de integração.
Conectar os elementos de integração
Em seguida, adicione uma conexão de borda para conectar o gatilho da API à tarefa Para cada paralelo.
Para adicionar a conexão de borda, clique no ponto de controle Fork na parte inferior do elemento API Trigger. Arraste e solte a conexão de borda no ponto de controle Mesclar na parte de cima do elemento da tarefa Para cada paralelo.
Configurar a tarefa "Para cada paralelo"
Para configurar a tarefa "Para cada paralelo", siga estas etapas:
- No designer de integração, clique na tarefa Para cada paralelo para conferir o painel de configuração da tarefa.
- Em Seleção de matriz > Lista para iteração, clique em Adicionar nova variável para adicionar uma nova variável.
- Na caixa de diálogo Criar variável, insira os seguintes detalhes:
-
Nome: insira
records
. - Tipo de dado: selecione JSON.
-
Esquema: selecione Inferir de um payload JSON de amostra. Digite o seguinte payload JSON de amostra:
[{ "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)" }]
-
Nome: insira
- Clique em Criar.
- Na seção Detalhes da subintegração, insira as seguintes informações:
- ID do Gatilho da API: selecione o elemento do gatilho da API na subintegração. Por exemplo, selecione Process-each-record_API_1.
- Estratégia de execução: selecione ASYNC.
- Selecione Run a single integration.
- Na seção Em cada execução, em Onde mapear elementos individuais da matriz, insira o nome da variável na tarefa de mapeamento de dados na subintegração. Nesse caso, digite registro. As variáveis de subintegração são listadas apenas para integrações publicadas. Se as variáveis não estiverem listadas, atualize a página. Pode levar algum tempo até que as variáveis fiquem visíveis após a publicação da subintegração.
Publicar a integração principal
Para publicar a integração principal, clique em Publicar no editor.
Testar sua integração
Para testar a integração, siga estas etapas:
- Faça o download dos dados de amostra para o Cloud Shell:
- Para iniciar uma sessão do Cloud Shell no console do Google Cloud,
clique no ícone
Ativar o Cloud Shell no console do Cloud. Isso inicia uma sessão no painel inferior do Cloud Console.
- Insira o comando a seguir no terminal do Cloud Shell.
wget https://raw.githubusercontent.com/GoogleCloudPlatform/application-integration-samples/main/assets/bq-sample-dataset.json
- Para verificar se o download dos dados de amostra foi concluído, digite o seguinte comando no terminal do Cloud Shell:
O arquivo salvo é listado no terminal do Cloud Shell.ls -la bq-sample-dataset.json
- Para iniciar uma sessão do Cloud Shell no console do Google Cloud,
clique no ícone
- Para selecionar três entradas aleatórias do conjunto de dados de amostra e armazená-las de forma que possam ser transmitidas para a integração, digite 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 }
- Para iniciar o teste, digite o seguinte comando no terminal do Cloud Shell:
Neste comando, substitua: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)"
project_id
pelo ID do projeto Google Cloud .region
com a região em que você criou a integração.
- Para verificar se a tabela do BigQuery agora contém esses registros, siga estas etapas:
- Na página do console do Cloud, clique em Menu de navegação.
- Na seção Analytics, clique em BigQuery.
-
Expanda o projeto e clique no conjunto de dados
bq_tutorial
. -
Expanda o conjunto de dados bq_tutorial e clique na tabela
tutorial
. - Clique na guia Explorador de tabelas para conferir os registros inseridos.
A seguir
Tente criar integrações com outros conectores. Para conferir a lista de todos os conectores compatíveis, consulte a Referência de conectores.