如何配合使用 Ruby 和 Azure 表存储How to use Azure Table Storage with Ruby

Tip

本文中的内容适用于 Azure 表存储和 Azure Cosmos DB 表 API。The content in this article applies to Azure Table storage and the Azure Cosmos DB Table API. Azure Cosmos DB 表 API 是表存储的高级产品,可提供吞吐量优化表、全局分发和自动辅助索引。The Azure Cosmos DB Table API is a premium offering for table storage that offers throughput-optimized tables, global distribution, and automatic secondary indexes.

概述Overview

本指南演示如何使用 Azure 表服务执行常见任务。This guide shows you how to perform common scenarios using Azure Table service. 示例是采用 Ruby 编写的,并使用了用于 Ruby 的 Azure 存储表客户端库The samples are written in Ruby and use the Azure Storage Table Client Library for Ruby. 涉及的方案包括创建和删除表、在表中插入和查询条目。The scenarios covered include creating and deleting a table, and inserting and querying entities in a table.

创建 Azure 服务帐户Create an Azure service account

可以通过 Azure 表存储使用表。You can work with tables using Azure Table storage. 需要为所要使用的服务创建一个帐户。You'll need to create an account for the service you're going to use.

创建 Azure 存储帐户Create an Azure storage account

创建第一个 Azure 存储帐户的最简单方法是使用 Azure 门户The easiest way to create your first Azure storage account is by using the Azure portal. 若要了解更多信息,请参阅 创建存储帐户To learn more, see Create a storage account.

也可以使用 Azure PowerShellAzure CLI 创建 Azure 存储帐户。You can also create an Azure storage account by using Azure PowerShell or Azure CLI.

如果暂时不想创建存储帐户,也可以使用 Azure 存储模拟器在本地环境中运行和测试代码。If you prefer not to create a storage account at this time, you can also use the Azure storage emulator to run and test your code in a local environment. 有关详细信息,请参阅 使用 Azure 存储模拟器进行开发和测试For more information, see Use the Azure Storage Emulator for Development and Testing.

添加对存储的访问权限Add access to Storage

若要使用 Azure 存储,必须下载和使用 Ruby Azure 包,其中包括一组便于与表 REST 服务进行通信的库。To use Azure Storage, you must download and use the Ruby Azure package that includes a set of convenience libraries that communicate with the Table REST services.

使用 RubyGems 获取该程序包Use RubyGems to obtain the package

  1. 使用命令行接口,例如 PowerShell (Windows)、Terminal (Mac) 或 Bash (Unix)。Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Unix).
  2. 在命令窗口中键入“gem install azure-storage-blob”以安装 gem 和依赖项。Type gem install azure-storage-table in the command window to install the gem and dependencies.

导入包Import the package

使用常用的文本编辑器将以下内容添加到要在其中使用存储的 Ruby 文件的顶部:Use your favorite text editor, add the following to the top of the Ruby file where you intend to use Storage:

require "azure/storage/table"

添加 Azure 存储连接Add an Azure Storage connection

Azure 存储模块读取环境变量 AZURE_STORAGE_ACCOUNT 和 AZURE_STORAGE_ACCESS_KEY 以获取连接到 Azure 存储器帐户所需的信息。The Azure Storage module reads the environment variables AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY for information required to connect to your Azure Storage account. 如果未设置这些环境变量,则在使用 Azure::Storage::Table::TableService 之前必须通过以下代码指定帐户信息:If these environment variables are not set, you must specify the account information before using Azure::Storage::Table::TableService with the following code:

Azure.config.storage_account_name = "<your Azure Storage account>"
Azure.config.storage_access_key = "<your Azure Storage access key>"
Azure.config.storage_endpoint_suffix = "core.chinacloudapi.cn"

从 Azure 门户中的经典或 Resource Manager 存储帐户中获取这些值:To obtain these values from a classic or Resource Manager storage account in the Azure portal:

  1. 登录到 Azure 门户Log in to the Azure portal.
  2. 导航到要使用的存储帐户。Navigate to the Storage account you want to use.
  3. 在右侧的“设置”边栏选项卡中,单击“访问密钥” 。In the Settings blade on the right, click Access Keys.
  4. 在显示的“访问密钥”边栏选项卡中,可看到访问密钥 1 和访问密钥 2。In the Access keys blade that appears, you'll see the access key 1 and access key 2. 可以使用其中任意一个密钥。You can use either of these.
  5. 单击复制图标以将密钥复制到剪贴板。Click the copy icon to copy the key to the clipboard.

创建表Create a table

使用 Azure::Storage::Table::TableService 对象可以对表和实体进行操作。The Azure::Storage::Table::TableService object lets you work with tables and entities. 要创建表,请使用 create_table() 方法。To create a table, use the create_table() method. 以下示例创建表或输出存在的错误。The following example creates a table or prints the error if there is any.

azure_table_service = Azure::Storage::Table::TableService.new
begin
    azure_table_service.create_table("testtable")
rescue
    puts $!
end

向表中添加条目Add an entity to a table

若要添加条目,应首先创建定义条目属性的哈希对象。To add an entity, first create a hash object that defines your entity properties. 请注意,必须为每个实体指定 PartitionKey 和 RowKey。Note that for every entity you must specify a PartitionKey and RowKey. 这些值是实体的唯一标识符,并且查询它们比查询其他属性快很多。These are the unique identifiers of your entities, and are values that can be queried much faster than your other properties. Azure 存储使用 PartitionKey 将表的实体自动分发到多个存储节点。Azure Storage uses PartitionKey to automatically distribute the table's entities over many storage nodes. 具有相同 PartitionKey 的条目存储在同一个节点上。Entities with the same PartitionKey are stored on the same node. RowKey 是条目在其所属分区内的唯一 ID。The RowKey is the unique ID of the entity within the partition it belongs to.

entity = { "content" => "test entity",
    :PartitionKey => "test-partition-key", :RowKey => "1" }
azure_table_service.insert_entity("testtable", entity)

更新条目Update an entity

可使用多种方法来更新现有条目:There are multiple methods available to update an existing entity:

  • update_entity(): 通过替换更新现有实体。update_entity(): Update an existing entity by replacing it.
  • merge_entity(): 通过将新属性值合并到现有实体来更新现有实体。merge_entity(): Updates an existing entity by merging new property values into the existing entity.
  • insert_or_merge_entity(): 通过替换现有实体来更新现有实体。insert_or_merge_entity(): Updates an existing entity by replacing it. 如果不存在条目,则插入新条目:If no entity exists, a new one will be inserted:
  • insert_or_replace_entity(): 通过将新属性值合并到现有实体来更新现有实体。insert_or_replace_entity(): Updates an existing entity by merging new property values into the existing entity. 如果不存在条目,则插入新条目。If no entity exists, a new one will be inserted.

以下示例演示使用 update_entity() 更新实体:The following example demonstrates updating an entity using update_entity():

entity = { "content" => "test entity with updated content",
    :PartitionKey => "test-partition-key", :RowKey => "1" }
azure_table_service.update_entity("testtable", entity)

对于 update_entity() 和 merge_entity(),如果要更新的实体不存在,更新操作会失败。With update_entity() and merge_entity(), if the entity that you are updating doesn't exist then the update operation will fail. 因此,如果想要存储某个实体而不考虑它是否已存在,则应改用 insert_or_replace_entity() 或 insert_or_merge_entity()。Therefore, if you want to store an entity regardless of whether it already exists, you should instead use insert_or_replace_entity() or insert_or_merge_entity().

使用实体组Work with groups of entities

有时,有必要成批地同时提交多项操作以确保通过服务器进行原子处理。Sometimes it makes sense to submit multiple operations together in a batch to ensure atomic processing by the server. 若要完成此操作,首先要创建一个 Batch 对象,然后对 TableService 使用 execute_batch() 方法。To accomplish that, you first create a Batch object and then use the execute_batch() method on TableService. 以下示例演示在一个批次中提交 RowKey 为 2 和 3 的两个条目。The following example demonstrates submitting two entities with RowKey 2 and 3 in a batch. 请注意,此操作仅适用于具有相同 PartitionKey 的条目。Notice that it only works for entities with the same PartitionKey.

azure_table_service = Azure::TableService.new
batch = Azure::Storage::Table::Batch.new("testtable",
    "test-partition-key") do
    insert "2", { "content" => "new content 2" }
    insert "3", { "content" => "new content 3" }
end
results = azure_table_service.execute_batch(batch)

查询条目Query for an entity

若要查询表中的实体,请传递表名称、PartitionKey 和 RowKey使用 get_entity() 方法。To query an entity in a table, use the get_entity() method, by passing the table name, PartitionKey and RowKey.

result = azure_table_service.get_entity("testtable", "test-partition-key",
    "1")

查询一组条目Query a set of entities

若要查询表中的一组实体,请创建查询哈希对象并使用 query_entities() 方法。To query a set of entities in a table, create a query hash object and use the query_entities() method. 以下示例演示如何获取具有相同 PartitionKey的所有条目:The following example demonstrates getting all the entities with the same PartitionKey:

query = { :filter => "PartitionKey eq 'test-partition-key'" }
result, token = azure_table_service.query_entities("testtable", query)

Note

如果结果集太大,一个查询无法全部返回,则返回一个继续标记,可以使用该标记检索后续页面。If the result set is too large for a single query to return, a continuation token is returned that you can use to retrieve subsequent pages.

查询一部分实体属性Query a subset of entity properties

对表的查询可以只检索条目的几个属性。A query to a table can retrieve just a few properties from an entity. 这种技术称为“投影”,可减少带宽并提高查询性能,尤其适用于大型条目。This technique, called "projection", reduces bandwidth and can improve query performance, especially for large entities. 请使用 select 子句并传递希望显示给客户端的属性的名称。Use the select clause and pass the names of the properties you would like to bring over to the client.

query = { :filter => "PartitionKey eq 'test-partition-key'",
    :select => ["content"] }
result, token = azure_table_service.query_entities("testtable", query)

删除条目Delete an entity

若要删除实体,请使用 delete_entity() 方法。To delete an entity, use the delete_entity() method. 传入包含该实体的表的名称、实体的 PartitionKey 和 RowKey。Pass in the name of the table that contains the entity, the PartitionKey, and the RowKey of the entity.

azure_table_service.delete_entity("testtable", "test-partition-key", "1")

删除表Delete a table

若要删除表,请使用 delete_table() 方法并传入要删除的表的名称。To delete a table, use the delete_table() method and pass in the name of the table you want to delete.

azure_table_service.delete_table("testtable")

后续步骤Next steps