鉴于下面定义的表格式(create-table.json
),在使用put-item
后跟add-event1.json
致电add-event2.json
后,我收到以下错误:
调用PutItem操作时发生客户端错误(ConditionalCheckFailedException):条件请求失败
为什么ConditionExpression不允许我写两个记录? (我希望在第二次手术后有2条记录)
我怀疑是因为使用了非关键条件,但我在docs中看不到任何表明缺乏对非关键条件的支持的内容。
创建表格
$ aws dynamodb create-table --cli-input-json file://create-table.json
创建-table.json
{
"TableName": "EVENTS_TEST",
"KeySchema": [
{ "AttributeName": "aggregateId", "KeyType": "HASH" },
{ "AttributeName": "streamRevision", "KeyType": "RANGE" }
],
"AttributeDefinitions": [
{ "AttributeName": "aggregateId", "AttributeType": "S" },
{ "AttributeName": "streamRevision", "AttributeType": "N" }
],
"ProvisionedThroughput": {
"ReadCapacityUnits": 10,
"WriteCapacityUnits": 10
}
}
添加第一条记录
$ aws dynamodb put-item --cli-input-json file://add-event1.json
附加event1.json
{
"TableName": "EVENTS_TEST",
"Item": {
"aggregateId": { "S": "id" },
"id": { "S": "119" },
"context": { "S": "*" },
"aggregate": { "S": "*" },
"streamRevision": { "N": "0" },
"commitId": { "S": "1119" },
"commitSequence": { "N": "0" },
"commitStamp": { "N": "1470185631511" },
"dispatched": { "BOOL": false },
"payload": { "S": "{ \"event\": \"bla\" }" }
},
"ExpressionAttributeNames": { "#name": "aggregate" },
"ConditionExpression": "attribute_not_exists(aggregateId) and attribute_not_exists(streamRevision) and #name <> :name and context <> :ctx",
"ExpressionAttributeValues": {
":name": { "S": "*" },
":ctx": { "S": "*" }
}
}
添加第二条记录
$ aws dynamodb put-item --cli-input-json file://add-event2.json
附加event2.json
{
"TableName": "EVENTS_TEST",
"Item": {
"aggregateId": { "S": "id" },
"id": { "S": "123" },
"context": { "S": "myCtx" },
"aggregate": { "S": "myAgg" },
"streamRevision": { "N": "0" },
"commitId": { "S": "1123" },
"commitSequence": { "N": "0" },
"commitStamp": { "N": "1470185631551" },
"dispatched": { "BOOL": false },
"payload": { "S": "{ \"event\": \"bla2\" }" }
},
"ExpressionAttributeNames": { "#name": "aggregate" },
"ConditionExpression": "aggregateId <> :id and streamRevision <> :rev and #name <> :name and context <> :ctx",
"ExpressionAttributeValues": {
":id": { "S": "id" },
":rev": { "N": "0" },
":name": { "S": "myAgg" },
":ctx": { "S": "myCtx" }
}
}
答案 0 :(得分:6)
您的目标是保存两条记录。这里有2个问题
散列和范围键的组合使记录唯一。 事件1和事件2具有相同的散列和范围键值。 因此,第二个put-item将只覆盖第一条记录。
在放入记录之前评估ConditionExpression。您的表达式失败,因为当您要插入事件2时,DynamoDB发现已存在具有aggregateId“id1”的记录。条件在“attribute_not_exists(aggregateId)”上失败,并且您收到ConditionalCheckFailedException此表达式可防止记录2覆盖记录1。
如果要保存两个记录,则必须提供另一种哈希键和/或范围键,以更好地表示数据项的唯一性。你不能用ConditionExpression解决这个问题。
答案 1 :(得分:0)
我收到了类似的错误。
The conditional request failed (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ConditionalCheckFailedException; Request ID: SMNKMSKJNSHBSGHVGHSB)
在我的情况下,我没有在表中添加排序键,并且第二项与第一项具有相同的主键。添加排序键后,它就可以正常工作。