如何在RavenDB中执行带Document Expiration的批量插入?
在RavenDB中实现带文档过期的批量插入
官方文档里单条插入时添加@expires元数据的方式,没法直接套用到批量插入场景,得通过批量操作API显式给每个文档附加过期元数据。以下是具体实现方案:
核心逻辑
批量插入时,必须为每个待插入文档单独设置包含@expires字段的元数据,同时要确保数据库已经开启文档过期功能(可在RavenDB Studio的数据库设置里启用)。
C# 代码示例
方式1:用BulkInsertOperation(推荐,更简洁)
using Raven.Client.Documents; using Raven.Client.Documents.BulkInsert; using Raven.Client.Documents.Session; // 业务文档类 public class Order { public string Id { get; set; } public decimal Amount { get; set; } public string CustomerId { get; set; } } public void BulkInsertWithExpiration() { // 初始化文档存储 using var store = new DocumentStore { Urls = new[] { "http://localhost:8080" }, Database = "YourDatabaseName" }; store.Initialize(); // 设置统一过期时间(必须用UTC时间,避免时区偏差) var expirationUtc = DateTime.UtcNow.AddDays(7); // 开启批量插入 using var bulkInsert = store.BulkInsert(); // 遍历待插入文档,逐个写入并附加过期元数据 foreach (var order in GetSampleOrders()) { var metadata = new MetadataAsDictionary(); metadata["@expires"] = expirationUtc; bulkInsert.Write(order, metadata); } } // 模拟待插入的文档列表 private IEnumerable<Order> GetSampleOrders() { return new List<Order> { new Order { Id = "orders/1", Amount = 99.9m, CustomerId = "customers/1" }, new Order { Id = "orders/2", Amount = 199.9m, CustomerId = "customers/2" } }; }
方式2:用BulkInsertCommandData(底层控制,适合复杂场景)
如果需要更精细的批量操作控制,可以直接构造命令数据:
using Raven.Client.Documents; using Raven.Client.Documents.Commands.BulkInsert; using Raven.Client.Documents.Session; public void BulkInsertWithExpirationUsingCommandData() { using var store = new DocumentStore { Urls = new[] { "http://localhost:8080" }, Database = "YourDatabaseName" }; store.Initialize(); var expirationUtc = DateTime.UtcNow.AddDays(7); var commandDatas = new List<BulkInsertCommandData>(); using var session = store.OpenSession(); foreach (var order in GetSampleOrders()) { // 序列化文档数据 var documentData = session.Advanced.GetDocumentData(order, null); // 构造元数据并设置过期时间 var metadata = new MetadataAsDictionary(); metadata["@expires"] = expirationUtc; // 创建批量插入命令 var commandData = new BulkInsertCommandData { Id = order.Id, Document = documentData, Metadata = metadata }; commandDatas.Add(commandData); } // 执行批量插入 store.CommandsFor(session.Database).BulkInsert(commandDatas); }
关键注意事项
- 强制用UTC时间:
@expires的值必须是UTC格式的DateTime,否则RavenDB的过期任务会出现时间计算错误 - 先启用过期功能:目标数据库要先开启文档过期(在Studio进入数据库设置,找到「Document Expiration」并启用)
- 大数量分批处理:超大量文档插入时,建议分批次执行,可通过
BulkInsertOptions配置批量大小、并发数优化性能 - 元数据合并:如果文档本身已有元数据,要合并
@expires字段,别覆盖原有元数据
内容的提问来源于stack exchange,提问作者Rodrigo Pierre
相关产品推荐
相关产品推荐

