Hola, mundo en Ruby

Este código de ejemplo es una aplicación "Hola, mundo" que se ejecuta en Ruby. En el ejemplo se muestra cómo completar las siguientes tareas:

  • Configurar la autenticación
  • Conéctate a una instancia de Bigtable.
  • Crea una tabla.
  • Escribe datos en la tabla.
  • Lee los datos.
  • Elimina la tabla.

Configurar la autenticación

Para usar las Ruby muestras de esta página en un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, a continuación, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    Instala Google Cloud CLI.

    Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

    If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

Para obtener más información, consulta Set up authentication for a local development environment.

Ejecutar la muestra

En este ejemplo de código se usa el paquete biblioteca de cliente de Ruby para Bigtable de la biblioteca de cliente de Google Cloud para Ruby para comunicarse con Bigtable.

Para ejecutar este programa de ejemplo, sigue las instrucciones del ejemplo en GitHub.

Usar la biblioteca de cliente de Cloud con Bigtable

La aplicación de ejemplo se conecta a Bigtable y muestra algunas operaciones sencillas.

Requerir la biblioteca de cliente

La muestra requiere google/cloud/bigtable, que proporciona el módulo Bigtable.

require "google/cloud/bigtable"

Conectarse a Bigtable

Define las variables que vas a usar en tu aplicación y sustituye "YOUR_PROJECT_ID" por el ID de un Google Cloud proyecto válido. A continuación, crea un objeto Bigtable que usarás para conectarte a Bigtable.

# These variables are used in the sample code below.
# instance_id      = "my-instance"
# table_id         = "my-table"
# column_family    = "cf"
# column_qualifier = "greeting"

bigtable = Google::Cloud::Bigtable.new
table_client = bigtable.table_admin_client

Crear una tabla

Comprueba si la tabla ya existe. Si no es así, llama al método create_table() para crear un objeto Table. La tabla tiene una sola familia de columnas que conserva una versión de cada valor.

# This is the full resource name for the table. Use this name to make admin
# calls for the table, such as reading or deleting the resource.
table_name = table_client.table_path project: bigtable.project_id,
                                     instance: instance_id,
                                     table: table_id
begin
  # Attempt to get the table to see if it already exists
  table_client.get_table name: table_name
  puts "#{table_id} is already exists."
  exit 0
rescue Google::Cloud::NotFoundError
  # The table doesn't exist, so let's create it.
  # The following is the resource name for the table's instance.
  instance_name = table_client.instance_path project: bigtable.project_id,
                                             instance: instance_id
  # This is the configuration of the table's column families.
  table_config = {
    column_families: {
      column_family => {
        gc_rule: Google::Cloud::Bigtable::Admin::V2::GcRule.max_num_versions(1)
      }
    }
  }
  # Now call the API to create the table.
  table_client.create_table parent: instance_name,
                            table_id: table_id,
                            table: table_config
  puts "Table #{table_id} created."
end

Escribir filas en una tabla

A continuación, usa una matriz de cadenas de felicitaciones para crear algunas filas nuevas en la tabla. Por cada saludo, crea una entrada con el método new_mutation_entry() de la tabla. A continuación, usa el método set_cell() de la entrada para asignar la familia de columnas, el calificador de columna, el saludo y una marca de tiempo a la entrada. Por último, escribe esa entrada en la tabla mediante el método mutate_row() de la tabla.

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

# Get a table data object for the new table we created.
table = bigtable.table instance_id, table_id

# 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

Crear un filtro

Antes de leer los datos que has escrito, crea un filtro para limitar los datos que devuelve Bigtable. Este filtro indica a Bigtable que devuelva solo la versión más reciente de cada valor, aunque la tabla contenga versiones anteriores que no se hayan recogido como elementos residuales.

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

Leer una fila por su clave de fila

Crea un objeto de fila y, a continuación, llama al método read_row(). Pasa el filtro para obtener una versión de cada valor de esa fila.

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}"

Analizar todas las filas de la tabla

Llama al método read_rows() y pasa el filtro para obtener todas las filas de la tabla. Como has incluido el filtro, Bigtable solo devuelve una versión 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

Eliminar una tabla.

Elimina la tabla con el método delete() de la tabla.

puts "Deleting the table #{table_id}"
# Call the admin API to delete the table given its full resource path.
table_client.delete_table name: table_name

Visión de conjunto

Aquí tienes el ejemplo de código completo sin comentarios.

# 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"

  # These variables are used in the sample code below.
  # instance_id      = "my-instance"
  # table_id         = "my-table"
  # column_family    = "cf"
  # column_qualifier = "greeting"

  bigtable = Google::Cloud::Bigtable.new
  table_client = bigtable.table_admin_client

  # This is the full resource name for the table. Use this name to make admin
  # calls for the table, such as reading or deleting the resource.
  table_name = table_client.table_path project: bigtable.project_id,
                                       instance: instance_id,
                                       table: table_id
  begin
    # Attempt to get the table to see if it already exists
    table_client.get_table name: table_name
    puts "#{table_id} is already exists."
    exit 0
  rescue Google::Cloud::NotFoundError
    # The table doesn't exist, so let's create it.
    # The following is the resource name for the table's instance.
    instance_name = table_client.instance_path project: bigtable.project_id,
                                               instance: instance_id
    # This is the configuration of the table's column families.
    table_config = {
      column_families: {
        column_family => {
          gc_rule: Google::Cloud::Bigtable::Admin::V2::GcRule.max_num_versions(1)
        }
      }
    }
    # Now call the API to create the table.
    table_client.create_table parent: instance_name,
                              table_id: table_id,
                              table: table_config
    puts "Table #{table_id} created."
  end

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

  # Get a table data object for the new table we created.
  table = bigtable.table instance_id, table_id

  # 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}"
  # Call the admin API to delete the table given its full resource path.
  table_client.delete_table name: table_name
end