Azure Storage Table SDK
This document provides an overview and examples of using the Azure Storage Table SDKs to interact with Azure Table Storage. Azure Table Storage is a NoSQL key-attribute store that lets you store large amounts of unstructured data. It's a cost-effective and scalable service for storing and querying structured non-relational data.
Key Concepts
- Entities: A set of property-bag (name-value pairs). Each entity has a required
PartitionKeyandRowKey. - Properties: Name-value pairs within an entity. Property names are strings, and values can be one of the supported primitive data types.
- PartitionKey: Determines the physical storage of the entity. Entities with the same
PartitionKeyare stored together. - RowKey: Uniquely identifies an entity within a partition.
Getting Started with the .NET SDK
The Azure.Data.Tables library provides a modern, idiomatic experience for working with Azure Table Storage in .NET.
Installation
Install the NuGet package:
dotnet add package Azure.Data.Tables
Usage Example
Here's a basic example of creating a table, inserting an entity, and querying entities:
using Azure;
using Azure.Data.Tables;
using System;
using System.Threading.Tasks;
public class TableClientExample
{
public static async Task Main(string[] args)
{
// Replace with your actual connection string
string connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
string tableName = "MySampleTable";
var client = new TableClient(connectionString, tableName);
// Create the table if it doesn't exist
await client.CreateIfNotExistsAsync();
// Define an entity
var animal = new MyAnimalEntity("Species", "Seahorses")
{
AnimalKind = "Fish",
Genus = "Hippocampus"
};
// Insert the entity
await client.UpsertEntityAsync(animal);
Console.WriteLine($"Entity '{animal.RowKey}' inserted/updated.");
// Query entities
Console.WriteLine("\nQuerying entities:");
var queryResults = client.QueryAsync(e => e.PartitionKey == "Species");
await foreach (var entity in queryResults)
{
Console.WriteLine($" - PartitionKey: {entity.PartitionKey}, RowKey: {entity.RowKey}, AnimalKind: {entity.AnimalKind}, Genus: {entity.Genus}");
}
// Delete the table (optional)
// await client.DeleteAsync();
// Console.WriteLine($"\nTable '{tableName}' deleted.");
}
}
public class MyAnimalEntity : ITableEntity
{
public string AnimalKind { get; set; }
public string Genus { get; set; }
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset? Timestamp { get; }
public ETag ETag { get; }
public MyAnimalEntity() { }
public MyAnimalEntity(string partitionKey, string rowKey)
{
PartitionKey = partitionKey;
RowKey = rowKey;
}
}
Python SDK
The azure-data-tables library is the recommended way to work with Azure Table Storage in Python.
Installation
pip install azure-data-tables
Usage Example
from azure.data.tables import TableServiceClient
from azure.core.exceptions import ResourceNotFoundError
# Replace with your actual connection string
connection_string = "YOUR_AZURE_STORAGE_CONNECTION_STRING"
table_name = "MySampleTablePy"
table_service_client = TableServiceClient.from_connection_string(connection_string)
try:
table_client = table_service_client.get_table_client(table_name)
table_client.create_table()
print(f"Table '{table_name}' created.")
except Exception as e:
print(f"Table '{table_name}' might already exist or an error occurred: {e}")
table_client = table_service_client.get_table_client(table_name)
# Define an entity
entity = {
"PartitionKey": "Species",
"RowKey": "Octopus",
"AnimalKind": "Cephalopod",
"Genus": "Octopus"
}
# Insert/update the entity
table_client.upsert_entity(entity)
print(f"Entity '{entity['RowKey']}' inserted/updated.")
# Query entities
print("\nQuerying entities:")
query_filter = "PartitionKey eq 'Species'"
for entity in table_client.query_entities(filter=query_filter):
print(f" - PartitionKey: {entity['PartitionKey']}, RowKey: {entity['RowKey']}, AnimalKind: {entity['AnimalKind']}, Genus: {entity['Genus']}")
# Delete the table (optional)
# try:
# table_service_client.delete_table(table_name)
# print(f"\nTable '{table_name}' deleted.")
# except ResourceNotFoundError:
# print(f"\nTable '{table_name}' not found for deletion.")
Java SDK
The Azure SDK for Java provides comprehensive support for Azure Table Storage.
Dependency (Maven)
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.x.x</version> <!-- Check for the latest version -->
</dependency>
Usage Example
import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableServiceClient;
import com.azure.data.tables.TableServiceClientBuilder;
import com.azure.data.tables.models.TableEntity;
import com.azure.data.tables.models.TableParallelQuery;
import com.azure.core.util.Context;
import java.util.Map;
public class TableClientExampleJava {
public static void main(String[] args) {
// Replace with your actual connection string
String connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
String tableName = "MySampleTableJava";
TableServiceClient tableServiceClient = new TableServiceClientBuilder()
.connectionString(connectionString)
.buildClient();
// Create the table if it doesn't exist
tableServiceClient.createTableIfNotExists(tableName);
System.out.println("Table '" + tableName + "' created or already exists.");
TableClient tableClient = tableServiceClient.getTableClient(tableName);
// Define an entity
TableEntity entity = new TableEntity("Species", "Dolphin")
.addProperty("AnimalKind", "Mammal")
.addProperty("Genus", "Delphinus");
// Insert/update the entity
tableClient.upsertEntity(entity);
System.out.println("Entity '" + entity.getRowKey() + "' inserted/updated.");
// Query entities
System.out.println("\nQuerying entities:");
String filter = "PartitionKey eq 'Species'";
TableParallelQuery query = tableClient.listEntities(filter, null, null);
for (TableEntity resultEntity : query) {
System.out.println(" - PartitionKey: " + resultEntity.getPartitionKey() +
", RowKey: " + resultEntity.getRowKey() +
", AnimalKind: " + resultEntity.getProperties().get("AnimalKind") +
", Genus: " + resultEntity.getProperties().get("Genus"));
}
// Delete the table (optional)
// tableServiceClient.deleteTable(tableName);
// System.out.println("\nTable '" + tableName + "' deleted.");
}
}
JavaScript/TypeScript SDK
The @azure/data-tables package offers a robust API for Node.js and browser applications.
Installation
npm install @azure/data-tables
# or
yarn add @azure/data-tables
Usage Example
const { TableClient } = require("@azure/data-tables");
async function main() {
// Replace with your actual connection string
const connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
const tableName = "MySampleTableJS";
const client = TableClient.fromConnectionString(connectionString, tableName);
// Create the table if it doesn't exist
await client.createTable();
console.log(`Table '${tableName}' created or already exists.`);
// Define an entity
const entity = {
partitionKey: "Species",
rowKey: "Penguin",
animalKind: "Bird",
genus: "Spheniscus"
};
// Insert/update the entity
await client.upsertEntity(entity);
console.log(`Entity '${entity.rowKey}' inserted/updated.`);
// Query entities
console.log("\nQuerying entities:");
const queryOptions = {
queryFilter: "PartitionKey eq 'Species'"
};
for await (const entity of client.listEntities(queryOptions)) {
console.log(` - PartitionKey: ${entity.partitionKey}, RowKey: ${entity.rowKey}, AnimalKind: ${entity.animalKind}, Genus: ${entity.genus}`);
}
// Delete the table (optional)
// await client.deleteTable();
// console.log(`\nTable '${tableName}' deleted.`);
}
main().catch(err => {
console.error("The following error occurred: ", err);
process.exit(1);
});
Go SDK
The Azure SDK for Go provides the aztables package for interacting with Azure Table Storage.
Installation
go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
Usage Example
package main
import (
"context"
"fmt"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)
func main() {
// Replace with your actual connection string
connectionString := "YOUR_AZURE_STORAGE_CONNECTION_STRING"
tableName := "MySampleTableGo"
client, err := aztables.NewClientFromConnectionString(connectionString, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
// Create the table if it doesn't exist
_, err = client.CreateTable(ctx, tableName, nil)
if err != nil {
// Ignore if table already exists
if !isTableAlreadyExistsError(err) {
log.Fatalf("failed to create table: %v", err)
}
} else {
fmt.Printf("Table '%s' created.\n", tableName)
}
tableClient := client.NewTableClient(tableName)
// Define an entity
entity := aztables.EDMTypeMap{
"PartitionKey": aztables.PropertyValue{Value: "Species"},
"RowKey": aztables.PropertyValue{Value: "Shark"},
"AnimalKind": aztables.PropertyValue{Value: "Fish"},
"Genus": aztables.PropertyValue{Value: "Carcharodon"},
}
// Insert/update the entity
_, err = tableClient.UpsertEntity(ctx, entity, nil)
if err != nil {
log.Fatalf("failed to upsert entity: %v", err)
}
fmt.Printf("Entity '%s' inserted/updated.\n", *entity["RowKey"].Value.(string))
// Query entities
fmt.Println("\nQuerying entities:")
filter := "PartitionKey eq 'Species'"
pager := tableClient.ListEntities(&aztables.ListEntitiesOptions{Filter: to.Ptr(filter)}, nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance page: %v", err)
}
for _, entity := range page.Entities {
fmt.Printf(" - PartitionKey: %s, RowKey: %s, AnimalKind: %v, Genus: %v\n",
entity["PartitionKey"].Value,
entity["RowKey"].Value,
entity["AnimalKind"].Value,
entity["Genus"].Value)
}
}
// Delete the table (optional)
// _, err = client.DeleteTable(ctx, tableName, nil)
// if err != nil {
// log.Fatalf("failed to delete table: %v", err)
// }
// fmt.Printf("\nTable '%s' deleted.\n", tableName)
}
// Helper function to check if the error indicates the table already exists
func isTableAlreadyExistsError(err error) bool {
// This is a simplification. In a real scenario, you might need to parse the error
// for specific Azure error codes or messages.
return err != nil && (len(err.Error()) > 0 && err.Error()[0] == 'T') // Example heuristic
}
API Reference & Further Reading
For detailed API documentation, please refer to the official SDK documentation for your chosen language: