使用 golang 检索 dynamodb 中的最新记录

Retrieve the most recent records in dynamodb with golang

我正在尝试检索插入到我的 DynamoDB table 中的最新记录,table 结构如下:

日期值是unix时间戳,这是一个例子json数据:

{
  "Date": 1590312898,
  "Id": "87a6614b-1d05-44af-ab4b-6bc0957796b3",
  "Value": 36
}

我尝试使用 ScanInput 函数将 Limit 结果设置为 1,但我无法获得正确的顺序,所以我得到了错误的行。我尝试使用此代码:

    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 检索它,那么您将查看排序(或范围键)

Specifies the order for index traversal: If true (default), the traversal is performed in ascending order; if false, the traversal is performed in descending order.

Items with the same partition key value are stored in sorted order by sort key. If the sort key data type is Number, the results are stored in numeric order. For type String, the results are stored in order of UTF-8 bytes. For type Binary, DynamoDB treats each byte of the binary data as unsigned.

我建议您了解如何重新构建 DynamoDB table 以使用 Global Secondary Index,该 Global Secondary Index 将使用所有项目使用的分区键和日期的排序键。然后您可以使用 ScanIndexForward 查询它并检索您的最大值。

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