drdawt9210 2018-10-17 23:45
浏览 172
已采纳

DynamoDB PutItem上的条件表达式

I'm trying to use a condition to put a intem on DynamoDB, but doesn't work.

I have a table of users and a attribute id as primary key and attibute name must be unique.

conditions := aws.String("NOT contains(email, :e_email)")
attributes := map[string]*dynamodb.AttributeValue{
    ":e_mail": &dynamodb.AttributeValue{
        S: &user.Email,
    },
}
input := &dynamodb.PutItemInput{
    Item:                item,
    TableName:           dynamoTable,
    ConditionExpression: conditions,
    ExpressionAttributeValues: attributes,
}
_, err = dynamo.PutItemWithContext(ctx1, input)
if err != nil {
    if erro, ok := err.(awserr.Error); ok {
        if erro.Code() == dynamodb.ErrCodeConditionalCheckFailedException {
            log.Println("User already exists")
            body, _ := json.Marshal(models.ErrUsuarioJaExiste)
            resp.StatusCode = models.ErrUsuarioJaExiste.CodigoHTTP
            resp.Body = string(body)
            return resp
        }
    }

    log.Println(err)
    resp.StatusCode = models.ErrInterno.CodigoHTTP
    body, _ := json.Marshal(models.ErrInterno)
    resp.Body = string(body)
    return resp
}

But I still can add items with the same email

  • 写回答

1条回答 默认 最新

  • dongqiang4819 2018-10-18 12:42
    关注

    You're misunderstanding how conditional expressions work. DynamoDB is not testing all items in the table for a matching email. It's testing this item for a matching email. Your conditional expression is only being applied to the item whose ID you are actually presenting on the put call, if there is such an item.

    Remember that PutItem can be used to insert a new item, but it can also be used to replace existing items. If an item with that ID is absent, which I presume is indeed the case here because you're writing a new ID, then your conditional expression will never work.

    Make email a primary key then you can use a conditional expression to test for presence and reject duplicate email insertion. Use the attribute_not_exists function with the name of the email attribute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)