使用Go SDK v2通过KeyConditionExpression查询DynamoDB遇400错误求助
问题原因
你遇到的ValidationException错误,核心原因是使用Go SDK v2的expression包构建查询条件时,没有正确传递生成的表达式属性名映射。
当你用expression.NewBuilder()构建条件时,SDK会自动为属性名(比如CustomerId)生成占位符(如#0),同时在expr对象中生成ExpressionAttributeNames(映射#0到CustomerId)和ExpressionAttributeValues(映射:0到实际值)。但你的代码里手动定义了ExpressionAttributeValues,却没有把expr生成的ExpressionAttributeNames传入QueryInput,导致DynamoDB无法识别#0对应的实际属性名。
修复方案
修改代码,直接使用expr对象生成的ExpressionAttributeNames和ExpressionAttributeValues,不要手动定义这些字段:
// GET /notifications/ func (api NotificationsApi) getNotifications(w http.ResponseWriter, r *http.Request) { var err error customerId := r.URL.Query().Get("customerId") if customerId == "" { api.errorResponse(w, "customerId query parameter required", http.StatusBadRequest) return } span, ctx := tracer.StartSpanFromContext(r.Context(), "notification.get") defer span.Finish(tracer.WithError(err)) // 构建条件 keyCond := expression.Key("CustomerId").Equal(expression.Value(customerId)) expr, err := expression.NewBuilder().WithKeyCondition(keyCond).Build() if err != nil { api.errorResponse(w, "failed to build expression: "+err.Error(), http.StatusInternalServerError) return } input := &dynamodb.QueryInput{ TableName: aws.String("notifications"), KeyConditionExpression: expr.KeyCondition(), // 使用expr生成的属性名和值映射,不要手动定义 ExpressionAttributeNames: expr.Names(), ExpressionAttributeValues: expr.Values(), } output, err := api.dynamoClient.Query(ctx, input) if err != nil { fmt.Println(err) api.errorResponse(w, "failed to query notifications: "+err.Error(), http.StatusInternalServerError) return } fmt.Println(output) // 这里可以添加返回结果的逻辑 }
关键修改点
- 构建
expression.Value时,直接传入customerId即可,不需要自己指定占位符:val,SDK会自动生成合适的占位符 - 移除手动定义的
ExpressionAttributeValues,改用expr.Names()和expr.Values()获取SDK生成的映射 - 增加了
err的检查(构建expression时的错误),避免后续逻辑执行异常
这样修改后,SDK会自动处理占位符和实际属性名/值的映射,DynamoDB就能正确解析查询条件,不会再出现#0未定义的错误。
内容的提问来源于stack exchange,提问作者ajrice6713
相关产品推荐
相关产品推荐

