使用 v2 Go SDK 查询 AWS DynamoDb 的 KeyConditionExpression 指南
来源:stackoverflow
2024-02-28 16:09:26
0浏览
收藏
本篇文章给大家分享《使用 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 的查询
// 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)
}
但是,我从 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删除
提取 protobuf 结构中的导出字段的方法
- 上一篇
- 提取 protobuf 结构中的导出字段的方法
- 下一篇
- AWS S3 预签名 URL 访问控制
查看更多
最新文章
-
- Golang · Go问答 | 28分钟前 | 标准库 · Context · 并发控制 · net/http · Go问答 · Go 请求超时 handler 取消信号 ErrHandlerTimeout Request.Context http.TimeoutHandler
- Go http.TimeoutHandler 为什么不能取消底层处理函数
- 311浏览 收藏
-
- Golang · Go问答 | 32分钟前 | 标准库 · Go问答 · Go hash.Hash64 Sum64 hash/fnv FNV-1a fnv.New64a 64位哈希
- Go hash/fnv.New64a 怎样计算稳定的 64 位哈希值
- 389浏览 收藏
-
- Golang · Go问答 | 35分钟前 | 错误处理 · 重定向 · net/http · HTTP客户端 · Go问答 · Go net/http error response CheckRedirect http.Client.Do ErrUseLastResponse
- Go net/http Client.Do 返回错误时为什么仍可能有 Response
- 164浏览 收藏
-
- Golang · Go问答 | 37分钟前 | 网络编程 · TCP · Go问答 · Go KeepAliveConfig SetKeepAlivePeriod net.TCPConn.SetKeepAlive TCP keep-alive
- Go net.TCPConn.SetKeepAlive 怎样控制 TCP 空闲保活
- 474浏览 收藏
-
- Golang · Go问答 | 56分钟前 | 文件处理 · csv · Go问答 · 错误排查 · Go encoding/csv csv.Reader CSV读取 FieldsPerRecord ErrFieldCount
- Go csv.Reader 为什么 FieldsPerRecord 会导致读取失败
- 210浏览 收藏
-
- Golang · Go问答 | 59分钟前 | JSON · go · token · encoding/json · Go token 流式解析 json.Decoder JSON嵌套
- Go json.Decoder.Token 为什么遇到非法嵌套会报错
- 170浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go xml.Decoder.Decode 为什么忽略未导出的字段
- 440浏览 收藏
-
- Golang · Go问答 | 1小时前 | go · 压缩 · compress/gzip Header.Comment gzip Reader
- Go compress/gzip.Header.Comment 怎样读取压缩流中的注释字段
- 128浏览 收藏
-
- Golang · Go问答 | 1小时前 | JSON · 类型转换 · Go问答 · encoding/json · Go encoding/json json.Unmarshal float64 json.Number JSON数字 Decoder.UseNumber
- Go json.Unmarshal 为什么把数字解码成 float64
- 397浏览 收藏
-
- Golang · Go问答 | 1小时前 | 文件处理 · Go问答 · 解压 Go archive/zip ZIP权限 ExternalAttrs zip.FileHeader.Mode
- Go zip.FileHeader.Mode 为什么解压权限不完整
- 333浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 1102次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 1098次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 1268次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 1209次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 1056次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go index/suffixarray.Index.Bytes 怎样取得索引引用的原始数据
- 2026-11-18 501浏览
-
- Go gosym.Sym.BaseName 怎样去掉符号的包名与接收者
- 2026-11-17 501浏览
-
- 正则命名捕获组取不到值怎么办
- 2026-11-15 501浏览

