Introduction
Azure Storage Tables is a NoSQL key-attribute store that allows you to store large amounts of structured data. It's ideal for applications that need a flexible schema and high availability. This guide will walk you through the essential steps to get started with Azure Storage Tables.
Tables are a powerful and cost-effective way to store semi-structured data in the cloud. They offer high scalability and durability, making them suitable for a wide range of applications, from web-scale services to enterprise data solutions.
Prerequisites
Before you begin, ensure you have the following:
- An active Azure account.
- The Azure CLI installed (optional, but recommended for quick setup).
- An Azure Storage SDK for your preferred programming language (e.g., .NET, Python, Node.js, Java).
Creating a Storage Account
A storage account is the foundation for all your Azure Storage data objects. You'll need one before you can create tables.
Using the Azure Portal
- Sign in to the Azure portal.
- Click on Create a resource.
- Search for Storage account and select it.
- Click Create.
- Fill in the required details: Subscription, Resource group, Storage account name (globally unique), Region, and Performance (Standard recommended for tables).
- Under Advanced tab, ensure Table storage is enabled.
- Review and create the storage account.
Using Azure CLI
You can create a storage account using the Azure CLI with the following command:
az storage account create \
--name mystoragetablesaccount \
--resource-group myResourceGroup \
--location eastus \
--sku Standard_LRS \
--kind StorageV2
Replace mystoragetablesaccount and myResourceGroup with your desired names.
Creating a Table
Once you have a storage account, you can create tables within it. Tables are collections of entities, and entities are groups of properties. Each entity has a PartitionKey and a RowKey, which together uniquely identify it.
Using SDKs
Here's an example using the Azure Storage Table SDK for Python:
from azure.data.tables import TableServiceClient
connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING" # Get this from your storage account keys
table_name = "MyTestTable"
try:
table_service_client = TableServiceClient.from_connection_string(connection_string)
table = table_service_client.create_table(table_name)
print(f"Table '{table_name}' created successfully.")
except Exception as e:
print(f"Error creating table: {e}")
YOUR_AZURE_STORAGE_CONNECTION_STRING with your actual connection string found in the Azure portal under your storage account's "Access keys".
Using REST API
You can also create tables using the Azure Storage REST API. This involves sending an HTTP PUT request to the table endpoint.
PUT /MyTestTable HTTP/1.1
Host: mystoragetablesaccount.table.core.windows.net
Content-Type: application/json;odata=nometadata
Authorization: SharedKey mystoragetablesaccount:YOUR_SIGNATURE
Date: Tue, 27 Oct 2023 00:00:00 GMT
x-ms-version: 2019-02-02
{
"TableName": "MyTestTable"
}
Authentication and signature generation for the REST API can be complex and are typically handled by SDKs.
Adding Data (Entities)
Entities are the basic units of data in Azure Tables. They are composed of properties, each with a name and a value. Two special properties, PartitionKey and RowKey, uniquely identify each entity.
Here's how to add an entity using the Python SDK:
from azure.data.tables import TableClient, EdmType
# ... (previous code for connection string and table client)
entity = {
"PartitionKey": "Users",
"RowKey": "user123",
"Name": "Alice Smith",
"Email": "alice.smith@example.com",
"Age": 30,
"IsActive": True
}
try:
table_client = TableClient.from_connection_string(connection_string, table_name)
created_entity = table_client.upsert_entity(entity)
print(f"Entity created successfully: {created_entity}")
except Exception as e:
print(f"Error adding entity: {e}")
upsert_entity method will create the entity if it doesn't exist, or update it if it does.
Querying Data
You can query entities in a table using various filter criteria. Queries are most efficient when they include a filter on the PartitionKey.
Example query to retrieve all entities with PartitionKey "Users":
# ... (previous code for connection string and table client)
partition_key_filter = "Users"
entities = table_client.query_entities(filter=f"PartitionKey eq '{partition_key_filter}'")
print(f"Entities for PartitionKey '{partition_key_filter}':")
for entity in entities:
print(entity)
You can also apply more complex OData filters:
# Example: Query entities where Age > 25
age_filter = "Age gt 25"
older_users = table_client.query_entities(filter=f"PartitionKey eq '{partition_key_filter}' and {age_filter}")
print(f"\nUsers older than 25:")
for user in older_users:
print(user)
Updating Data
To update an existing entity, you can use the update_entity or upsert_entity methods. If you use update_entity, the entity must already exist. upsert_entity will create it if it doesn't.
Example of updating an entity:
# ... (previous code for connection string, table client, and entity)
# Retrieve the entity to update
entity_to_update = table_client.get_entity("Users", "user123")
# Modify properties
entity_to_update["Age"] = 31
entity_to_update["IsActive"] = False
try:
updated_entity = table_client.update_entity(entity_to_update)
print(f"Entity updated successfully: {updated_entity}")
except Exception as e:
print(f"Error updating entity: {e}")
Deleting Data
To delete an entity, you need to specify its PartitionKey and RowKey.
Example of deleting an entity:
# ... (previous code for connection string and table client)
partition_key_to_delete = "Users"
row_key_to_delete = "user123"
try:
table_client.delete_entity(partition_key_to_delete, row_key_to_delete)
print(f"Entity with PartitionKey='{partition_key_to_delete}' and RowKey='{row_key_to_delete}' deleted successfully.")
except Exception as e:
print(f"Error deleting entity: {e}")
Next Steps
Congratulations on getting started with Azure Storage Tables! You've learned how to set up a storage account, create tables, and perform basic CRUD (Create, Read, Update, Delete) operations on entities.
To further enhance your understanding, consider exploring:
- Azure Table Storage conceptual documentation for advanced topics like indexing and performance.
- SDK documentation for your specific language to discover more features.
- Azure Cosmos DB Table API for a globally distributed, highly scalable NoSQL solution.