如何搭配 Ruby 使用 Azure 表格儲存體和 Azure Cosmos DB 資料表 APIHow to use Azure Table Storage and the Azure Cosmos DB Table API with Ruby

適用於: 資料表 API

提示

本文中的內容適用於 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.

本文說明如何建立資料表、儲存您的資料,以及對資料執行 CRUD 作業。This article shows you how to create tables, store your data, and perform CRUD operations on the data. 選擇 Azure 資料表服務或 Azure Cosmos DB 資料表 API。Choose either the Azure Table service or the Azure Cosmos DB Table API. 本文中說明的範例是以 Ruby 撰寫的,並且使用 適用於 Ruby 的 Azure 儲存體資料表用戶端程式庫The samples described in this article are written in Ruby and uses the Azure Storage Table Client Library for Ruby. 涵蓋的案例包括建立資料表、刪除資料表、插入實體,以及查詢資料表中的實體。The scenarios covered include create a table, delete a table, insert entities, and query entities from the table.

建立 Azure 服務帳戶Create an Azure service account

您可以使用 Azure 表格儲存體或 Azure Cosmos DB 來搭配使用表格。You can work with tables using the Azure Table storage or the Azure Cosmos DB. 若要深入了解這兩項服務中的資料表供應項目間的差異,請參閱資料表供應項目一文。To learn more about the differences between table offerings in these two services, see the Table offerings article. 您必須為您要使用的服務建立帳戶。You'll need to create an account for the service you're going to use. 下列各節說明如何建立 Azure 資料表儲存體和 Azure Cosmos DB 帳戶,不過您可以只使用其中一個。The following sections show how to create both Azure Table storage and the Azure Cosmos DB account, however you can just use one of them.

建立 Azure 儲存體帳戶Create an Azure storage account

建立 Azure 儲存體帳戶最簡單的方法,就是使用 Azure 入口網站The easiest way to create an 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.

建立 Azure Cosmos DB 帳戶Create an Azure Cosmos DB account

有關建立 Azure Cosmos DB 資料表 API 帳戶的指示,請參閱建立表格資料庫帳戶For instructions on creating an Azure Cosmos DB Table API account, see Create a database account.

新增對 Azure 儲存體或 Azure Cosmos DB 的存取權Add access to Azure storage or Azure Cosmos DB

若要使用「Azure 儲存體」或 Azure Cosmos DB,您必須下載並使用 Ruby Azure 套件,這包含一組能夠與「資料表 REST」服務進行通訊的便利程式庫。To use Azure Storage or Azure Cosmos DB, 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-table 以安裝 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"

新增連接字串Add your connection string

您可以連線到 Azure 儲存體帳戶或 Azure Cosmos DB 資料表 API 帳戶。You can either connect to the Azure storage account or the Azure Cosmos DB Table API account. 根據您使用的帳戶類型,取得連接字串。Get the connection string based on the type of account you are using.

新增 Azure 儲存體連線Add an Azure Storage connection

「Azure 儲存體」模組會讀取環境變數 AZURE_STORAGE_ACCOUNTAZURE_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 入口網站中的傳統或 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.

新增 Azure Cosmos DB 連線Add an Azure Cosmos DB connection

若要連線至 Azure Cosmos DB,請從 Azure 入口網站複製您的主要連接字串,然後使用所複製的連接字串來建立 Client 物件。To connect to Azure Cosmos DB, copy your primary connection string from the Azure portal, and create a Client object using your copied connection string. 您可以在建立 TableService 物件時傳遞 Client 物件:You can pass the Client object when you create a TableService object:

common_client = Azure::Storage::Common::Client.create(storage_account_name:'myaccount', storage_access_key:'mykey', storage_table_host:'mycosmosdb_endpoint')
table_client = Azure::Storage::Table::TableService.new(client: common_client)

建立資料表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. 請注意,對每個實體都必須指定 PartitionKeyRowKeyNote 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 是實體在其所屬資料分割內的唯一識別碼。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

若要查詢資料表中的實體,請使用 get_entity() 方法,藉由傳遞資料表名稱、PartitionKeyRowKey 來進行。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)

注意

如果結果集太大,以致單一查詢無法傳回,則會傳回接續 Token,供您用來擷取後續的頁面。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