Search code examples
amazon-web-servicesgoamazon-dynamodbdynamodb-queries

How to return the largest timestamp for a sort key from dynamodb table using Go APIs?


I have a table structure like this:

column type
bubbleId String
bubbleLastUpdated String
... ...

bubbleId is my Primary Key and bubbleLastUpdated is my Sort Key

The ellipses(...) represent the rest of the data in the structure which doesn't pertain to this question.

Using the expression builder where possible, how should the QueryInput object be built, such that the largest value for bubbleLastUpdated is returned?

I'm using the following in my QueryInput object:

    results, err := d.dynamoClient.Query(&dynamodb.QueryInput{
        TableName: aws.String(tableName),
        ScanIndexForward: aws.Bool(false),
        Limit: aws.Int64(1),
    })

Of course, this returns an error saying there must be a KeyConditionExpression parameter in the request. I'm somewhat familiar with key expression builder, but I don't want to actually provide conditionals for these. Unfortunately, after a ton of searching, I've ended up here. I'm either looking for the wrong thing or missing something simple.

An example would be most helpful.

Thanks!


Solution

  • What you call primary key is actually called partition key. You have to specify at least the partition key to be able to use query.

    If you don't have the partition key, then you can use scan, but it is inefficient, and you should consider redesigning the table, or adding global secondary index (gsi).

    You can use the partition key in the query like this:

        var queryInput = &dynamodb.QueryInput{
            TableName:        aws.String(tableName),
            ScanIndexForward: aws.Bool(false),
            Limit:            aws.Int64(1),
            KeyConditions: map[string]*dynamodb.Condition{
                "bubbleId": {
                    ComparisonOperator: aws.String("EQ"),
                    AttributeValueList: []*dynamodb.AttributeValue{
                        {
                            S: aws.String("bubbleId"),
                        },
                    },
                },
            },
        }
    
        var resp, err = d.dynamoClient.Query(queryInput)
        if err != nil {
            return nil, err
        }