Hello World em Ruby

Esse exemplo de código é um aplicativo "Hello World" executado no Ruby. Ela mostra como concluir as seguintes tarefas:

  • Configurar a autenticação
  • Conectar-se a uma instância do Bigtable.
  • criar uma nova tabela;
  • Gravação de dados na tabela
  • Leitura dos dados
  • Exclusão da tabela

Configurar a autenticação

Para usar as amostras de Ruby nesta página de um ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure o Application Default Credentials com as credenciais de usuário.

  1. Instale a CLI do Google Cloud.
  2. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  3. Crie as credenciais de autenticação para sua Conta do Google:

    gcloud auth application-default login

Veja mais informações em: Configurar a autenticação para um ambiente de desenvolvimento local.

Como executar a amostra

Este exemplo de código usa o pacote da biblioteca de cliente do Ruby para Bigtable da biblioteca de cliente do Google Cloud para Ruby a fim de se comunicar com o Bigtable.

Para executar este programa de amostra, siga as instruções do exemplo no GitHub.

Como usar a biblioteca de cliente do Cloud com o Bigtable

O aplicativo de amostra conecta-se ao Bigtable e demonstra algumas operações simples.

Como solicitar a biblioteca de cliente

A amostra requer google/cloud/bigtable, que fornece o módulo Bigtable.

require "google/cloud/bigtable"

Como se conectar ao Bigtable

Estabeleça as variáveis que você usará no aplicativo, substituindo “YOUR_PROJECT_ID” pelo ID de um projeto do Google Cloud válido. Em seguida, crie um novo objeto Bigtable que você usará para se conectar ao Bigtable.

# instance_id      = "my-instance"
# table_id         = "my-table"
# column_family    = "cf"
# column_qualifier = "greeting"

bigtable = Google::Cloud::Bigtable.new

Como criar uma tabela

Verifique se a tabela já existe. Se ela ainda não existir, chame o método create_table() para criar um objeto Table. A tabela tem um único grupo de colunas que retém uma versão de cada valor.

if bigtable.table(instance_id, table_id).exists?
  puts "#{table_id} is already exists."
  exit 0
else
  table = bigtable.create_table instance_id, table_id do |column_families|
    column_families.add(
      column_family,
      Google::Cloud::Bigtable::GcRule.max_versions(1)
    )
  end

  puts "Table #{table_id} created."
end

Como gravar linhas em uma tabela

Em seguida, use uma matriz de strings de saudações para criar novas linhas para a tabela. Para cada saudação, crie uma entrada usando o método new_mutation_entry() da tabela. Em seguida, use o método set_cell() da entrada para atribuir a ela o grupo de colunas, o qualificador de coluna, a saudação e um carimbo de data\hora. Por fim, grave essa entrada na tabela usando o método mutate_row().

puts "Write some greetings to the table #{table_id}"
greetings = ["Hello World!", "Hello Bigtable!", "Hello Ruby!"]

# Insert rows one by one
# Note: To perform multiple mutation on multiple rows use `mutate_rows`.
greetings.each_with_index do |value, i|
  puts " Writing,  Row key: greeting#{i}, Value: #{value}"

  entry = table.new_mutation_entry "greeting#{i}"
  entry.set_cell(
    column_family,
    column_qualifier,
    value,
    timestamp: (Time.now.to_f * 1_000_000).round(-3)
  )

  table.mutate_row entry
end

Como criar um filtro

Antes de ler os dados que você gravou, crie um filtro para limitar os dados que o Bigtable retorna. Com esse filtro, o Bigtable retornará apenas a versão mais recente de cada valor, mesmo que a tabela contenha versões mais antigas que não tenham sido coletadas como lixo.

# Only retrieve the most recent version of the cell.
filter = Google::Cloud::Bigtable::RowFilter.cells_per_column 1

Como ler uma linha pela chave dela

Crie um objeto row e chame o método read_row(), transmitindo o filtro para receber uma versão de cada valor dessa linha.

puts "Reading a single row by row key"
row = table.read_row "greeting0", filter: filter
puts "Row key: #{row.key}, Value: #{row.cells[column_family].first.value}"

Como verificar todas as linhas da tabela

Chame o método read_rows(), transmitindo o filtro para receber todas as linhas dessa tabela. Como você transmitiu no filtro, o Bigtable retornará apenas uma versão de cada valor.

puts "Reading the entire table"
table.read_rows.each do |row|
  puts "Row key: #{row.key}, Value: #{row.cells[column_family].first.value}"
end

Como excluir tabelas

Exclua a tabela com o método delete().

puts "Deleting the table #{table_id}"
table.delete

Como tudo funciona em conjunto

Veja o exemplo de código completo sem comentários.

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def hello_world instance_id, table_id, column_family, column_qualifier
  require "google/cloud/bigtable"

  # instance_id      = "my-instance"
  # table_id         = "my-table"
  # column_family    = "cf"
  # column_qualifier = "greeting"

  bigtable = Google::Cloud::Bigtable.new

  if bigtable.table(instance_id, table_id).exists?
    puts "#{table_id} is already exists."
    exit 0
  else
    table = bigtable.create_table instance_id, table_id do |column_families|
      column_families.add(
        column_family,
        Google::Cloud::Bigtable::GcRule.max_versions(1)
      )
    end

    puts "Table #{table_id} created."
  end

  puts "Write some greetings to the table #{table_id}"
  greetings = ["Hello World!", "Hello Bigtable!", "Hello Ruby!"]

  # Insert rows one by one
  # Note: To perform multiple mutation on multiple rows use `mutate_rows`.
  greetings.each_with_index do |value, i|
    puts " Writing,  Row key: greeting#{i}, Value: #{value}"

    entry = table.new_mutation_entry "greeting#{i}"
    entry.set_cell(
      column_family,
      column_qualifier,
      value,
      timestamp: (Time.now.to_f * 1_000_000).round(-3)
    )

    table.mutate_row entry
  end

  # Only retrieve the most recent version of the cell.
  filter = Google::Cloud::Bigtable::RowFilter.cells_per_column 1

  puts "Reading a single row by row key"
  row = table.read_row "greeting0", filter: filter
  puts "Row key: #{row.key}, Value: #{row.cells[column_family].first.value}"

  puts "Reading the entire table"
  table.read_rows.each do |row|
    puts "Row key: #{row.key}, Value: #{row.cells[column_family].first.value}"
  end

  puts "Deleting the table #{table_id}"
  table.delete
end