特定のドキュメントに対して Time to Live (TTL) の値を構成する

完了

Azure Cosmos DB SDK を使用すると、コンテナー内の個々の項目に Time-to-Live (TTL) を構成できます。 TTL を使用すると、指定した期間が経過した後にアイテムが自動的に削除されます。 個々の項目に Time to Live (TTL) を実装するには、項目を更新する場合と同じ方法を使用できます。

まず、 Product クラスを見てみましょう。 JSON の ttl プロパティが null でない場合にのみ設定する新しい TimeToLive プロパティを定義できます。 この手法を実現するには、JsonProperty ヘッダーを構成して null 値を無視し、メンバーを null 許容型 int として構成します。

[JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
public int? ttl { get; set; }

そこから、TimeToLive 値を整数に設定して、アイテムが最後に変更された時刻を超えて自動的に消去されるまでの期間 (秒単位) を示すことで、サドル変数を更新できます。

saddle.ttl = 1000;

ReplaceItemAsync<> メソッドを使用して項目を更新します。

await container.ReplaceItemAsync<Product>(saddle);

Python SDK を使用すると、項目に新しいプロパティ値を動的に設定できます。 項目に TimeToLive 値を設定するには、項目が最後に変更された時刻を超えて自動的に消去されるまでの長さ (秒単位) を示す整数を割り当てます。 この変更を行うには、項目オブジェクトを新しい ttl プロパティ値で更新します。

saddle["ttl"] = 1000

replace_item メソッドを使用して項目を更新します。

container.replace_item(item=saddle, body=saddle)

ただし、思い出したように、アイテムを表す Product クラスを定義しました。 JSON の ttl プロパティが null でない場合にのみ設定する新しい TimeToLive プロパティを定義できます。 この手法は、メンバーを null 許容 int として構成することによって実現されます。

class Product:
    def __init__(
            self,
            internal_id: str,
            name: str,
            category_id: str,
            price: float,
            tags: list[str],
            ttl: int = None):
        self.internal_id = internal_id
        self.name = name
        self.category_id = category_id  # Partition key
        self.price = price
        self.tags = tags
        self.ttl = ttl # Time to live

    def to_dict(self):
        product_dict = {
            "id": self.internal_id,  # Map internal_id to id
            "name": self.name,
            "categoryId": self.category_id,
            "price": self.price,
            "tags": self.tags
        }
        if self.ttl is not None:
            product_dict["ttl"] = self.ttl
        return product_dict

ttl プロパティを追加した後でこのクラスを操作するには、新しい Product オブジェクトをインスタンス化し、プロパティ値を設定します。

# Perform the point read
saddle = container.read_item(item=item_id, partition_key=partition_key_value)

# Convert the response to a Product object
product = Product(
    internal_id=saddle["id"],
    name=saddle["name"],
    category_id=saddle["categoryId"],
    price=saddle["price"],
    tags=saddle["tags"],
    # Add the TTL value here if it exists
    ttl=saddle.get("ttl")
)

# Set the TTL property (in seconds)
product.ttl = 1000

# Update the item in Cosmos DB
container.replace_item(item=item_id, body=product.to_dict())

to_dict()メソッドを使用して、Product オブジェクトをディクショナリに変換し、項目を更新します。 ご思い出のとおり、 __dict__ 属性の代わりにこのメソッドを使用して 、internal_id プロパティが JSON オブジェクトの id プロパティに適切にマップされていることを確認します。

get("ttl") メソッドは、サドル オブジェクトから ttl プロパティの値を取得するために使用されます。 プロパティが存在しない場合、メソッドは Noneを返します。 この値は、インスタンス化されると Product オブジェクトに渡されます。

JavaScript SDK を使用すると、項目に新しいプロパティ値を動的に設定できます。 項目に TimeToLive 値を設定するには、項目が最後に変更された時刻を超えて自動的に消去されるまでの長さ (秒単位) を示す整数を割り当てます。 この変更を行うには、項目オブジェクトを新しい ttl プロパティ値で更新します。

saddle.ttl = 1000;

replace メソッドを使用して項目を更新します。

await container.item(saddle.id, saddle.categoryId).replace(saddle);

ただし、思い出したように、アイテムを表す Product クラスを定義しました。 JSON の ttl プロパティが null でない場合にのみ設定する新しい TimeToLive プロパティを定義できます。 この手法は、メンバーを null 許容 int として構成することによって実現されます。

class Product {
    constructor(internalId, name, categoryId, price, tags, ttl=null) {
        this.internalId = internalId;
        this.name = name;
        this.categoryId = categoryId; // Partition key
        this.price = price;
        this.tags = tags;
        this.ttl = ttl; // Optional time-to-live
    }

    toJSON() {
        const json = {
            id: this.internalId, // Map internalId to id
            name: this.name,
            categoryId: this.categoryId,
            price: this.price,
            tags: this.tags
        };
        if (this.ttl !== null) {
            json.ttl = this.ttl;
        }
        return json;
    }
}

ttl プロパティを追加した後でこのクラスを操作するには、新しい Product オブジェクトをインスタンス化し、プロパティ値を設定します。

// Perform the point read
const { resource: saddle } = await container.item(itemId, partitionKeyValue).read();

const product = new Product(
    saddle.id,
    saddle.name,
    saddle.categoryId,
    saddle.price,
    saddle.tags,
    saddle.ttl // Include the TTL value if it exists
);

// Set the TTL property (in seconds)
product.ttl = 1500;

// Update the item in Cosmos DB
await container.item(product.internalId, product.categoryId).replace(product.toJSON());

toJSON()メソッドを使用して、Product オブジェクトをディクショナリに変換し、項目を更新します。 ご思い出のとおり、このメソッドは、代わりに標準の JSON シリアル化に依存して 、internalId プロパティが JSON オブジェクトの id プロパティに適切にマップされるようにするために使用します。

DefaultTimeToLive プロパティがコンテナー レベルで構成されていない場合、このプロセスは機能しません。 また、ttl-1値は、項目の TTL を無効にします。