ドキュメントの作成

完了

新しい項目を作成するには、まず、Product 型の C# コードで新しい変数を作成する必要があります。

Product saddle = new()
{
    id = "027D0B9A-F9D9-4C96-8213-C8546C4AAE71",
    categoryId = "26C74104-40BC-4541-8EF5-9892F7F03D72",
    name = "LL Road Seat/Saddle",
    price = 27.12d,
    tags = new string[] 
    {
        "brown",
        "weathered"
    }
};

Microsoft.Azure.Cosmos 型の変数が既に存在するとします。コンテナー の名前付き コンテナー

Product 型の新しい項目変数をコンストラクターに渡して CreateItemAsync<> メソッドを非同期に呼び出すことができます。

await container.CreateItemAsync<Product>(saddle);

このメソッドの呼び出しによって新しい項目が作成されますが、操作の結果に関するメタデータは何も取得できません。 または、ItemResponse<> 型の変数に操作の結果を格納することもできます。

ItemResponse<Product> response = await container.CreateItemAsync<Product>(saddle);

HttpStatusCode status = response.StatusCode;
double requestUnits = response.RequestCharge;

Product item = response.Resource;

try-catch ブロックを使用している場合は、CosmosException 型を処理することができます。これには、HTTP 状態コード値用の StatusCode プロパティが含まれています。 アプリケーション コードで考慮する必要がある一般的な HTTP 状態コードをいくつか次に示します。

Code タイトル 理由
400 正しくない要求 要求の本文の項目で問題が発生しました
403 許可されていません コンテナーがいっぱいである可能性があります
409 葛藤 コンテナー内の項目には既に一致する id がある可能性があります
413 RequestEntityTooLarge 項目がエンティティの最大サイズを超えています
429 リクエストが多すぎます 現在の要求は、コンテナーに対してプロビジョニングされた最大 RU/秒を超えています

次の例では、項目がコンテナー内に既に存在する競合シナリオを処理し、他のシナリオでは一般的な例外処理ブロックにフォールバックします。

try
{
    await container.CreateItemAsync<Product>(saddle);
}
catch(CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
    // Add logic to handle conflicting ids
}
catch(CosmosException ex) 
{
    // Add general exception handling logic
}

Azure Cosmos DB コンテナーに新しい項目を作成するには、まず項目モデルのインスタンスを作成する必要があります。 Python では、このプロセスは Product クラスのインスタンスを定義することで実現できます。

saddle = Product(
        internal_id="2a7816bf-9a3c-4f33-b7d7-84efb3923538",
        name="Road Warrior Saddle",
        category_id="26C74104-40BC-4541-8EF5-9892F7F03D72",
        price=65.15,
        tags=["black", "cushioned", "leather"]
    ).to_dict()

Product クラスには、インスタンスをディクショナリに変換するto_dict メソッドがあることを思い出してください。 また、このクラスは、 internal_id プロパティを、Azure Cosmos DB に必要な id プロパティにマップします。

名前付きazure.cosmos.Container型の変数が既にあるとします。

create_item メソッドを使用して、コンテナーに新しい項目を作成できます。

container.create_item(body=saddle)

このメソッドの呼び出しにより新しい項目が作成されますが、操作の結果に関するメタデータは提供されません。 代わりに、操作の応答を変数に取り込むこともできます。 get_response_headers() メソッドは、要求の料金や作成された項目の ETag 値など、操作に関するメタデータを取得します。これにより、オプティミスティック コンカレンシー シナリオが可能になります。

response = container.create_item(body=saddle)
# Get response headers
headers = response.get_response_headers()

# Retrieve the created item
item = response

# Extract metadata from headers
request_charge = headers.get('x-ms-request-charge')
etag = headers.get('etag')

# Output the metadata
print(f"Request Charge: {request_charge}")
print(f"etag: {etag}")

print(f"Item created: {item}")
  • x-ms-request-charge: 操作によって使用される要求ユニット (RU)。
  • etag: 項目のバージョンを表す一意の値。

例外処理

Python SDK では、さまざまなシナリオで例外が発生します。 これらの例外は try-except ブロックを使用して処理できます。 CosmosHttpResponseError 例外には、HTTP 状態コードなどの有用な情報が含まれています。 発生する可能性がある一般的な HTTP 状態コードには、次のようなものがあります。

Code タイトル 理由
400 正しくない要求 要求の本文の項目で問題が発生しました
403 許可されていません コンテナーがいっぱいである可能性があります
409 葛藤 コンテナー内の項目には既に一致する id がある可能性があります
413 RequestEntityTooLarge 項目がエンティティの最大サイズを超えています
429 リクエストが多すぎます 現在の要求は、コンテナーに対してプロビジョニングされた最大 RU/秒を超えています

これらの例外を処理する例を次に示します。

from azure.cosmos.exceptions import CosmosHttpResponseError

try:
    container.create_item(body=saddle)
except CosmosHttpResponseError as ex:
    if ex.status_code == 409:  # Conflict
        print("Conflict: Item with the same id already exists.")
    elif ex.status_code == 429:  # Too Many Requests
        print("Too many requests: Reduce request rate or increase RU/s provisioned.")
    elif ex.status_code == 400:  # Bad Request
        print("Bad request: Check the structure of the item being sent.")
    else:
        print(f"HTTP error occurred: Status code {ex.status_code}, message: {ex.message}")
except Exception as ex:
    print(f"An unexpected error occurred: {ex}")

新しい項目を作成するには、まずデータを表すオブジェクトを定義する必要があります。

項目を定義する

JavaScript で、必要なすべてのプロパティを持つオブジェクトとして項目を定義します。 たとえば、製品項目を定義する方法は次のとおりです。

const saddle = new Product(
    "027D0B9A-F9D9-4C96-8213-C8546C4AAE72", // internalId
    "LL Road Seat/Saddle", // name
    "26C74104-40BC-4541-8EF5-9892F7F03D72", // categoryId
    27.12, // price
    ["brown", "weathered"] // tags
);

このオブジェクトには次のプロパティがあります。

  • internalId: アイテムの一意識別子。
  • categoryId: コンテナーのパーティション キー パスに一致するプロパティ。
  • namepricetags など、項目を記述するその他のプロパティ。

Product クラスには、オブジェクトを JSON 文字列に変換するtoJSON() メソッドがあることを思い出してください。 また、このクラスは、 internalId プロパティを、Azure Cosmos DB に必要な id プロパティにマップします。

アイテムを作成する

名前付きContainer型の変数が既にあるとします。 items.create メソッドを使用して項目を作成できます。

const { resource: item } = await container.items.create(saddle);

このメソッドは、Azure Cosmos DB コンテナーに項目を作成するための要求を送信します。

メタデータの取得

items.create メソッドからの応答には、要求の料金や ETag 値など、操作に関する有用なメタデータを提供するヘッダーが含まれています。これにより、オプティミスティック コンカレンシー シナリオが可能になります。

const { resource: item, headers } = await container.items.create(saddle);

const requestCharge = headers["x-ms-request-charge"];
const etag = headers.etag;

console.log(`Request Charge: ${requestCharge}`);
console.log(`etag: ${etag}`);
console.log("Item created:", item);
  • x-ms-request-charge: 操作によって使用される要求ユニット (RU)。
  • etag: 項目のバージョンを表す一意の値。

エラーを処理する

項目を作成するときに、競合や無効な要求などのエラーが発生する可能性があります。 これらのエラーを処理するには、try-catch ブロックを使用します。 発生する可能性がある一般的な HTTP 状態コードには、次のようなものがあります。

Code タイトル 理由
400 正しくない要求 要求の本文の項目で問題が発生しました
403 許可されていません コンテナーがいっぱいである可能性があります
409 葛藤 コンテナー内の項目には既に一致する id がある可能性があります
413 RequestEntityTooLarge 項目がエンティティの最大サイズを超えています
429 リクエストが多すぎます 現在の要求は、コンテナーに対してプロビジョニングされた最大 RU/秒を超えています
try {
    const { resource: item, headers } = await container.items.create(saddle);
    console.log("Item created:", item);
} catch (error) {
    if (error.code === 409) {
        console.log(`Conflict: Item with the same id (${saddle.id}) already exists.`);
    } else if (error.code === 429) {
        console.log("Too many requests: Reduce request rate or increase RU/s provisioned.");
    } else if (error.code === 400) {
        console.log("Bad request: Check the structure of the item being sent.");
    } else {
        console.log(`An unexpected error occurred: ${error.message}`);
    }
}

この実装により、項目を作成し、診断用のメタデータを取得し、エラーを適切に処理できるようになります。