mcpField
A
azure-cosmos-java

azure-cosmos-java

github.com/sickn33データ・データベース48.7k62 回インストール今日更新
リポジトリ

azure-cosmos-java について

Azure Cosmos DB の NoSQL API 向け Java クライアントライブラリです。同期またはリアクティブなアクセスでデータベースやコンテナーを操作するアプリケーション向けで、整合性レベルや接続モードも設定できます。

主な機能

  1. 01同期・非同期クライアント
  2. 02アカウント、データベース、コンテナー操作
  3. 03データベースとコンテナーの作成
  4. 04アイテムの作成・読み取り・更新・削除
  5. 05パラメーター付き SQL クエリ
  6. 06整合性レベルと接続モードの設定

活用シーン

  1. 01Azure Cosmos DB を使う Java アプリの構築
  2. 02リアクティブなデータ操作
  3. 03SQL パラメーターによるアイテム検索

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-cosmos-java

インストール後、Claude Code で/azure-cosmos-javaを入力して読み込まれたか確認します。

詳細

Azure Cosmos DB SDK for Java

グローバル分散とリアクティブパターンに対応した、Azure Cosmos DB NoSQL API 用クライアントライブラリです。

インストール

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>{reviewed_exact_version}</version>
</dependency>

または、Azure SDK BOM を使用します。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
    </dependency>
</dependencies>

環境変数

COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_KEY=<your-primary-key>

認証

キーベース認証
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(System.getenv("COSMOS_ENDPOINT"))
    .key(System.getenv("COSMOS_KEY"))
    .buildClient();
非同期クライアント
import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();
カスタマイズを適用する場合
import com.azure.cosmos.ConsistencyLevel;
import java.util.Arrays;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .directMode(directConnectionConfig, gatewayConnectionConfig)
    .consistencyLevel(ConsistencyLevel.SESSION)
    .connectionSharingAcrossClientsEnabled(true)
    .contentResponseOnWriteEnabled(true)
    .userAgentSuffix("my-application")
    .preferredRegions(Arrays.asList("West US", "East US"))
    .buildClient();

クライアント階層

クラス用途
CosmosClient / CosmosAsyncClientアカウントレベルの操作
CosmosDatabase / CosmosAsyncDatabaseデータベース操作
CosmosContainer / CosmosAsyncContainerコンテナー/項目の操作

基本的なワークフロー

データベースの作成
// Sync
var dbResponse = client.createDatabaseIfNotExists("myDatabase");
var database = client.getDatabase(dbResponse.getProperties().getId());

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));
コンテナーの作成
asyncClient.createDatabaseIfNotExists("myDatabase")
    .flatMap(dbResponse -> {
        String databaseId = dbResponse.getProperties().getId();
        return asyncClient.getDatabase(databaseId)
            .createContainerIfNotExists("myContainer", "/partitionKey")
            .map(containerResponse -> asyncClient.getDatabase(databaseId)
                .getContainer(containerResponse.getProperties().getId()));
    })
    .subscribe(container -> System.out.println("Container: " + container.getId()));
CRUD 操作
import com.azure.cosmos.models.PartitionKey;

CosmosAsyncContainer container = asyncClient
    .getDatabase("myDatabase")
    .getContainer("myContainer");

// Create
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("Created: " + response.getItem());
        // Read
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("Read: " + response.getItem());
        // Update
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // Delete
        return container.deleteItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()));
    })
    .block();
ドキュメントのクエリ
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

CosmosContainer container = client.getDatabase("myDatabase").getContainer("myContainer");

var query = new com.azure.cosmos.models.SqlQuerySpec(
    "SELECT * FROM c WHERE c.status = @status",
    java.util.List.of(new com.azure.cosmos.models.SqlParameter("@status", "active")));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

CosmosPagedIterable<User> results = container.queryItems(
    query,
    options,
    User.class
);

results.forEach(user -> System.out.println("User: " + user.getName()));

主な概念

パーティションキー

次の条件に合うパーティションキーを選択してください。

  • カーディナリティが高い(異なる値が多数ある)
  • データとリクエストが均等に分散される
  • クエリで頻繁に使用される
整合性レベル
レベル保証
強い整合性線形化可能性
有界整合性遅延が制限された一貫性のあるプレフィックス
セッションセッション内で一貫性のあるプレフィックス
一貫性のあるプレフィックス読み取りで順序が逆転した書き込みが表示されません
結果整合性順序の保証なし
リクエストユニット(RU)

すべての操作で RU を消費します。応答ヘッダーを確認してください。

CosmosItemResponse<User> response = container.createItem(user);
System.out.println("RU charge: " + response.getRequestCharge());

ベストプラクティス

  1. CosmosClient を再利用する — 一度作成し、アプリケーション全体で再利用します
  2. 高スループットのシナリオでは非同期クライアントを使用する
  3. パーティションキーを慎重に選択する — パフォーマンスとスケーラビリティに影響します
  4. 書き込み時のコンテンツ応答を有効にする — 作成した項目にすぐアクセスできます
  5. 地理的に分散したアプリケーションでは優先リージョンを設定する
  6. 429 エラーを再試行ポリシーで処理する(既定で組み込まれています)
  7. 本番環境では、レイテンシを最小限に抑えるためにダイレクトモードを使用する

エラー処理

import com.azure.cosmos.CosmosException;

try {
    container.createItem(item);
} catch (CosmosException e) {
    System.err.println("Status: " + e.getStatusCode());
    System.err.println("Message: " + e.getMessage());
    System.err.println("Request charge: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("Item already exists");
    } else if (e.getStatusCode() == 429) {
        System.err.println("Rate limited, retry after: " + e.getRetryAfterDuration());
    }
}

参照リンク

リソースURL
Maven パッケージhttps://central.sonatype.com/artifact/com.azure/azure-cosmos
API ドキュメントhttps://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html
製品ドキュメントhttps://learn.microsoft.com/azure/cosmos-db/
サンプルhttps://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples
パフォーマンスガイドhttps://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql
トラブルシューティングhttps://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql

使用する場面

このスキルは、概要で説明されているワークフローやアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明範囲に明確に一致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認してください。

CRUD の例では、シリアル化されたパーティションキーのプロパティがコンテナーのパスと一致する User モデルが必要です。示されている new PartitionKey(user.getId()) が有効なのは、実際のパーティションキー値が ID と等しい場合に限られます。それ以外の場合は、モデルの正しいパーティションキー値を渡してください。サンプルでの書き込み/削除は、認可されたテスト用コンテナーで実行し、RU コストに上限を設け、シャットダウン時にクライアントを閉じてください。リアクティブなサブスクリプションでは完了/エラー処理が必要です。subscribe() の呼び出しだけで完了したと判断しないでください。

コメント