azure-data-tables-py について
Azure Storage Tables または Cosmos DB Table API の構造化キー・バリューデータを扱う Python SDK です。テーブルとエンティティの管理、条件付きクエリ、同一パーティション内の一括操作、非同期クライアントを提供します。
主な機能
- 01テーブルとエンティティの CRUD 管理
- 02キーまたは条件によるエンティティ検索
- 03取得するエンティティ属性の選択
- 04同一パーティション内の一括操作
- 05非同期クライアントの利用
活用シーン
- 01パーティションキーと行キーを持つレコードの保存と取得
- 02パーティション内のエンティティを絞り込み属性を選択
- 03同一パーティションの複数レコードを一括処理
- 04非同期クライアントによるテーブル操作
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-data-tables-pyインストール後、Claude Code で/azure-data-tables-pyを入力して読み込まれたか確認します。
詳細
Python 用 Azure Tables SDK
構造化データ向けの NoSQL キー値ストア(Azure Storage Tables または Cosmos DB Table API)。
インストール
pip install azure-data-tables azure-identity
環境変数
# Azure Storage Tables
AZURE_STORAGE_ACCOUNT_URL=https://<account>.table.core.windows.net
# Cosmos DB Table API
COSMOS_TABLE_ENDPOINT=https://<account>.table.cosmos.azure.com
認証
from azure.identity import DefaultAzureCredential
from azure.data.tables import TableServiceClient, TableClient
credential = DefaultAzureCredential()
endpoint = "https://<account>.table.core.windows.net"
# Service client (manage tables)
service_client = TableServiceClient(endpoint=endpoint, credential=credential)
# Table client (work with entities)
table_client = TableClient(endpoint=endpoint, table_name="mytable", credential=credential)
クライアントの種類
| クライアント | 用途 |
|---|---|
TableServiceClient | テーブルの作成/削除、テーブルの一覧表示 |
TableClient | エンティティの CRUD、クエリ |
これらは独立したフラグメントです。アカウント/テーブル/パーティション/行と、書き込み/削除の正確な範囲を確認してください。既存のエンティティを保護し、同時変更には ETag/一致条件を使用して、タイムアウト後は再試行の前に状態を照合してください。Storage Table と Cosmos Table では認証/機能/トランザクションの制限が異なります。一方の ID 構成が両方に適用できると思い込まず、選択したエンドポイントを確認してください。クエリ/ページ/バイト数に上限を設け、エンティティの内容をログに記録しないでください。失敗時にはクライアントだけでなく、非同期クレデンシャルもクローズしてください。通貨を double で扱う例は説明用です。金額には正確な資産単位を選択してください。
テーブル操作
# Create table
service_client.create_table("mytable")
# Create if not exists
service_client.create_table_if_not_exists("mytable")
# Delete table
service_client.delete_table("mytable")
# List tables
for table in service_client.list_tables():
print(table.name)
# Get table client
table_client = service_client.get_table_client("mytable")
エンティティ操作
重要:すべてのエンティティに PartitionKey と RowKey が必要です(2つを合わせて一意の ID を構成します)。
エンティティの作成
entity = {
"PartitionKey": "sales",
"RowKey": "order-001",
"product": "Widget",
"quantity": 5,
"price": 9.99,
"shipped": False
}
# Create (fails if exists)
table_client.create_entity(entity=entity)
# Upsert explicitly replaces; omitted mode defaults can merge instead.
from azure.data.tables import UpdateMode
table_client.upsert_entity(entity=entity, mode=UpdateMode.REPLACE)
エンティティの取得
# Get by key (fastest)
entity = table_client.get_entity(
partition_key="sales",
row_key="order-001"
)
print(f"Product: {entity['product']}")
エンティティの更新
# Replace entire entity
entity["quantity"] = 10
table_client.update_entity(entity=entity, mode="replace")
# Merge (update specific fields only)
update = {
"PartitionKey": "sales",
"RowKey": "order-001",
"shipped": True
}
table_client.update_entity(entity=update, mode="merge")
エンティティの削除
table_client.delete_entity(
partition_key="sales",
row_key="order-001"
)
エンティティのクエリ
パーティション内のクエリ
# Query by partition (efficient)
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'"
)
for entity in entities:
print(entity["RowKey"]) # Do not dump property payloads
フィルターを使用したクエリ
# Filter by properties
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales' and quantity gt 3"
)
# With parameters (safer)
entities = table_client.query_entities(
query_filter="PartitionKey eq @pk and price lt @max_price",
parameters={"pk": "sales", "max_price": 50.0}
)
特定のプロパティの選択
entities = table_client.query_entities(
query_filter="PartitionKey eq 'sales'",
select=["RowKey", "product", "price"]
)
すべてのエンティティの一覧表示
# List all (cross-partition - use sparingly)
for entity in table_client.list_entities():
print(entity["RowKey"]) # Do not dump property payloads
バッチ操作
from azure.data.tables import TableTransactionError
# Batch operations (same partition only!)
operations = [
("create", {"PartitionKey": "batch", "RowKey": "1", "data": "first"}),
("create", {"PartitionKey": "batch", "RowKey": "2", "data": "second"}),
("upsert", {"PartitionKey": "batch", "RowKey": "3", "data": "third"}),
]
try:
table_client.submit_transaction(operations)
except TableTransactionError as e:
print(f"Transaction failed: {e}")
非同期クライアント
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.identity.aio import DefaultAzureCredential
async def table_operations():
credential = DefaultAzureCredential()
async with TableClient(
endpoint="https://<account>.table.core.windows.net",
table_name="mytable",
credential=credential
) as client:
# Create
await client.create_entity(entity={
"PartitionKey": "async",
"RowKey": "1",
"data": "test"
})
# Query
async for entity in client.query_entities("PartitionKey eq 'async'"):
print(entity["RowKey"]) # Do not dump property payloads
import asyncio
asyncio.run(table_operations())
データ型
| Python の型 | Table Storage の型 |
|---|---|
str | String |
int | Int64 |
float | Double |
bool | Boolean |
datetime | DateTime |
bytes | Binary |
UUID | Guid |
ベストプラクティス
- パーティションキーを設計する際は、クエリパターンと均等な分散を考慮します
- 可能な限りパーティション内でクエリする(パーティションをまたぐクエリはコストが高くなります)
- 同じパーティション内に複数のエンティティがある場合は、バッチ操作を使用する
- upsert モードを慎重に選択する。冪等性はビジネス上の影響と同時実行性にも左右されます
- インジェクションを防ぐため、パラメーター化クエリを使用する
- エンティティを小さく保つ — 1 エンティティあたり最大 1MB
- 高スループットのシナリオでは、非同期クライアントを使用する
使用する場合
このスキルは、概要で説明されているワークフローやアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中止して確認を求めてください。
コメント
Markdown 対応