Skip to content

Instantly share code, notes, and snippets.

@shirou
Created September 8, 2023 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirou/617bf4c6549b6e284abaa31027b37631 to your computer and use it in GitHub Desktop.
Save shirou/617bf4c6549b6e284abaa31027b37631 to your computer and use it in GitHub Desktop.
dynamodb batch get items sample code
const maxRetryCount = 3
func (s *Server) getAlbums(ctx context.Context, albumIDs []uuid.UUID) ([]Album, error) {
ctx, span := tracer.Start(ctx, "getAlbums")
defer span.End()
keysToGet := make([]map[string]types.AttributeValue, len(albumIDs))
for i, albumID := range albumIDs {
idv, err := attributevalue.Marshal(albumID.String())
if err != nil {
return nil, err
}
keysToGet[i] = map[string]types.AttributeValue{
"AlbumID": idv,
}
}
input := dynamodb.BatchGetItemInput{
RequestItems: map[string]types.KeysAndAttributes{
AlbumTableName: {
Keys: keysToGet,
},
},
}
ret := make([]Album, 0)
// retry until UnprocessedKeys is null or reach maxRetryCount
for i := 0; i < maxRetryCount; i++ {
response, err := s.c.BatchGetItem(ctx, &input)
if err != nil {
return nil, err
}
var resValue []Album
v, ok := response.Responses[AlbumTableName]
if !ok {
if len(response.UnprocessedKeys) == 0 {
return nil, fmt.Errorf("no AlbumTableName table in response")
}
continue // retry
}
if err := attributevalue.UnmarshalListOfMaps(v, &resValue); err != nil {
return nil, err
}
if len(response.UnprocessedKeys) == 0 {
break
}
input.RequestItems = response.UnprocessedKeys
ret = append(ret, resValue...)
time.Sleep(500 * time.Millisecond)
}
return ret, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment