适用范围:
NoSQL
在 Azure Cosmos DB 中,可以选择在容器级别配置生存时间 (TTL),也可以在为容器完成 TTL 设置之后,在项级别重写生存时间。 可以使用 Azure 门户或特定于语言的 SDK 为容器配置 TTL。 可以通过 SDK 配置项级别 TTL 重写。
使用 Azure 门户在容器上启用 TTL
使用以下步骤在未过期的容器上启用 TTL。 在容器级别启用 TTL 允许在单个项的级别重写相同的值。 还可以通过在秒内输入非零值来设置 TTL。
登录到 Azure 门户。
创建新的 Azure Cosmos DB 帐户或选择现有的帐户。
打开“数据资源管理器”窗格。
选择现有容器,展开 “设置” 选项卡并修改以下值:
- 在 “设置”下,找到 存活时间。
- 根据需求,可以:
-
关闭此设置。
- 将其设置为“开”(无默认值)。
- 使用以秒为单位指定的 TTL 值打开。
- 选择“保存”,保存更改。
- 如果 DefaultTimeToLive 为 null,则 TTL 为 Off。
- 如果 DefaultTimeToLive 为 -1 ,则 TTL 设置为 “打开” (无默认值)。
- 如果 DefaultTimeToLive 具有任何其他整数值(0 除外),则 TTL 设置为 On。 服务器会根据配置的值自动删除项。
使用 Azure CLI 或 Azure PowerShell 在容器上启用 TTL
若要在容器上创建或启用 TTL,请参阅:
使用 SDK 在容器上启用 TTL
Database database = client.GetDatabase("database");
ContainerProperties properties = new ()
{
Id = "container",
PartitionKeyPath = "/customerId",
// Never expire by default
DefaultTimeToLive = -1
};
// Create a new container with TTL enabled and without any expiration value
Container container = await database
.CreateContainerAsync(properties);
CosmosDatabase database = client.getDatabase("database");
CosmosContainerProperties properties = new CosmosContainerProperties(
"container",
"/customerId"
);
// Never expire by default
properties.setDefaultTimeToLiveInSeconds(-1);
// Create a new container with TTL enabled and without any expiration value
CosmosContainerResponse response = database
.createContainerIfNotExists(properties);
const database = await client.database("database");
const properties = {
id: "container",
partitionKey: "/customerId",
// Never expire by default
defaultTtl: -1
};
const { container } = await database.containers
.createIfNotExists(properties);
database = client.get_database_client('database')
database.create_container(
id='container',
partition_key=PartitionKey(path='/customerId'),
# Never expire by default
default_ttl=-1
)
db, _ := c.NewDatabase("demo_db")
pkDefinition := azcosmos.PartitionKeyDefinition{
Paths: []string{"/state"},
Kind: azcosmos.PartitionKeyKindHash,
}
// Never expire by default
ttl := int32(-1)
db.CreateContainer(context.Background(), azcosmos.ContainerProperties{
ID: "demo_container",
PartitionKeyDefinition: pkDefinition,
DefaultTimeToLive: &ttl,
}, nil)
使用 SDK 在容器上设置 TTL
若要在容器上设置 TTL,需要提供一个非零正数,指示时间段(以秒为单位)。 在项的上次修改的时间戳 (_ts
) 过后,将会删除容器中的所有值,具体取决于配置的 TTL 值。
Database database = client.GetDatabase("database");
ContainerProperties properties = new ()
{
Id = "container",
PartitionKeyPath = "/customerId",
// Expire all documents after 90 days
DefaultTimeToLive = 90 * 60 * 60 * 24
};
// Create a new container with TTL enabled and without any expiration value
Container container = await database
.CreateContainerAsync(properties);
CosmosDatabase database = client.getDatabase("database");
CosmosContainerProperties properties = new CosmosContainerProperties(
"container",
"/customerId"
);
// Expire all documents after 90 days
properties.setDefaultTimeToLiveInSeconds(90 * 60 * 60 * 24);
CosmosContainerResponse response = database
.createContainerIfNotExists(properties);
const database = await client.database("database");
const properties = {
id: "container",
partitionKey: "/customerId",
// Expire all documents after 90 days
defaultTtl: 90 * 60 * 60 * 24
};
const { container } = await database.containers
.createIfNotExists(properties);
database = client.get_database_client('database')
database.create_container(
id='container',
partition_key=PartitionKey(path='/customerId'),
# Expire all documents after 90 days
default_ttl=90 * 60 * 60 * 24
)
db, _ := c.NewDatabase("demo_db")
// Expire all documents after 90 days
ttl := int32(90 * 24 * 60 * 60)
db.CreateContainer(context.Background(), azcosmos.ContainerProperties{
ID: containerName,
PartitionKeyDefinition: pkDefinition,
DefaultTimeToLive: &ttl,
}, nil)
通过 Azure 门户为项目设置 TTL
除了在容器上设置默认 TTL 之外,还可以为项设置 TTL。 在项级别设置 TTL 会覆盖该容器中项的默认 TTL。
若要对项设置 TTL,需要提供一个非零正数,该数字指示在项目上次修改时间戳之后使项 _ts
过期的时间段(以秒为单位)。 当项目不应过期时,你也可以提供 -1
。
如果项没有 TTL 字段,则默认情况下,设置为容器的 TTL 将应用于该项。
如果在容器级别禁用 TTL,则在容器上重新启用 TTL 之前,将忽略该项上的 TTL 字段。
使用以下步骤在项目上启用 TTL:
登录到 Azure 门户。
创建新的 Azure Cosmos DB 帐户或选择现有的帐户。
打开“数据资源管理器”窗格。
选择现有容器,将其展开并修改以下值:
- 打开“规模和设置”窗口。
- 在 “设置”下,找到 生存时间。
- 选择“启用(无默认值)”或选择“启用”,然后设置一个 TTL 值。
- 选择“保存”,保存更改。
导航到要为其设置生存时间的项,添加 ttl
属性,然后选择“ 更新”。
{
"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
}
使用 SDK 在项上设置 TTL
public record SalesOrder(string id, string customerId, int ttl);
Container container = database.GetContainer("container");
SalesOrder item = new (
"SO05",
"CO18009186470"
// Expire sales order in 30 days using "ttl" property
ttl: 60 * 60 * 24 * 30
);
await container.CreateItemAsync<SalesOrder>(item);
public class SalesOrder {
public String id;
public String customerId;
// Include a property that serializes to "ttl" in JSON
public Integer ttl;
}
CosmosContainer container = database.getContainer("container");
SalesOrder item = new SalesOrder();
item.id = "SO05";
item.customerId = "CO18009186470";
// Expire sales order in 30 days using "ttl" property
item.ttl = 60 * 60 * 24 * 30;
container.createItem(item);
const container = await database.container("container");
const item = {
id: 'SO05',
customerId: 'CO18009186470',
// Expire sales order in 30 days using "ttl" property
ttl: 60 * 60 * 24 * 30
};
await container.items.create(item);
container = database.get_container_client('container')
item = {
'id': 'SO05',
'customerId': 'CO18009186470',
# Expire sales order in 30 days using "ttl" property
'ttl': 60 * 60 * 24 * 30
}
container.create_item(body=item)
custInfo := map[string]any{
"id": "SO05",
"customerId": "CO18009186470",
// Expire sales order in 30 days using "ttl" property
"ttl": int32(60 * 60 * 24 * 30),
}
container, _ := db.NewContainer(containerName)
item, err := json.Marshal(custInfo)
container.CreateItem(context.Background(), azcosmos.NewPartitionKeyString("CO18009186470"), item, nil)
使用 SDK 重置 TTL
可以通过对项执行写入或更新操作来重置项上的 TTL。 写入或更新操作会将_ts
设置为当前时间,并且项目到期的TTL计时将重新开始。 若要更改项的 TTL,可以更新相关字段,就像更新任何其他字段那样。
SalesOrder item = await container.ReadItemAsync<SalesOrder>(
"SO05",
new PartitionKey("CO18009186470")
);
// Update ttl to 2 hours
SalesOrder modifiedItem = item with {
ttl = 60 * 60 * 2
};
await container.ReplaceItemAsync<SalesOrder>(
modifiedItem,
"SO05",
new PartitionKey("CO18009186470")
);
CosmosItemResponse<SalesOrder> response = container.readItem(
"SO05",
new PartitionKey("CO18009186470"),
SalesOrder.class
);
SalesOrder item = response.getItem();
// Update ttl to 2 hours
item.ttl = 60 * 60 * 2;
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
container.replaceItem(
item,
"SO05",
new PartitionKey("CO18009186470"),
options
);
const { resource: item } = await container.item(
'SO05',
'CO18009186470'
).read();
// Update ttl to 2 hours
item.ttl = 60 * 60 * 2;
await container.item(
'SO05',
'CO18009186470'
).replace(item);
item = container.read_item(
item='SO05',
partition_key='CO18009186470'
)
# Update ttl to 2 hours
item['ttl'] = 60 * 60 * 2
container.replace_item(
item='SO05',
body=item
)
// Read the item
resp, _ := container.ReadItem(context.Background(), azcosmos.NewPartitionKeyString("CO18009186470"), "SO05", nil)
var order map[string]any
json.Unmarshal(resp.Value, &order)
// Update ttl to 2 hours
order["ttl"] = int32(120 * 60)
updatedOrder, err = json.Marshal(order)
container.ReplaceItem(context.Background(), azcosmos.NewPartitionKeyString("CO18009186470"), "SO05", updatedOrder, nil)
使用 SDK 禁用 TTL
若要在容器上禁用 TTL 并停止后台进程检查过期项, DefaultTimeToLive
应删除容器上的属性。 删除此属性不同于将其设置为 -1。 将它设置为 -1 时,新项将实时添加到容器中,但可以在容器中的特定项上重写此值。 从容器中删除 TTL 属性时,这些项永远不会过期,即使它们显式重写了以前的默认 TTL 值。
ContainerProperties properties = await container.ReadContainerAsync();
// Disable ttl at container-level
properties.DefaultTimeToLive = null;
await container.ReplaceContainerAsync(properties);
CosmosContainerResponse response = container.read();
CosmosContainerProperties properties = response.getProperties();
// Disable ttl at container-level
properties.setDefaultTimeToLiveInSeconds(null);
container.replace(properties);
const { resource: definition } = await container.read();
// Disable ttl at container-level
definition.defaultTtl = null;
await container.replace(definition);
database.replace_container(
container,
partition_key=PartitionKey(path='/id'),
# Disable ttl at container-level
default_ttl=None
)
containerInfo, _ := container.Read(context.Background(), nil)
props := containerInfo.ContainerProperties
// Disable ttl at container-level
props.DefaultTimeToLive = nil
container.Replace(context.Background(), *props, nil)
相关内容