amazon-web-servicesgoamazon-dynamodbaws-sdk-goaws-sdk-go-v2

How to serialize DynamoDB LastEvaluatedKey to string


Have a requirement of transferring the LastEvaluatedKey returned from the query output as the response of a paginated API call so that the users can request the next page with the LastEvaluatedKey. Is it possible to convert with aws-sdk-go-v2 ?

Have tried to marshal and unmarshal using json but it was not working

lek := map[string]types.AttributeValue{
    "num":  &types.AttributeValueMemberN{Value: "1"},
    "text": &types.AttributeValueMemberS{Value: "text"},
}
barray, err := json.Marshal(lek)
if err != nil {
  fmt.println(err)
}

lekDecoded := map[string]types.AttributeValue{}
err = json.Unmarshal(barray, &lekDecoded)
if err != nil {
 fmt.println(err)
}

This always keeps failing to decode it back to map[string]types.AttributeValue


Solution

  • LastEvaluatedKey is provided in plain text in the response. If you want to encode it, you can do so using base64 for example. You can choose any type of encoding so long as you decode before supplying back to the next paged request.

    Encode LEK

    aws dynamodb scan \
    --table-name test \
    --limit 1 \
    --query LastEvaluatedKey | base64
    
    ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo
    

    Decode encoded LEK

    echo ewogICAgImlkIjogewogICAgICAgICJTIjogIjR3OG5pWnBpTXk2cXoxbW50RkE1dSIKICAgIH0KfQo | base64 --decode
    
    {
        "id": {
            "S": "4w8niZpiMy6qz1mntFA5u"
        }
    }