如何在 DynamoDB Go SDK 中编写查询,其中分区键的条件相同,但一组分区值的排序键为 MAX?

How do I write a query in DynamoDB Go SDK with equal condition for the partition key but a MAX for the sort key for a set of partition values?

我在 DynamoDB 中有一个 table 和一个复合键

user_id(分区键) 时间戳(排序键)

我想检索一组项目,我有一组要检索的 user_id,但我还需要时间戳为每个 user_id 的最大值。

例如:

user_id timestamp attr
1 1614910613 value1
1 1614902527 value 2
2 1614910683 value 2
2 1614881311 value 2
3 1614902527 value 2

我想检索 user_id 1 和 2 的行,以及每个用户的最大时间戳。在这种情况下,我的结果集应该是:

user_id timestamp attr
1 1614910613 value1
2 1614910683 value 2

我现在可以逐项执行此关键表达式:

cond := expression.KeyAnd(
    expression.Key("user_id").Equal(expression.Value(userId)),
    expression.Key("timestamp").LessThanEqual(expression.Value(int32(time.Now().Unix()))),
    )
expr, err:= expression.NewBuilder().WithKeyCondition(cond).Build()

if err!=nil {
    panic(err)
}

input := &dynamodb.QueryInput{
    ExpressionAttributeNames: expr.Names(),
    ExpressionAttributeValues: expr.Values(),
    KeyConditionExpression: expr.KeyCondition(),
    TableName: aws.String("td.notes"),
    Limit: aws.Int64(1),
    ScanIndexForward: aws.Bool(false),
}

我的问题是,我不知道如何为 user_id 键传递一组值而不是单个值。我看了一下 BatchGetItem,我知道我可以这样做:

mapOfAttrKeys := []map[string]*dynamodb.AttributeValue{}

for _, place := range userIDs {
    mapOfAttrKeys = append(mapOfAttrKeys, map[string]*dynamodb.AttributeValue{
        "user_id": &dynamodb.AttributeValue{
            S: aws.String(place),
        },
        "timestamp": &dynamodb.AttributeValue{
            N: aws.String(timestamp),
        },
    })
}

input := &dynamodb.BatchGetItemInput{
    RequestItems: map[string]*dynamodb.KeysAndAttributes{
        tableName: &dynamodb.KeysAndAttributes{
            Keys: mapOfAttrKeys,
        },
    },
}

但我不能在时间戳中加入“小于”条件。

谢谢!

GetItem 和 BatchGetItem 需要确切的主键。

您需要为每个您想要的用户发出单独的 Query() return。

return最大化的关键,正如您所发现的那样

Limit: aws.Int64(1),
ScanIndexForward: aws.Bool(false),

你真的不需要这个

expression.Key("timestamp").LessThanEqual(expression.Value(int32(time.Now().Unix())))