選項
首頁首頁 Skill 開發者工具 azure-cosmos-java

azure-cosmos-java

microsoft/skills microsoft/skills

提供有關如何使用 Azure Cosmos DB Java SDK 的程式碼範例與指引,內容涵蓋設定、驗證、CRUD 操作以及查詢。

...展開全部
10
更新時間 2026-09-12

Azure Cosmos DB Java SDK

適用於 Azure Cosmos DB NoSQL API 的客戶端函式庫,具備全球分佈與反應式模式。

安裝


    com.azure
    azure-cosmos
    最新版本

或使用 Azure SDK BOM:


    
        
            com.azure
            azure-sdk-bom
            {bom_version}
            pom
            import
        
    



    
        com.azure
        azure-cosmos
    

環境變數

COSMOS_ENDPOINT=https://.documents.azure.com:443/
COSMOS_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 容器/項目操作

核心工作流程

建立資料庫

// 同步
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// 採用鏈式調用的非同步操作
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("已建立: " + 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.getId()));

CRUD 操作

import com.azure.cosmos.models.PartitionKey;

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

// 建立
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("已建立: " + response.getItem());
        // 讀取
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("讀取: " + response.getItem());
        // 更新
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // 刪除
        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");

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

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

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

關鍵概念

分區鍵

選擇分區鍵時應注意:

  • 高基數(許多不同的值)
  • 資料與請求的均勻分佈
  • 在查詢中經常使用

一致性等級

層級 保證
強一致性 線性化
有限過時度 具有有界滯後的一致前綴
會話 會話內的相容前綴
一致的前綴 讀取操作絕不會看到順序錯亂的寫入
最終一致性 不保證順序

請求單位 (RUs)

所有操作都會消耗 RU。請檢查回應標頭:

CosmosItemResponse response = container.createItem(user);
System.out.println("RU 消耗量: " + 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("狀態: " + e.getStatusCode());
    System.err.println("訊息: " + e.getMessage());
    System.err.println("請求費用: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("項目已存在");
    } else if (e.getStatusCode() == 429) {
        System.err.println("呼叫次數超限,請於 " + e.getRetryAfterDuration() + " 後重試");
    }
}

參考連結

資源 網址
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
在 GitHub 上查看
---
name: azure-cosmos-java
description: Provides code examples and guidance for using the Azure Cosmos DB SDK for Java, including setup, authentication, CRUD operations, and querying.
license: MIT
---

# Azure Cosmos DB SDK for Java

Client library for Azure Cosmos DB NoSQL API with global distribution and reactive patterns.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>LATEST</version>
</dependency>
```

Or use Azure SDK BOM:

```xml
<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>
```

## Environment Variables

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

## Authentication

### Key-based Authentication

```java
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();
```

### Async Client

```java
import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();
```

### With Customizations

```java
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();
```

## Client Hierarchy

| Class | Purpose |
|-------|---------|
| `CosmosClient` / `CosmosAsyncClient` | Account-level operations |
| `CosmosDatabase` / `CosmosAsyncDatabase` | Database operations |
| `CosmosContainer` / `CosmosAsyncContainer` | Container/item operations |

## Core Workflow

### Create Database

```java
// Sync
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));
```

### Create Container

```java
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 Operations

```java
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();
```

### Query Documents

```java
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

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

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

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

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

## Key Concepts

### Partition Keys

Choose a partition key with:
- High cardinality (many distinct values)
- Even distribution of data and requests
- Frequently used in queries

### Consistency Levels

| Level | Guarantee |
|-------|-----------|
| Strong | Linearizability |
| Bounded Staleness | Consistent prefix with bounded lag |
| Session | Consistent prefix within session |
| Consistent Prefix | Reads never see out-of-order writes |
| Eventual | No ordering guarantee |

### Request Units (RUs)

All operations consume RUs. Check response headers:

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

## Best Practices

1. **Reuse CosmosClient** — Create once, reuse throughout application
2. **Use async client** for high-throughput scenarios
3. **Choose partition key carefully** — Affects performance and scalability
4. **Enable content response on write** for immediate access to created items
5. **Configure preferred regions** for geo-distributed applications
6. **Handle 429 errors** with retry policies (built-in by default)
7. **Use direct mode** for lowest latency in production

## Error Handling

```java
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());
    }
}
```

## Reference Links

| Resource | URL |
|----------|-----|
| Maven Package | https://central.sonatype.com/artifact/com.azure/azure-cosmos |
| API Documentation | https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html |
| Product Docs | https://learn.microsoft.com/azure/cosmos-db/ |
| Samples | https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples |
| Performance Guide | https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql |
| Troubleshooting | https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql |

所有檔案

0 個檔案

安裝 azure-cosmos-java

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-cosmos-java # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 microsoft/skills

相關技能

algorithmic-art
更新時間 2026-08-27
receiving-code-review
更新時間 2026-09-03
tech-debt-tracker
更新時間 2026-08-29
senior-backend
更新時間 2026-08-30
OR