amazon-web-services - 使用 golang 检索 dynamodb 中的最新记录
问题描述
我正在尝试检索插入到我的 DynamoDB 表中的最新记录,表结构是这样的:
- 日期(订单键)
- ID(分区键)
- 价值
日期值是 unix 时间戳,这是一个示例 json 数据:
{
"Date": 1590312898,
"Id": "87a6614b-1d05-44af-ab4b-6bc0957796b3",
"Value": 36
}
我尝试使用限制结果设置为 1 的 ScanInput 函数,但我无法获得正确的顺序,所以我得到了错误的行。我尝试使用此代码:
filt := expression.Name("Date").NotEqual(expression.Value(nil))
proj := expression.NamesList(expression.Name("Date"), expression.Name("Id"), expression.Name("Value"))
expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
if err != nil {
fmt.Println("Got error building expression:")
fmt.Println(err.Error())
}
// Build the query input parameters
params := &dynamodb.ScanInput{
Limit: aws.Int64(1),
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
FilterExpression: expr.Filter(),
ProjectionExpression: expr.Projection(),
TableName: aws.String(tableName),
}
// Make the DynamoDB Query API call
result, err := svc.Scan(params)
也许我必须使用 ScanIndexForward 参数,但我不明白如何以正确的方式设置它。
有什么建议吗?这是正确的方法吗?
提前致谢
解决方案更新:
我必须使用 QueryInput 而不是 ScanInput 函数来使用 ScanInputForward,这是新代码:
var queryInput = &dynamodb.QueryInput{
TableName: aws.String(tableName),
KeyConditions: map[string]*dynamodb.Condition{
"Type": {
ComparisonOperator: aws.String("EQ"),
AttributeValueList: []*dynamodb.AttributeValue{
{
S: aws.String("SM"),
},
},
},
},
ScanIndexForward: aws.Bool(false),
Limit: aws.Int64(1),
}
result, err := svc.Query(queryInput)
解决方案
首先,由于您的日期是分区键,因此每当您在后端进行扫描时,DynamoDB 都会单独调用每个分区。无论他们返回哪个顺序,都将是响应中的顺序。
如果您想使用ScanIndexForward检索它,那么您将查看排序(或范围键)
指定索引遍历的顺序:如果为true(默认),则按升序进行遍历;如果为 false,则按降序执行遍历。
具有相同分区键值的项目按排序键按排序顺序存储。如果排序键数据类型为数字,则结果按数字顺序存储。对于 String 类型,结果按 UTF-8 字节顺序存储。对于 Binary 类型,DynamoDB 将二进制数据的每个字节视为无符号。
我建议您查看如何重新构建您的 DynamoDB 表以使用全局二级索引,该索引将使用所有项目使用的分区键和日期的排序键。然后,您可以使用 ScanIndexForward 查询并检索您的最大值。
否则,您将无法执行扫描,然后按订单进行后期处理。
推荐阅读
- php - 为珠宝店开发购物车应用程序有哪些合适的 PHP 框架
- sql-server - 使用 CodeIgniter SQLSRV 在 SQL Server 中执行存储过程
- docker - 如何防止`docker image prune -f -a`删除正在进行的构建中使用的中间图像?
- mongodb - MongoDB Atlas 未连接到我的 golang 应用程序
- javascript - 如果未找到打印,则检查数组中是否存在元素
- node.js - 错误:在 Gaxios 上找不到。
尝试从 Gmail 获取历史记录列表时 - c# - Automapper - IncludeBase 抽象通用父原因“...不是源自”错误
- flutter - 使用命令 flutter build apk 时如何解决音频播放器的配置问题?
- python - 使用逻辑运算符创建新列
- c++ - 使用可变参数存储 C++ lambda