Ruby 版 Hello World
本代码示例是一个在 Ruby 上运行的“hello world”应用,其中演示了如何完成以下任务:
- 设置身份验证
- 连接到 Bigtable 实例。
- 新建一个表。
- 将数据写入表中。
- 重新读取这些数据。
- 删除表。
设置身份验证
如需在本地开发环境中使用本页面上的 Ruby 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
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。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC。
运行示例
此代码示例使用 Ruby 版 Google Cloud 客户端库的适用于 Bigtable 的 Ruby 客户端库软件包与 Bigtable 通信。
要运行此示例程序,请按照 GitHub 上的相应示例说明执行操作。
将 Cloud 客户端库与 Bigtable 搭配使用
示例应用会连接到 Bigtable 并演示一些简单操作。
需要客户端库
该示例需要使用 google/cloud/bigtable
,其中提供了 Bigtable
模块。
连接到 Bigtable
建立您要在应用中使用的变量,并将“YOUR_PROJECT_ID”替换为有效 Google Cloud 项目的 ID。然后,创建一个新的 Bigtable
对象,您将使用此对象连接到 Bigtable。
创建表
检查您的表是否已存在。如果不存在,请调用 create_table()
方法来创建一个 Table
对象。该表有一个列族,其中保留了每个值的一个版本。
将行写入表
接下来,使用由问候语组成的字符串数组来为表创建一些新行。对于每条问候语,使用表的 new_mutation_entry()
方法创建一个条目。然后,使用条目的 set_cell()
方法为该条目分配列族、列限定符、问候语和时间戳。最后,使用表的 mutate_row()
方法将该条目写入表中。
创建过滤条件
在读取您写入的数据之前,请创建过滤条件,以限制 Bigtable 返回的数据。此过滤条件指示 Bigtable 仅返回每个值的最新版本,即使该表包含尚未被垃圾回收的旧版本。
按行键读取行
创建一个行对象,然后调用 read_row()
方法并传入过滤条件,以获取该行中每个值的一个版本。
扫描所有表行
调用 read_rows()
方法并传入过滤条件,以获取表中的所有行。由于您传入了过滤条件,因此 Bigtable 仅会返回每个值的一个版本。
删除表
使用表的 delete()
方法删除表。
综合应用
以下为不包含注释的完整代码示例。