Ruby Hello World

이 코드 샘플은 Ruby에서 실행되는 'hello world' 애플리케이션입니다. 이 샘플은 다음 작업을 완료하는 방법을 보여줍니다.

  • 인증 설정
  • Bigtable 인스턴스에 연결
  • 새 테이블 만들기
  • 테이블에 데이터 쓰기
  • 데이터 다시 읽기
  • 테이블 삭제

인증 설정

로컬 개발 환경에서 이 페이지의 Ruby 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    Google Cloud CLI를 설치합니다.

    외부 ID 공급업체 (IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

    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.

자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

샘플 실행

이 코드 샘플은 Ruby용 Google Cloud 클라이언트 라이브러리Bigtable용 Ruby 클라이언트 라이브러리를 사용하여 Bigtable과 통신합니다.

이 샘플 프로그램을 실행하려면 GitHub에서 샘플 안내를 따르세요.

Cloud 클라이언트 라이브러리를 Bigtable과 함께 사용

샘플 애플리케이션을 Bigtable에 연결하여 몇 가지 간단한 작업을 보여줍니다.

클라이언트 라이브러리 필요

샘플에는 Bigtable 모듈을 제공하는 google/cloud/bigtable이 필요합니다.

require "google/cloud/bigtable"

Bigtable에 연결

애플리케이션에서 사용할 변수를 설정하고 'YOUR_PROJECT_ID'를 유효한 Google Cloud 프로젝트의 ID로 바꿉니다. 그런 다음 Bigtable에 연결하는 데 사용할 새 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

테이블 만들기

테이블이 이미 있는지 확인합니다. 없는 경우 create_table() 메서드를 호출하여 Table 객체를 만듭니다. 테이블에는 각 값별로 한 버전만 보관하는 column family가 한 개 있습니다.

# 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

테이블에 행 쓰기

그런 다음 인사말 문자열 배열을 사용하여 테이블의 새 행을 만듭니다. 각 인사말에 대해 테이블의 new_mutation_entry() 메서드를 사용하여 항목을 만듭니다. 그런 다음 항목의 set_cell() 메서드를 사용하여 column family, column qualifier, 인사말, 타임스탬프를 항목에 할당합니다. 마지막으로 테이블의 mutate_row() 메서드를 사용하여 테이블에 해당 항목을 씁니다.

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

필터 만들기

작성한 데이터를 읽기 전에 Bigtable이 반환하는 데이터를 제한하는 필터를 생성합니다. 테이블에 가비지로 수집되지 않은 이전 버전이 있더라도 이 필터는 각 값의 최신 버전만 반환하도록 Bigtable에 지시합니다.

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

row key를 통해 행 읽기

행 객체를 만든 다음 read_row() 메서드를 호출하고 필터를 전달하여 이 행에서 각 값의 버전 하나를 가져옵니다.

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

모든 테이블 행 검색

read_rows() 메서드를 호출하고 필터를 전달하여 테이블의 모든 행을 가져옵니다. 필터를 전달했으므로 Bigtable은 각 값별로 버전 1개만 반환합니다.

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

테이블 삭제

테이블의 delete() 메서드를 사용하여 테이블을 삭제합니다.

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

요약 정리

다음은 주석이 없는 전체 코드 샘플입니다.

# 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