Dynamodb unmarshal map into struct

Viewed 1844

I am trying to retrieve a column from dynamodb which is saved as map[string][]string (map with key as string and values as a list of string)

example:

{ 
  { "string1": ["1", "2"]},
  { "string2": ["3", "4"]},
}

I am getting the data but I am not able to unmarshal it and store it in the struct

type Record struct {
    listOfMap map[string][]string
}

scanInput := &dynamodb.ScanInput{
    TableName:            aws.String("someTable"),
    ProjectionExpression: aws.String("desiredColumnToRetrieve"),
}

dynamodbOutput, err := svc.dynamodb.Scan(scanInput)
if err != nil {
    log.Errorf("dynamodb.Scan() error - %s", err)
}

fmt.Println(dynamodbOutput)

records := []Record{}

err = dynamodbattribute.UnmarshalListOfMaps(dynamodbOutput.Items, &records)
if err != nil {
    log.Errorf("dynamodbattribute.UnmarshalListOfMaps() error - %s", err)
}

fmt.Println(records)

dynamodb output (this output is from the above print statements):

{
  Count: 2,
  Items: [{
      desiredColumnToRetrieve: {
        M: {
          string1: {
            L: [{
                S: "1"
              },{
                S: "2"
              }]
          }
        }
      }
    },{
      desiredColumnToRetrieve: {
        M: {
          string2: {
            L: [{
                S: "3"
              },{
                S: "4"
              }]
          }
        }
      }
    }],
  ScannedCount: 2
}
{[map[] map[]}

The data is not getting saved to the struct/map

1 Answers

Probably it would not work, you need to iterate over items first, like:

for _, i := range dynamodbOutput.Items {
        record := Record{}

        err = dynamodbattribute.UnmarshalMap(i, &record)

And in fact, your listOfMaps is regular map. Why do you call so? It's rather mapOfLists

By the way doing full scans on NoSQL tables isn't the best practice, if you are going to do always, you'd better to review partitioning sorting keys and whole data schema. Cheers.

Related