问题描述
我是 dynamodb 的新手.当我将 putitem
与 dynamodb 一起使用时,我想自动增加 id 值.
I am new to dynamodb. I want to auto increment id value when I use putitem
with dynamodb.
可以这样做吗?
推荐答案
这是 DynamoDB 中的反模式,其构建是为了跨多个分区/分片/服务器进行扩展.由于扩展限制,DynamoDB 不支持自增主键,并且无法保证跨多个服务器.
This is anti-pattern in DynamoDB which is build to scale across many partitions/shards/servers. DynamoDB does not support auto-increment primary keys due to scaling limitations and cannot be guaranteed across multiple servers.
更好的选择是从多个索引组装主键.主键最长可达 2048 字节.有几个选项:
Better option is to assemble primary key from multiple indices. Primary key can be up to 2048 bytes. There are few options:
- 使用 UUID 作为您的键 - 可能是基于时间的 UUID,这使其独一无二、分布均匀并带有时间价值
- 使用随机生成的数字或时间戳 + 随机(可能是位移),例如:ts <<12 + random_number
- 使用其他服务或 DynamoDB 本身生成增量唯一 ID(需要额外调用)
- Use UUID as your key - possibly time based UUID which makes it unique, evenly distributed and carries time value
- Use randomly generated number or timestamp + random (possibly bit-shifting) like: ts << 12 + random_number
- Use another service or DynamoDB itself to generate incremental unique id (requires extra call)
以下代码将在 DynamoDB 中自动递增计数器,然后您可以将其用作主键.
Following code will auto-increment counter in DynamoDB and then you can use it as primary key.
var documentClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: 'sampletable',
Key: { HashKey : 'counters' },
UpdateExpression: 'ADD #a :x',
ExpressionAttributeNames: {'#a' : "counter_field"},
ExpressionAttributeValues: {':x' : 1},
ReturnValues: "UPDATED_NEW" // ensures you get value back
};
documentClient.update(params, function(err, data) {});
// once you get new value, use it as your primary key
我个人最喜欢的是在 http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
以下函数将为特定分片生成 id(作为参数提供).这样你就可以拥有唯一的密钥,它是由时间戳、分片号组合而成的.和一些随机性(0-512).
Following function will generate id for a specific shard (provided as parameter). This way you can have unique key, which is assembled from timestamp, shard no. and some randomness (0-512).
var CUSTOMEPOCH = 1300000000000; // artificial epoch
function generateRowId(shardId /* range 0-64 for shard/slot */) {
var ts = new Date().getTime() - CUSTOMEPOCH; // limit to recent
var randid = Math.floor(Math.random() * 512);
ts = (ts * 64); // bit-shift << 6
ts = ts + shardId;
return (ts * 512) + randid;
}
var newPrimaryHashKey = "obj_name:" + generateRowId(4);
// output is: "obj_name:8055517407349240"
这篇关于如何在 dynamodb 中对主键 id 使用自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!