TTL

最近更新时间:2024-12-20 10:59:22

我的收藏

功能介绍

TTL(Time to Live,生存周期)功能,指数据项从创建或更新后开始,到自动被系统删除的时间期限。在创建数据库集合时,通过为文档设置TTL,数据库能够自动清理过期的数据,从而优化存储空间的使用,保持数据的时效性,并确保查询结果的准确性,特别是在数据具有时效性要求的场景中,如实时推荐系统等。

适用场景

某些业务场景下,业务数据的增长很快,并且业务数据的热度随着时间推移会有明显的降低,可以使用 TTL 将热度降低的数据在特定的过期时间时自动清理。例如:在电子商务平台中,用户搜索和浏览行为产生的向量数据,如点击流和用户偏好向量,通常具有很高的时效性。这些数据在短期内对于个性化推荐至关重要,但随着时间的推移,其相关性会迅速降低。在向量数据库集合中,设置TTL,便会自动删除过时的用户行为数据,确保推荐系统能够基于最新的用户互动提供实时、相关的推荐,从而提升用户体验和业务效率。

SDK demo

SDK
Demo
SDK 获取方式
Python SDK
ttl.py
Java SDK
Go SDK
ttl_demo

使用示例

如下以 Java SDK 为例,给出使用 TTL 的关键步骤。
1. 创建集合时,指定 TTL 字段 expired_at,并将 TTL 字段 expired_at 设置 FIlter 索引。
// 初始化 Colleciton 参数
CreateCollectionParam collectionParam = CreateCollectionParam.newBuilder()
.withName("book-vector")
.withShardNum(1)
.withReplicaNum(1)
.withDescription("this is a java sdk test")
.addField(new FilterIndex("id", FieldType.String, IndexType.PRIMARY_KEY))
.addField(new VectorIndex("vector", 3, IndexType.HNSW,
MetricType.COSINE, new HNSWParams(16, 200)))
.addField(new FilterIndex("expired_at", FieldType.Uint64, IndexType.FILTER))
.withTtlConfig(TTLConfig.newBuilder().WithEnable(true).WithTimeField("expired_at").build())
.build();
Collection collection = db.createCollection(collectionParam);
2. 插入向量数据时,指定 TTL 字段 expired_at 过期时间。
说明:
数据库插入数据,过期时间允许有1个小时的误差。
List<Document> documentList = new ArrayList<>(Arrays.asList(
Document.newBuilder()
.withId("0001")
.withVector(Arrays.asList(0.2123, 0.21, 0.213))
.addDocField(new DocField("bookName", "西游记"))
.addDocField(new DocField("author", "吴承恩"))
// 设置数据过期时间为当前时间 24 小时之后
.addDocField(new DocField("expired_at", System.currentTimeMillis()/1000 + 24*60*60))
.build(),
Document.newBuilder()
.withId("0002")
.withVector(Arrays.asList(0.2123, 0.25, 0.213))
.addDocField(new DocField("bookName", "三国演义"))
.addDocField(new DocField("author", "罗贯中"))
.build()));
System.out.println("---------------------- upsert ----------------------");
InsertParam insertParam = InsertParam.newBuilder().withDocuments(documentList).build();
AffectRes affectRes = client.upsert("db-test", "book-vector", insertParam);
System.out.println(JsonUtils.toJsonString(affectRes));