Cosmos DBのデータをJSONファイルにエクスポートする方法
ローカルで動かす前提のコードです。
import json
import os
import yaml
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
# Cosmos DBクライアントの初期化
cosmos_db_endpoint = "https://hogehoge-cosmos.documents.azure.com:443/" # 実際のエンドポイントに置き換える
cosmos_db_name = "hogehoge_db" # 実際のDB名に置き換える
cosmos_db_container_name = "hogehoge_container" # 実際のコンテナ名に置き換える
def export_cosmosdb_data_to_json(database_name: str, container_name: str, file_name: str):
"""
Cosmos DBからデータをエクスポートしてJSONファイルに保存する。
"""
# Azureのデフォルトクレデンシャルを使用してCosmosClientを作成
azure_credential = DefaultAzureCredential()
client = CosmosClient(cosmos_db_endpoint, credential=azure_credential)
# データベースクライアントを取得
database = client.get_database_client(database_name)
# コンテナクライアントを取得
container = database.get_container_client(container_name)
# クエリの実行(全データを取得)
query = "SELECT * FROM c"
items = list(container.query_items(query, enable_cross_partition_query=True))
# データをJSONファイルに書き込み
with open(file_name, 'w', encoding='utf-8') as f:
json.dump(items, f, ensure_ascii=False, indent=4)
print(f"{container_name} のデータのエクスポートが完了しました。ファイル名: {file_name}")
if __name__ == "__main__":
# エクスポート対象のコンテナと出力ファイル名
container_name = cosmos_db_container_name
file_name = f'{container_name}.json'
# 実行:データをJSONにエクスポート
export_cosmosdb_data_to_json(cosmos_db_name, container_name, file_name)
使い方
-
Azure環境への認証
DefaultAzureCredential
はローカル開発環境やAzure環境での認証情報を自動的に取得します。必要に応じて、VS Codeの拡張機能やaz login
などのAzure CLIコマンドでログインしておきます。 -
エンドポイント/DB/コンテナ名の設定
cosmos_db_endpoint
、cosmos_db_name
、cosmos_db_container_name
を実際の値に置き換えます。 -
スクリプトの実行
ターミナルやコマンドプロンプトでpython <ファイル名>.py
を実行すると、指定されたコンテナの全ドキュメントがJSONファイルとして出力されます。
これにより、Cosmos DBから取り出したデータをローカル環境にバックアップしたり、他のシステムで解析するために活用したりできます。機密情報(接続文字列やエンドポイントなど)が含まれる場合は、.env
ファイルを使うなどして適切に管理してください。