Crie uma instância e escreva dados com a CLI cbt

Se estiver a aprender sobre o Bigtable, pode trabalhar num início rápido para ter uma ideia dos princípios básicos que usaria em grande escala num ambiente de produção.

Neste início rápido, vai realizar as seguintes ações:

  • Estabeleça ligação a uma instância do Bigtable.
  • Realizar tarefas administrativas básicas.
  • Escrever dados numa tabela.
  • Ler dados de uma tabela.

Antes de começar

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  4. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Bigtable and Cloud Bigtable Admin APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable bigtable.googleapis.com bigtableadmin.googleapis.com
  8. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/bigtable.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  9. Install the Google Cloud CLI.

  10. Se estiver a usar um fornecedor de identidade (IdP) externo, tem primeiro de iniciar sessão na CLI gcloud com a sua identidade federada.

  11. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  12. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Verify that billing is enabled for your Google Cloud project.

  14. Enable the Cloud Bigtable and Cloud Bigtable Admin APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable bigtable.googleapis.com bigtableadmin.googleapis.com
  15. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/bigtable.admin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  16. Execute o seguinte comando para instalar a CLI cbt:
    gcloud components install cbt
  17. Crie uma instância do Bigtable

    1. Abra a página Criar instância na Google Cloud consola.

      Crie uma instância

    2. Em Nome da instância, introduza Quickstart instance.

    3. Para o ID da instância, introduza quickstart-instance.

    4. Clique em Continuar.

    5. Para Tipo de armazenamento, selecione SSD.

    6. Clique em Continuar.

    7. Para ID do cluster, introduza quickstart-instance-c1.

    8. Para Região, selecione uma região perto de si.

    9. Para Zona, selecione Qualquer.

    10. Para o Modo de dimensionamento de nós, escolha Atribuição manual.

    11. Para Quantidade, selecione 1.

    12. Clique em Criar para criar a instância.

    Associe-se à sua instância

    1. Configure a CLI cbt para usar o seu projeto e instância criando um ficheiro .cbtrc, substituindo PROJECT_ID pelo ID do projeto onde criou a instância do Bigtable:

      echo project = PROJECT_ID >> ~/.cbtrc && echo instance = quickstart-instance >> ~/.cbtrc
      
    2. Confirme que configurou o ficheiro .cbtrc corretamente:

      cat ~/.cbtrc

      O terminal apresenta o conteúdo do ficheiro .cbtrc, que tem um aspeto semelhante ao seguinte:

      project = PROJECT_ID
      instance = quickstart-instance

      Agora, pode usar a cbt CLI com a sua instância.

    Ler e escrever dados

    O Bigtable armazena dados em tabelas, que contêm linhas. Cada linha é identificada por uma chave de linha.

    Os dados numa linha estão organizados em famílias de colunas, que são grupos de colunas. Um qualificador de coluna identifica uma única coluna numa família de colunas.

    Pode haver várias células com indicação de data/hora na interseção de uma linha e uma coluna.

    1. Cria uma tabela com o nome my-table.

      cbt createtable my-table
    2. Apresentar uma lista das suas tabelas:

      cbt ls

      O comando apresenta um resultado semelhante ao seguinte:

          my-table

    3. Adicione uma família de colunas com o nome cf1:

      cbt createfamily my-table cf1
    4. Liste as suas famílias de colunas:

      cbt ls my-table

      O comando apresenta um resultado semelhante ao seguinte:

          Family Name     GC Policy
          -----------     ---------
          cf1             <never>

    5. Escreva os valores test-value1 e test-value2 na linha r1, usando a família de colunas cf1 e o qualificador de coluna c1:

      cbt set my-table r1 cf1:c1=test-value1
        cbt set my-table r1 cf1:c1=test-value2
      
    6. Use o comando cbt read para ler os dados que adicionou à tabela:

      cbt read my-table

      A shell apresenta um resultado semelhante ao seguinte:

          ----------------------------------------
          r1
            cf1:c1                                   @ 2023/03/22-06:56:11.323000
              "test-value1"
            cf1:c1                                   @ 2023/03/22-06:56:04.361000
              "test-value2"

      São armazenados dois valores com data/hora para a mesma coluna na linha r1.

    Limpar

    Para evitar incorrer em cobranças na sua conta do Google Cloud pelos recursos usados neste início rápido, elimine a instância. A eliminação do ficheiro .cbtrc deixa-o preparado para trabalhar num projeto diferente.

    1. Elimine a tabela my-table:

      cbt deletetable my-table
    2. Elimine a instância:

      cbt deleteinstance quickstart-instance
    3. Elimine o ficheiro .cbtrc:

      rm ~/.cbtrc

    4. Opcional: revogue as credenciais da CLI gcloud:

      gcloud auth revoke

    O que se segue?