DynamoDB ConditionExpression 不检查重复项

DynamoDB ConditionExpression not checking duplicate

我有这个 DynamoDB table

TableName: MyTable 
    string HashKey: Id,  
    string RangeKey: createTime
Other attributes
    string partId
    string carNum
    string partId_carNum
Local_secondary_index : partId, projection_type       = "ALL"
Local_secondary_index : partId_carNum, projection_type  = "ALL"

我正在尝试通过 Id 和 partId_carNum 的独特组合来实现 post。但是 conditionExpression 不起作用。我在 table 中看到重复条目。我的代码有什么问题?

这是我的打字稿的样子

下面是一个项目的例子

 {
   "Id" : "000001823841",
   "partId" : "1",
   "carNum" : "car",
   "createTime" : "124232353"
   }



 const params: PutItemInput = {
            TableName: MyTable,
            Item: item,
            ConditionExpression: 'Id <> :f AND partId_carNum <> :g',
            ExpressionAttributeValues: {
                ':f': { 'S': '000001823841' },
                ':g': { 'S': '1#car' }
            }
        };

 return await new DynamoDB()
            .putItem(params)
            .promise()
            .then(() => {
                console.log(`SUCCESS: Event with  ID inserted`);
            })
            .catch(err => {
                console.error(`FAILED to write event to ${params.TableName}. with Error: ${err}`);
            });

DynamoDB 没有 built-in 机制来确保非主键属性的唯一性。

根据PutItem docs

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists

这里有几个选项:

  1. partId_carNum 构建到您的主键中。
  2. 在您的应用程序代码中使用 transactions to simulate the unique constraints

如果您有 RDBMS 背景,选项 2 可能会让人觉得有点老套,但这是 DDB 中的常见模式。