在 Azure Cosmos DB 中配置生存时间Configure time to live in Azure Cosmos DB

在 Azure Cosmos DB 中,可以选择在容器级别配置生存时间 (TTL),也可以在为容器完成设置之后,在项级别重写生存时间。In Azure Cosmos DB, you can choose to configure Time to Live (TTL) at the container level, or you can override it at an item level after setting for the container. 可以通过 Azure 门户或特定于语言的 SDK 配置容器的 TTL。You can configure TTL for a container by using Azure portal or the language-specific SDKs. 可以通过 SDK 配置项级别 TTL 重写。Item level TTL overrides can be configured by using the SDKs.

备注

此内容与 Azure Cosmos DB 事务存储 TTL 相关。This content is related to Azure Cosmos DB transactional store TTL. 如果正在查找通过 Azure Synapse Link 启用 NoETL HTAP 方案的分析存储 TTL,请单击此处If you are looking for analitycal store TTL, that enables NoETL HTAP scenarios through Azure Synapse Link, please click here.

使用 Azure 门户在容器上启用生存时间Enable time to live on a container using Azure portal

通过以下步骤在没有到期时间的容器上启用生存时间。Use the following steps to enable time to live on a container with no expiration. 启用此项即可在项级别重写 TTL。Enable this to allow TTL to be overridden at the item level. 也可通过输入非零值(代表秒)来设置 TTL。You can also set the TTL by entering a non-zero value for seconds.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 创建新的 Azure Cosmos 帐户或选择现有的帐户。Create a new Azure Cosmos account or select an existing account.

  3. 打开“数据资源管理器”窗格 。Open the Data Explorer pane.

  4. 选择一个现有的容器,将其展开并修改以下值:Select an existing container, expand it and modify the following values:

    • 打开“规模和设置”窗口。 Open the Scale & Settings window.
    • 在“设置”下找到“生存时间”。 Under Setting find, Time to Live .
    • 选择“启用(无默认值)”或选择“启用”,然后设置一个 TTL 值 Select On (no default) or select On and set a TTL value
    • 单击“保存” 以保存更改。Click Save to save the changes.

    在 Azure 门户中配置生存时间

  • 当 DefaultTimeToLive 为 null 时,生存时间为“关”When DefaultTimeToLive is null then your Time to Live is Off
  • 当 DefaultTimeToLive 为 -1 时,“生存时间”设置为“开”(无默认值)When DefaultTimeToLive is -1 then your Time to Live setting is On (No default)
  • 当 DefaultTimeToLive 具有任何其他整数值(0 除外)时,“生存时间”设置为“开”When DefaultTimeToLive has any other Int value (except 0) your Time to Live setting is On

使用 Azure CLI 或 PowerShell 在容器上启用生存时间Enable time to live on a container using Azure CLI or PowerShell

若要在容器上创建或启用 TTL,请参阅To create or enable TTL on a container see,

使用 SDK 在容器上启用生存时间Enable time to live on a container using SDK

.NET SDK.NET SDK

.NET SDK V2 (Microsoft.Azure.DocumentDB).NET SDK V2 (Microsoft.Azure.DocumentDB)

// Create a new container with TTL enabled and without any expiration value
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.Id = "myContainer";
collectionDefinition.PartitionKey.Paths.Add("/myPartitionKey");
collectionDefinition.DefaultTimeToLive = -1; //(never expire by default)

DocumentCollection ttlEnabledCollection = await client.CreateDocumentCollectionAsync(
    UriFactory.CreateDatabaseUri("myDatabaseName"),
    collectionDefinition);

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

CosmosAsyncContainer container;

// Create a new container with TTL enabled and without any expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.setDefaultTimeToLiveInSeconds(-1);
container = database.createContainerIfNotExists(containerProperties, 400).block().getContainer();

使用 SDK 在容器上设置生存时间Set time to live on a container using SDK

若要在容器上设置生存时间,需提供一个非零正数来指示时间段(以秒为单位)。To set the time to live on a container, you need to provide a non-zero positive number that indicates the time period in seconds. 在项的上次修改的时间戳 (_ts) 过后,将会删除容器中的所有值,具体取决于配置的 TTL 值。Based on the configured TTL value, all items in the container after the last modified timestamp of the item _ts are deleted.

.NET SDK.NET SDK

.NET SDK V2 (Microsoft.Azure.DocumentDB).NET SDK V2 (Microsoft.Azure.DocumentDB)

// Create a new container with TTL enabled and a 90 day expiration
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.Id = "myContainer";
collectionDefinition.PartitionKey.Paths.Add("/myPartitionKey");
collectionDefinition.DefaultTimeToLive = 90 * 60 * 60 * 24 // expire all documents after 90 days

DocumentCollection ttlEnabledCollection = await client.CreateDocumentCollectionAsync(
    UriFactory.CreateDatabaseUri("myDatabaseName"),
    collectionDefinition;

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

CosmosAsyncContainer container;

// Create a new container with TTL enabled with default expiration value
CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
containerProperties.setDefaultTimeToLiveInSeconds(90 * 60 * 60 * 24);
container = database.createContainerIfNotExists(containerProperties, 400).block().getContainer();

NodeJS SDKNodeJS SDK

const containerDefinition = {
          id: "sample container1",
        };

async function createcontainerWithTTL(db: Database, containerDefinition: ContainerDefinition, collId: any, defaultTtl: number) {
      containerDefinition.id = collId;
      containerDefinition.defaultTtl = defaultTtl;
      await db.containers.create(containerDefinition);
}

在某个项上设置生存时间Set time to live on an item

除了在容器上设置默认的生存时间,还可以为项设置生存时间。In addition to setting a default time to live on a container, you can set a time to live for an item. 在项级别设置生存时间将重写该容器中项的默认 TTL。Setting time to live at the item level will override the default TTL of the item in that container.

  • 若要在项上设置 TTL,则需要提供一个非零正数,该数字表示自项上次的修改时间戳 (_ts) 之后,项过期所经过的时间段(以秒为单位)。To set the TTL on an item, you need to provide a non-zero positive number, which indicates the period, in seconds, to expire the item after the last modified timestamp of the item _ts.

  • 如果项没有 TTL 字段,则默认情况下,设置到容器的 TTL 将应用到项。If the item doesn't have a TTL field, then by default, the TTL set to the container will apply to the item.

  • 如果在容器级别禁用了 TTL,在项上的 TTL 字段会被忽略,直到在容器上再次启用 TTL。If TTL is disabled at the container level, the TTL field on the item will be ignored until TTL is re-enabled on the container.

Azure 门户Azure portal

通过以下步骤在项上启用生存时间:Use the following steps to enable time to live on an item:

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 创建新的 Azure Cosmos 帐户或选择现有的帐户。Create a new Azure Cosmos account or select an existing account.

  3. 打开“数据资源管理器”窗格 。Open the Data Explorer pane.

  4. 选择一个现有的容器,将其展开并修改以下值:Select an existing container, expand it and modify the following values:

    • 打开“规模和设置”窗口。 Open the Scale & Settings window.
    • 在“设置”下找到“生存时间”。 Under Setting find, Time to Live .
    • 选择“启用(无默认值)”或选择“启用”,然后设置一个 TTL 值。 Select On (no default) or select On and set a TTL value.
    • 单击“保存” 以保存更改。Click Save to save the changes.
  5. 接下来导航到要为其设置生存时间的项,添加 ttl 属性,然后选择“更新”。 Next navigate to the item for which you want to set time to live, add the ttl property and select Update .

    {
        "id": "1",
        "_rid": "Jic9ANWdO-EFAAAAAAAAAA==",
        "_self": "dbs/Jic9AA==/colls/Jic9ANWdO-E=/docs/Jic9ANWdO-EFAAAAAAAAAA==/",
        "_etag": "\"0d00b23f-0000-0000-0000-5c7712e80000\"",
        "_attachments": "attachments/",
        "ttl": 10,
        "_ts": 1551307496
    }
    

.NET SDK(任何).NET SDK (any)

// Include a property that serializes to "ttl" in JSON
public class SalesOrder
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
    [JsonProperty(PropertyName="cid")]
    public string CustomerId { get; set; }
    // used to set expiration policy
    [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
    public int? ttl { get; set; }

    //...
}
// Set the value to the expiration in seconds
SalesOrder salesOrder = new SalesOrder
{
    Id = "SO05",
    CustomerId = "CO18009186470",
    ttl = 60 * 60 * 24 * 30;  // Expire sales orders in 30 days
};

NodeJS SDKNodeJS SDK

const itemDefinition = {
          id: "doc",
          name: "sample Item",
          key: "value",
          ttl: 2
        };

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

// Include a property that serializes to "ttl" in JSON
public class SalesOrder
{
    private String id;
    private String customerId;
    private Integer ttl;

    public SalesOrder(String id, String customerId, Integer ttl) {
        this.id = id;
        this.customerId = customerId;
        this.ttl = ttl;
    }

    public String getId() {return this.id;}
    public void setId(String new_id) {this.id = new_id;}
    public String getCustomerId() {return this.customerId;}
    public void setCustomerId(String new_cid) {this.customerId = new_cid;}
    public Integer getTtl() {return this.ttl;}
    public void setTtl(Integer new_ttl) {this.ttl = new_ttl;}

    //...
}

// Set the value to the expiration in seconds
SalesOrder salesOrder = new SalesOrder(
    "SO05",
    "CO18009186470",
    60 * 60 * 24 * 30  // Expire sales orders in 30 days
);

重置生存时间Reset time to live

可以通过在项上执行写入或更新操作,重置项的生存时间。You can reset the time to live on an item by performing a write or update operation on the item. 写入或更新操作会将 _ts 设置为当前时间,要到期的项的 TTL 就会重启。The write or update operation will set the _ts to the current time, and the TTL for the item to expire will begin again. 若要更改项的 TTL,可以更新相关字段,就像更新任何其他字段那样。If you wish to change the TTL of an item, you can update the field just as you update any other field.

.NET SDK.NET SDK

.NET SDK V2 (Microsoft.Azure.DocumentDB).NET SDK V2 (Microsoft.Azure.DocumentDB)

// This examples leverages the Sales Order class above.
// Read a document, update its TTL, save it.
response = await client.ReadDocumentAsync(
    "/dbs/salesdb/colls/orders/docs/SO05"),
    new RequestOptions { PartitionKey = new PartitionKey("CO18009186470") });

Document readDocument = response.Resource;
readDocument.ttl = 60 * 30 * 30; // update time to live
response = await client.ReplaceDocumentAsync(readDocument);

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

// This examples leverages the Sales Order class above.
// Read a document, update its TTL, save it.
CosmosAsyncItemResponse<SalesOrder> itemResponse = container.readItem("SO05", new PartitionKey("CO18009186470"), SalesOrder.class)
        .flatMap(readResponse -> {
            SalesOrder salesOrder = readResponse.getItem();
            salesOrder.setTtl(60 * 30 * 30);
            return container.createItem(salesOrder);
}).block();

禁用生存时间Turn off time to live

如果已在项上设置生存时间,并且不再想要该项过期,则可以获取该项,删除 TTL 字段并替换服务器上的项。If time to live has been set on an item and you no longer want that item to expire, then you can get the item, remove the TTL field, and replace the item on the server. 从项中删除 TTL 字段时,分配给容器的默认 TTL 值会应用到项。When the TTL field is removed from the item, the default TTL value assigned to the container is applied to the item. 将 TTL 值设置为 -1 可以防止项过期,并且不会从容器继承 TTL 值。Set the TTL value to -1 to prevent an item from expiring and to not inherit the TTL value from the container.

.NET SDK.NET SDK

.NET SDK V2 (Microsoft.Azure.DocumentDB).NET SDK V2 (Microsoft.Azure.DocumentDB)

// This examples leverages the Sales Order class above.
// Read a document, turn off its override TTL, save it.
response = await client.ReadDocumentAsync(
    "/dbs/salesdb/colls/orders/docs/SO05"),
    new RequestOptions { PartitionKey = new PartitionKey("CO18009186470") });

Document readDocument = response.Resource;
readDocument.ttl = null; // inherit the default TTL of the container

response = await client.ReplaceDocumentAsync(readDocument);

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

// This examples leverages the Sales Order class above.
// Read a document, update its TTL, save it.
CosmosAsyncItemResponse<SalesOrder> itemResponse = container.readItem("SO05", new PartitionKey("CO18009186470"), SalesOrder.class)
        .flatMap(readResponse -> {
            SalesOrder salesOrder = readResponse.getItem();
            salesOrder.setTtl(null);
            return container.createItem(salesOrder);
}).block();

禁用生存时间Disable time to live

若要在容器上禁用生存时间并阻止后台进程查找过期项,则应删除容器上的 DefaultTimeToLive 属性。To disable time to live on a container and stop the background process from checking for expired items, the DefaultTimeToLive property on the container should be deleted. 删除此属性不同于将其设置为 -1。Deleting this property is different from setting it to -1. 将它设置为 -1 时,添加到容器的新项将永久生存。但是,可以在容器中的特定项上重写此值。When you set it to -1, new items added to the container will live forever, however you can override this value on specific items in the container. 从容器中删除 TTL 属性后项就不会过期,即使这些项已显式重写了以前的默认 TTL 值。When you remove the TTL property from the container the items will never expire, even if there are they have explicitly overridden the previous default TTL value.

.NET SDK.NET SDK

.NET SDK V2 (Microsoft.Azure.DocumentDB).NET SDK V2 (Microsoft.Azure.DocumentDB)

// Get the container, update DefaultTimeToLive to null
DocumentCollection collection = await client.ReadDocumentCollectionAsync("/dbs/salesdb/colls/orders");
// Disable TTL
collection.DefaultTimeToLive = null;
await client.ReplaceDocumentCollectionAsync(collection);

Java SDKJava SDK

Java SDK V4 (Maven com.azure::azure-cosmos)Java SDK V4 (Maven com.azure::azure-cosmos)

CosmosContainerProperties containerProperties = new CosmosContainerProperties("myContainer", "/myPartitionKey");
// Disable TTL
containerProperties.setDefaultTimeToLiveInSeconds(null);
// Update container settings
container.replace(containerProperties).block();

后续步骤Next steps

在以下文章中详细了解生存时间:Learn more about time to live in the following article: