Ruby Hello World

Bei diesem Codebeispiel handelt es sich um eine "Hello World"-Anwendung in Ruby. Das Beispiel veranschaulicht die folgenden Aufgaben:

  • Authentifizierung einrichten
  • Verbindung zu einer Bigtable-Instanz herstellen
  • Erstellen einer neuen Tabelle
  • Schreiben von Daten in die Tabelle
  • Lesen von Daten aus der Tabelle
  • Löschen einer Tabelle

Authentifizierung einrichten

Wenn Sie die Ruby Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

  1. Install the Google Cloud CLI.
  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. 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, confirm that you have configured the gcloud CLI to use Workforce Identity Federation.

Weitere Informationen unter Set up authentication for a local development environment.

Beispiel ausführen

In diesem Codebeispiel wird das Paket Ruby-Clientbibliothek für Bigtable der Google Cloud-Clientbibliothek für Ruby verwendet, um mit Bigtable zu kommunizieren.

Folgen Sie zur Ausführung dieses Beispielprogramms der Anleitung für das Beispiel auf GitHub.

Cloud-Clientbibliothek mit Bigtable verwenden

Die Beispielanwendung stellt eine Verbindung zu Bigtable her und zeigt einige einfache Vorgänge.

Clientbibliothek anfordern

In diesem Beispiel ist google/cloud/bigtable zur Bereitstellung des Bigtable-Moduls erforderlich.

require "google/cloud/bigtable"

Verbindung zu Bigtable herstellen

Legen Sie die Variablen fest, die Sie in der Anwendung verwenden möchten. Ersetzen Sie dabei „YOUR_PROJECT_ID“ durch die ID eines gültigen Google Cloud -Projekts. Erstellen Sie dann ein neues Bigtable-Objekt, mit dem Sie eine Verbindung zu Bigtable herstellen.

# 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

Tabelle erstellen

Prüfen Sie, ob die Tabelle bereits vorhanden ist. Ist dies nicht der Fall, rufen Sie die Methode create_table() auf, um ein Table-Objekt zu erstellen. Die Tabelle enthält eine einzelne Spaltenfamilie, in der eine Version jedes Wertes gespeichert ist.

# 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

Zeilen in eine Tabelle schreiben

Verwenden Sie als Nächstes ein String-Array mit Begrüßungen, um neue Zeilen für die Tabelle zu erstellen. Erstellen Sie mithilfe der Methode new_mutation_entry() der Tabelle für jede Begrüßung einen Eintrag. Verwenden Sie als Nächstes die Methode set_cell() des Eintrags, um dem Eintrag die Spaltenfamilie, den Spaltenqualifizierer, die Begrüßung und einen Zeitstempel zuzuweisen. Schreiben Sie zuletzt mit der Methode mutate_row() der Tabelle diesen Eintrag in die Tabelle.

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

Filter erstellen

Erstellen Sie vor dem Lesen der von Ihnen geschriebenen Daten einen Filter, um die von Bigtable zurückgegebenen Daten zu beschränken. Mit diesem Filter wird Bigtable angewiesen, nur die neueste Version jedes Werts zurückzugeben, auch wenn die Tabelle ältere Versionen enthält, die noch nicht automatisch bereinigt wurden.

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

Zeile über ihren Zeilenschlüssel lesen

Erstellen Sie ein Zeilenobjekt und rufen Sie dann die Methode read_row() auf. Übergeben Sie dabei den Filter, um eine Version jedes Werts in dieser Zeile abzurufen.

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

Alle Tabellenzeilen scannen

Rufen Sie die Methode read_rows() auf, die den Filter übergibt, um alle Zeilen in der Tabelle zu erhalten. Durch Übergabe des Filters gibt Bigtable nur eine Version jedes Werts zurück.

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

Tabelle löschen

Mit der Methode delete() der Tabelle löschen Sie die Tabelle.

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

Zusammenfassung

Im Folgenden ist das vollständige Codebeispiel ohne Kommentare aufgeführt.

# 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