以 Python 開始使用 Azure 表格儲存體和 Azure Cosmos DB 資料表 APIGet started with Azure Table storage and the Azure Cosmos DB Table API using Python

適用於: 資料表 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.

Azure 表格儲存體和 Azure Cosmos DB 是可將結構化的 NoSQL 資料儲存在雲端中的服務,並提供具有無結構描述設計的索引鍵/屬性存放區。The Azure Table storage and the Azure Cosmos DB are services that store structured NoSQL data in the cloud, providing a key/attribute store with a schemaless design. 由於表格儲存體和 Azure Cosmos DB 並無結構描述,因此可輕易隨著應用程式發展需求改寫資料。Because Table storage and Azure Cosmos DB are schemaless, it's easy to adapt your data as the needs of your application evolve. 相較於類似資料量的傳統 SQL,對許多類型的應用程式而言,表格儲存體和資料表 API 資料可快速存取且符合成本效益,通常可降低成本。Access to the table storage and table API data is fast and cost-effective for many types of applications, and is typically lower in cost than traditional SQL for similar volumes of data.

您可以使用表格儲存體或 Azure Cosmos DB 來儲存具彈性的資料集,例如 Web 應用程式的使用者資料、通訊錄、裝置資訊,以及服務所需的其他中繼資料類型。You can use the Table storage or the Azure Cosmos DB to store flexible datasets like user data for web applications, address books, device information, or other types of metadata your service requires. 您可以在資料表中儲存任意數目的實體,且儲存體帳戶可包含任意數目的資料表,最高可達儲存體帳戶的容量限制。You can store any number of entities in a table, and a storage account may contain any number of tables, up to the capacity limit of the storage account.

關於此範例About this sample

此範例示範如何在常見的 Azure 表格儲存體案例中使用適用於 Python 的 Azure Cosmos DB 表格 SDK (英文)。This sample shows you how to use the Azure Cosmos DB Table SDK for Python in common Azure Table storage scenarios. SDK 名稱表示其適用於 Azure Cosmos DB,但也同時適用於 Azure Cosmos DB 和 Azure 表格儲存體,兩個服務皆具有唯一的端點。The name of the SDK indicates it is for use with Azure Cosmos DB, but it works with both Azure Cosmos DB and Azure Tables storage, each service just has a unique endpoint. 在這些案例探索中會使用 Python 範例,可說明如何執行下列動作:These scenarios are explored using Python examples that illustrate how to:

  • 建立和刪除表格Create and delete tables
  • 插入和查詢實體Insert and query entities
  • 修改實體Modify entities

在進行此範例中的案例時,您可以參閱 Azure Cosmos DB SDK for Python API 參考資料 (英文)。While working through the scenarios in this sample, you may want to refer to the Azure Cosmos DB SDK for Python API reference.

PrerequisitesPrerequisites

您需要下列項目才能成功完成此範例︰You need the following to complete this sample successfully:

建立 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 表格 API 帳戶Create an Azure Cosmos DB Table API account

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

安裝適用於 Python 的 Azure Cosmos DB 資料表 SDKInstall the Azure Cosmos DB Table SDK for Python

儲存體帳戶已建立後,下一個步驟就是安裝適用於 Python 的 Microsoft Azure Cosmos DB 資料表 SDK (英文)。After you've created a Storage account, your next step is to install the Microsoft Azure Cosmos DB Table SDK for Python. 如需安裝 SDK 的詳細資料,請參閱 GitHub 上 [Cosmos DB Table SDK for Python] 存放庫中的 README.rst 檔案。For details on installing the SDK, refer to the README.rst file in the Cosmos DB Table SDK for Python repository on GitHub.

匯入 TableService 和實體類別Import the TableService and Entity classes

若要在 Python 的 Azure 表格服務中使用實體,可以使用 TableService實體類別。To work with entities in the Azure Table service in Python, you use the TableService and Entity classes. 在靠近您 Python 檔案的頂端處新增此程式碼,以匯入這兩者:Add this code near the top your Python file to import both:

from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity

連線到 Azure 表格服務Connect to Azure Table service

若要連線到 Azure 儲存體表格服務,請建立 TableService 物件,並傳入您的儲存體帳戶名稱和帳戶金鑰。To connect to Azure Storage Table service, create a TableService object, and pass in your Storage account name and account key. 以您的帳戶名稱和金鑰取代 myaccountmykeyReplace myaccount and mykey with your account name and key.

table_service = TableService(account_name='myaccount', account_key='mykey')

連線至 Azure Cosmos DBConnect to Azure Cosmos DB

若要連線到 Azure Cosmos DB,從 Azure 入口網站複製您的主要連接字串,並使用複製的連接字串建立 TableService 物件:To connect to Azure Cosmos DB, copy your primary connection string from the Azure portal, and create a TableService object using your copied connection string:

table_service = TableService(connection_string='DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;TableEndpoint=myendpoint;')

建立資料表Create a table

呼叫 create_table 以建立資料表。Call create_table to create the table.

table_service.create_table('tasktable')

將實體新增至資料表Add an entity to a table

若要新增實體,首先建立一個代表您實體的物件,然後將物件傳遞至 TableService.insert_entity 方法To add an entity, you first create an object that represents your entity, then pass the object to the TableService.insert_entity method. 實體物件可以是字典或類型為 Entity 的物件,並定義您實體的屬性名稱與值。The entity object can be a dictionary or an object of type Entity, and defines your entity's property names and values. 除了您為實體定義的任何其他屬性外。每個實體必須包含必要的 PartitionKey and RowKey 屬性。Every entity must include the required PartitionKey and RowKey properties, in addition to any other properties you define for the entity.

此範例會建立一個代表實體的字典物件,然後將該物件傳遞至 insert_entity 方法,以將它新增至資料表:This example creates a dictionary object representing an entity, then passes it to the insert_entity method to add it to the table:

task = {'PartitionKey': 'tasksSeattle', 'RowKey': '001',
        'description': 'Take out the trash', 'priority': 200}
table_service.insert_entity('tasktable', task)

此範例會建立一個代表實體的物件,然後將該物件傳遞至 insert_entity 方法,以將它新增至資料表:This example creates an Entity object, then passes it to the insert_entity method to add it to the table:

task = Entity()
task.PartitionKey = 'tasksSeattle'
task.RowKey = '002'
task.description = 'Wash the car'
task.priority = 100
table_service.insert_entity('tasktable', task)

PartitionKey 和 RowKeyPartitionKey and RowKey

您必須為每個實體指定 PartitionKeyRowKey 屬性。You must specify both a PartitionKey and a RowKey property for every entity. 這些屬性是您實體的唯一識別碼,共同形成實體的主要索引鍵。These are the unique identifiers of your entities, as together they form the primary key of an entity. 使用這些值查詢的速度遠快於使用任何其他實體屬性查詢,因為系統只會將這些屬性編製索引。You can query using these values much faster than you can query any other entity properties because only these properties are indexed.

表格服務會使用 PartitionKey,以智慧化方式在儲存體節點之間分散資料表實體。The Table service uses PartitionKey to intelligently distribute table entities across storage nodes. 具有相同 PartitionKey 的實體會儲存在相同的節點上。Entities that have the same PartitionKey are stored on the same node. RowKey 是實體在其所屬資料分割內的唯一識別碼。RowKey is the unique ID of the entity within the partition it belongs to.

更新實體Update an entity

若要更新實體的所有屬性值,請呼叫 update_entity 方法。To update all of an entity's property values, call the update_entity method. 此範例說明如何以實體的更新版本取代現有的實體:This example shows how to replace an existing entity with an updated version:

task = {'PartitionKey': 'tasksSeattle', 'RowKey': '001',
        'description': 'Take out the garbage', 'priority': 250}
table_service.update_entity('tasktable', task)

如果正在更新的實體已不存在,則更新操作便會失敗。If the entity that is being updated doesn't already exist, then the update operation will fail. 如果您想要儲存實體,無論其是否存在,請使用 insert_or_replace_entityIf you want to store an entity whether it exists or not, use insert_or_replace_entity. 在下列範例中,第一個呼叫將取代現有實體。In the following example, the first call will replace the existing entity. 第二個呼叫將插入新實體,因為資料表中沒有具有指定 PartitionKey 和 RowKey 的實體存在。The second call will insert a new entity, since no entity with the specified PartitionKey and RowKey exists in the table.

# Replace the entity created earlier
task = {'PartitionKey': 'tasksSeattle', 'RowKey': '001',
        'description': 'Take out the garbage again', 'priority': 250}
table_service.insert_or_replace_entity('tasktable', task)

# Insert a new entity
task = {'PartitionKey': 'tasksSeattle', 'RowKey': '003',
        'description': 'Buy detergent', 'priority': 300}
table_service.insert_or_replace_entity('tasktable', task)

提示

update_entity 方法會取代現有實體其所有的屬性與值,您也可以用它們來移除現有實體的屬性。The update_entity method replaces all properties and values of an existing entity, which you can also use to remove properties from an existing entity. 您可以使用 merge_entity 方法以新的或已修改的屬性值來更新現有的實體,而不完全取代該實體。You can use the merge_entity method to update an existing entity with new or modified property values without completely replacing the entity.

修改多個實體Modify multiple entities

若要確保表格服務對要求的處理為不可部分完成,您可以在一個批次中一起提交多個作業。To ensure the atomic processing of a request by the Table service, you can submit multiple operations together in a batch. 首先,使用 TableBatch 類別將多個作業新增至單一批次。First, use the TableBatch class to add multiple operations to a single batch. 接著,呼叫 TableService.commit_batch 以不可部分完成的作業提交這些作業。Next, call TableService.commit_batch to submit the operations in an atomic operation. 要以批次修改的所有文件必須在同一個分割中。All entities to be modified in batch must be in the same partition.

此範例會在一個批次中同時新增兩個實體:This example adds two entities together in a batch:

from azure.cosmosdb.table.tablebatch import TableBatch
batch = TableBatch()
task004 = {'PartitionKey': 'tasksSeattle', 'RowKey': '004',
           'description': 'Go grocery shopping', 'priority': 400}
task005 = {'PartitionKey': 'tasksSeattle', 'RowKey': '005',
           'description': 'Clean the bathroom', 'priority': 100}
batch.insert_entity(task004)
batch.insert_entity(task005)
table_service.commit_batch('tasktable', batch)

批次也可以與內容管理員語法搭配使用:Batches can also be used with the context manager syntax:

task006 = {'PartitionKey': 'tasksSeattle', 'RowKey': '006',
           'description': 'Go grocery shopping', 'priority': 400}
task007 = {'PartitionKey': 'tasksSeattle', 'RowKey': '007',
           'description': 'Clean the bathroom', 'priority': 100}

with table_service.batch('tasktable') as batch:
    batch.insert_entity(task006)
    batch.insert_entity(task007)

查詢實體Query for an entity

若要查詢資料表中的實體,請將其 PartitionKey 與 RowKey 傳遞至 TableService.get_entity 方法。To query for an entity in a table, pass its PartitionKey and RowKey to the TableService.get_entity method.

task = table_service.get_entity('tasktable', 'tasksSeattle', '001')
print(task.description)
print(task.priority)

查詢實體集合Query a set of entities

您可以提供一個含 filter 參數的篩選字串,來查詢一組實體。You can query for a set of entities by supplying a filter string with the filter parameter. 此範例會對 PartitionKey 套用篩選條件,以尋找西雅圖中的所有工作:This example finds all tasks in Seattle by applying a filter on PartitionKey:

tasks = table_service.query_entities(
    'tasktable', filter="PartitionKey eq 'tasksSeattle'")
for task in tasks:
    print(task.description)
    print(task.priority)

查詢實體屬性的子集Query a subset of entity properties

您也可以限制會為查詢中的每個實體傳回哪些屬性。You can also restrict which properties are returned for each entity in a query. 這項稱為「投射」的技術可減少頻寬並提高查詢效能 (尤其是對大型實體或結果集而言) 。This technique, called projection, reduces bandwidth and can improve query performance, especially for large entities or result sets. 使用 select 參數並傳遞您要傳回到用戶端的屬性名稱。Use the select parameter and pass the names of the properties you want returned to the client.

下列程式碼中的查詢只會傳回資料表中各實體的說明。The query in the following code returns only the descriptions of entities in the table.

注意

下列程式碼片段只針對 Azure 儲存體運作。The following snippet works only against the Azure Storage. 儲存體模擬器並不支援此程式碼片段。It is not supported by the Storage Emulator.

tasks = table_service.query_entities(
    'tasktable', filter="PartitionKey eq 'tasksSeattle'", select='description')
for task in tasks:
    print(task.description)

查詢沒有分割區和資料列索引鍵的實體Query for an entity without partition and row keys

您也可以查詢資料表中的實體,而不需要使用分割區和資料列索引鍵。You can also query for entities within a table without using the partition and row keys. 使用 table_service.query_entities 沒有 "filter" 和 "select" 參數的方法,如下列範例所示:Use the table_service.query_entities method without the "filter" and "select" parameters as show in the following example:

print("Get the first item from the table")
tasks = table_service.query_entities(
    'tasktable')
lst = list(tasks)
print(lst[0])

刪除實體Delete an entity

藉由將實體的 PartitionKeyRowKey 傳遞至 delete_entity 方法,將實體刪除。Delete an entity by passing its PartitionKey and RowKey to the delete_entity method.

table_service.delete_entity('tasktable', 'tasksSeattle', '001')

刪除資料表Delete a table

如果您不再需要資料表及其內的任何實體,請呼叫 delete_table 方法,將資料表永久地從 Azure 儲存體中刪除。If you no longer need a table or any of the entities within it, call the delete_table method to permanently delete the table from Azure Storage.

table_service.delete_table('tasktable')

後續步驟Next steps