【问题标题】:DynamoDB ConditionExpression not checking duplicateDynamoDB ConditionExpression 不检查重复
【发布时间】:2020-09-29 04:07:06
【问题描述】:

我有这张 DynamoDB 表

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 的独特组合来实现发布。但是条件表达式不起作用。我在表中看到重复的条目。我的代码有什么问题?

这是我的 typeScript 的样子

下面是一个项目的例子

 {
   "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}`);
            });

【问题讨论】:

    标签: node.js amazon-web-services amazon-dynamodb


    【解决方案1】:

    DynamoDB 没有内置机制来确保非主键属性的唯一性。

    根据PutItem docs

    要防止新项目替换现有项目,请使用 包含 attribute_not_exists 函数的条件表达式 将属性名称用作 分区键 桌子。由于每条记录都必须包含该属性,因此 attribute_not_exists 函数只有在没有匹配项时才会成功 存在

    你有几个选择:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多