2019年更新
2019 年,自提出问题以来,这里似乎没有任何变化。在 DynamoDB 中,为非主键字段提供唯一性仍然很棘手。这是最近在亚马逊上发布的一篇文章:https://aws.amazon.com/blogs/database/simulated-amazon-dynamodb-unique-constraints-using-transactions/
基本上,作者建议在同一个表中创建辅助记录,而不是使用如下所述的附加表。
例如,在下图中,为了确保instance_id=2c5d0cc8d900是唯一值,您必须添加
具有人工主键值“instance_id#2c5d0cc8d900”的记录。如果插入成功,您可以插入主记录本身。
+--------------------------+-------------------------+--------+----------------
| id | instance_id | attr1 | other fields...
| | | |
| (primary key) | (a non-key field, | |
| | must be unique) | |
+--------------------------+-------------------------+--------+----------------
| instance_id#2c5d0cc8d900 | | |
| a9fd702a | 2c5d0cc8d900 | qwerty | ...
虽然这种方法可能效果很好,但我个人仍然更喜欢使用单独的表格,如下我原来的答案中所述。因为,当从包含此类辅助记录的表中读取数据时,您必须注意从实际记录中过滤它们。
原答案
如果我正确理解了这个问题,您希望确保不是哈希键的字段的唯一性。
(我不确定你为什么不使用instanceId
作为服务器表的哈希键,我想你有理由这样做)。
我的回答:看起来像如果不使用辅助表,你就无法做到这一点.
这是您现有的服务器表:
+----------------------------------------------+
| Servers |
+----------------------------------------------+
| * id the hash key |
| * instanceId non-key field, must be unique|
| |
| * ... |
| * other fields |
| * ... |
+----------------------------------------------+
我将创建一个附加表,其中 instanceId 作为哈希键:
+----------------------------------------------+
| Instance |
+----------------------------------------------+
| * instanceId the hash key |
+----------------------------------------------+
有了这样一个表,在将记录保存到服务器之前,您必须
首先通过向 Instance 添加一条记录 (putItem) 来确保 instanceId 值是唯一的,并提供一个 ConditionExpression,例如attribute_not_exists(instanceId)
.
并且仅当 put 操作在没有ConditionalCheckFailedException
错误,您可以继续将记录添加到服务器中。
如果您想基于instanceId和imageId这两个字段的组合来确保服务器中记录的唯一性,
使用这些字段的串联值作为 aux 表中的单个字段,而不是仅使用 instanceId:
+----------------------------------------------+
| Instance_Image |
+----------------------------------------------+
| * instanceId_imageId the hash key |
+----------------------------------------------+