0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] Cosmos DBのデータをJSONにエクスポートする方法

Last updated at Posted at 2025-01-21

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)

使い方

  1. Azure環境への認証
    DefaultAzureCredential はローカル開発環境やAzure環境での認証情報を自動的に取得します。必要に応じて、VS Codeの拡張機能やaz loginなどのAzure CLIコマンドでログインしておきます。

  2. エンドポイント/DB/コンテナ名の設定
    cosmos_db_endpointcosmos_db_namecosmos_db_container_name を実際の値に置き換えます。

  3. スクリプトの実行
    ターミナルやコマンドプロンプトで python <ファイル名>.py を実行すると、指定されたコンテナの全ドキュメントがJSONファイルとして出力されます。

これにより、Cosmos DBから取り出したデータをローカル環境にバックアップしたり、他のシステムで解析するために活用したりできます。機密情報(接続文字列やエンドポイントなど)が含まれる場合は、.env ファイルを使うなどして適切に管理してください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?