触发器中的 DocumentDB 更新分区键
DocumentDB Update Partition Key in Trigger
我根据记录的当前时间戳设置了 MM/YYYY 格式的分区键。我还有一个 PreTrigger 可以在保存记录时更新此值:
function validate() {
var context = getContext();
var request = context.getRequest();
var document = request.getBody();
var now = new Date(),
document.PartitionKey = ("0" + (now.getMonth() + 1)).slice(-2) + "/" + now.getFullYear();
request.setBody(document);
}
但是,我收到以下错误:
One or more errors occurred.Message: {"Errors":["PartitionKey extracted from document doesn't match the one specified in the header"]}
我们不能在触发器中修改分区键吗?
不,您不能从触发器内部更改分区键。
这是因为存储的 procedures/triggers 是在单个分区键范围内以事务方式执行的。由于 DocumentDB 是分布式数据库,因此需要分区键将请求路由到右侧 server/partition.
执行此操作的最佳方法是从在插入期间填充分区键的数据访问层。附带说明一下,不鼓励使用时间戳作为分区键,因为它会导致热点(通常在当前 timestamp/last 几个小时内频繁访问数据)。
我根据记录的当前时间戳设置了 MM/YYYY 格式的分区键。我还有一个 PreTrigger 可以在保存记录时更新此值:
function validate() {
var context = getContext();
var request = context.getRequest();
var document = request.getBody();
var now = new Date(),
document.PartitionKey = ("0" + (now.getMonth() + 1)).slice(-2) + "/" + now.getFullYear();
request.setBody(document);
}
但是,我收到以下错误:
One or more errors occurred.Message: {"Errors":["PartitionKey extracted from document doesn't match the one specified in the header"]}
我们不能在触发器中修改分区键吗?
不,您不能从触发器内部更改分区键。
这是因为存储的 procedures/triggers 是在单个分区键范围内以事务方式执行的。由于 DocumentDB 是分布式数据库,因此需要分区键将请求路由到右侧 server/partition.
执行此操作的最佳方法是从在插入期间填充分区键的数据访问层。附带说明一下,不鼓励使用时间戳作为分区键,因为它会导致热点(通常在当前 timestamp/last 几个小时内频繁访问数据)。