You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure Function(Node.js)输出绑定设置Cosmos DB项级TTL?

问题解答

不能通过Azure Function Cosmos DB输出绑定的配置属性直接实现项级TTL设置,需要在每个要写入的文档实体中显式添加ttl字段(单位为秒)来实现。

具体实现步骤:

  1. 修改数据处理逻辑
    不要直接将事件数据序列化为字符串,而是先为数据添加ttl字段,再赋值给输出绑定。比如要设置文档1小时后过期(3600秒),修改你的index.ts代码如下:

    const httpTrigger: AzureFunction = async function (context: Context, eventGridEvent: EventGridEvent<DTO>): Promise<void> {
        // 克隆事件数据并添加ttl字段,设置为3600秒(1小时)
        const documentWithTtl = {
            ...eventGridEvent.data,
            ttl: 3600
        };
        context.bindings.outputDocument = JSON.stringify(documentWithTtl);
    }
    export default httpTrigger;
    
  2. 优化绑定配置
    你配置中的defaultTtl字段仅在createIfNotExists为true且容器不存在时生效,用来设置容器级TTL。既然你已经在Azure门户手动配置了容器级TTL为-1,这个字段可以删除,避免混淆:

    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "outputDocument",
      "databaseName": "myDatabase",
      "collectionName": "myCollection",
      "createIfNotExists": true,
      "PartitionKey": "/customerId",
      "connectionStringSetting": "CosmosDbConnectionString"
    }
    

原理说明

当容器级TTL已启用且设置为-1(默认文档永不过期)时,文档中的ttl字段会覆盖容器的默认行为:

  • 带有ttl字段的文档会在指定秒数后自动过期删除
  • 未带有ttl字段的文档会遵循容器级设置,保持永不过期

内容的提问来源于stack exchange,提问作者Andreas Rainer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:05:15