首页 > 解决方案 > 使用 golang 检索 dynamodb 中的最新记录

问题描述

我正在尝试检索插入到我的 DynamoDB 表中的最新记录,表结构是这样的:

日期值是 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)

标签: amazon-web-servicesgoamazon-dynamodbdynamodb-queries

解决方案


首先,由于您的日期是分区键,因此每当您在后端进行扫描时,DynamoDB 都会单独调用每个分区。无论他们返回哪个顺序,都将是响应中的顺序。

如果您想使用ScanIndexForward检索它,那么您将查看排序(或范围键)

指定索引遍历的顺序:如果为true(默认),则按升序进行遍历;如果为 false,则按降序执行遍历。

具有相同分区键值的项目按排序键按排序顺序存储。如果排序键数据类型为数字,则结果按数字顺序存储。对于 String 类型,结果按 UTF-8 字节顺序存储。对于 Binary 类型,DynamoDB 将二进制数据的每个字节视为无符号。

我建议您查看如何重新构建您的 DynamoDB 表以使用全局二级索引,该索引将使用所有项目使用的分区键和日期的排序键。然后,您可以使用 ScanIndexForward 查询并检索您的最大值。

否则,您将无法执行扫描,然后按订单进行后期处理。


推荐阅读