使用 v2 Go SDK 查询 AWS DynamoDb 的 KeyConditionExpression 指南
来源:stackoverflow
时间:2024-02-28 16:09:26 446浏览 收藏
本篇文章给大家分享《使用 v2 Go SDK 查询 AWS DynamoDb 的 KeyConditionExpression 指南》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
我在 dynamodb 中有一个使用以下命令创建的现有表
aws dynamodb create-table \
--region us-east-1 \
--table-name notifications \
--attribute-definitions AttributeName=CustomerId,AttributeType=S AttributeName=Timestamp,AttributeType=N AttributeName=MessageId,AttributeType=S \
--key-schema AttributeName=CustomerId,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--global-secondary-indexes '[
{
"IndexName": "MessageId",
"KeySchema": [
{
"AttributeName": "MessageId",
"KeyType": "HASH"
}
],
"Projection": {
"ProjectionType": "ALL"
},
"ProvisionedThroughput": {
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5
}
}
]'
}
我想在它前面放置一个 API 包装器,它允许我从提供 CustomerId 的表中获取所有记录,因此我尝试使用来自 v2 GO SDK 的查询
<code>// 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(":val"))
expr, err := expression.NewBuilder().WithKeyCondition(keyCond).Build()
input := &dynamodb.QueryInput{
TableName: aws.String("notifications"),
KeyConditionExpression: expr.KeyCondition(),
ExpressionAttributeValues: map[string]dynamodbTypes.AttributeValue{
":val": &dynamodbTypes.AttributeValueMemberS{Value: customerId},
},
}
fmt.Println(*expr.KeyCondition())
output, err := api.dynamoClient.Query(ctx, input)
fmt.Println(output)
fmt.Println(err)
}
</code>
但是,我从 dynamodb 得到了 400
operation error DynamoDB: Query, https response error StatusCode: 400, RequestID: *****, api error ValidationException: Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #0
fmt.PrintLn(*expr.KeyCondition()) 的输出是 #0 = :0
在本地运行此查询会返回我的预期结果
awslocal dynamodb query \
--table-name notifications \
--key-condition-expression "CustomerId = :val" \
--expression-attribute-values '{":val":{"S":"localTesting"}}'
我也尝试过包含时间戳,但不认为这是必需的,因为我的终端命令没有它就可以工作。我认为我没有不当取消引用。我知道我的发电机会话是有效的,因为我可以发布到我的包装器并通过终端命令查看更新。
正确答案
以下是您可以用作模板的查询示例:
// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
DynamoDbClient *dynamodb.Client
TableName string
}
// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(releaseYear int) ([]Movie, error) {
var err error
var response *dynamodb.QueryOutput
var movies []Movie
keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
if err != nil {
log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
} else {
response, err = basics.DynamoDbClient.Query(context.TODO(), &dynamodb.QueryInput{
TableName: aws.String(basics.TableName),
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
KeyConditionExpression: expr.KeyCondition(),
})
if err != nil {
log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
} else {
err = attributevalue.UnmarshalListOfMaps(response.Items, &movies)
if err != nil {
log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
}
}
}
return movies, err
}
您可以查看更多 GoV2 示例 此处
今天关于《使用 v2 Go SDK 查询 AWS DynamoDb 的 KeyConditionExpression 指南》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习