我正在使用 GO SDK 并使用 DynamnoDB BatchGetItem
API。
我看到了这个代码示例 -
https://github.com/aws/aws-sdk-go/blob/master/service/dynamodb/examples_test.go
是否有任何其他代码示例显示来自BatchGetItem
API 的响应的解组?
我正在使用 GO SDK 并使用 DynamnoDB BatchGetItem
API。
我看到了这个代码示例 -
https://github.com/aws/aws-sdk-go/blob/master/service/dynamodb/examples_test.go
是否有任何其他代码示例显示来自BatchGetItem
API 的响应的解组?
让我分享一段代码。理解它的关键是,当您向 dynamodb 发送 GetBatchItem 请求时,您指定了该表的表名和键映射,因此您得到的响应是表名和匹配项的映射
placeIDs := []string { "london_123", "sanfran_15", "moscow_9" }
type Place {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}
mapOfAttrKeys := []map[string]*dynamodb.AttributeValue{}
for _, place := range placeIDs {
mapOfAttrKeys = append(mapOfAttrKeys, map[string]*dynamodb.AttributeValue{
"id": &dynamodb.AttributeValue{
S: aws.String(place),
},
"attr": &dynamodb.AttributeValue{
S: aws.String("place"),
},
})
}
input := &dynamodb.BatchGetItemInput{
RequestItems: map[string]*dynamodb.KeysAndAttributes{
tableName: &dynamodb.KeysAndAttributes{
Keys: mapOfAttrKeys,
},
},
}
batch, err := db.BatchGetItem(input)
if err != nil {
panic(fmt.Errorf("batch load of places failed, err: %w", err))
}
for _, table := range batch.Responses {
for _, item := range table {
var place Place
err = dynamodbattribute.UnmarshalMap(item, &place)
if err != nil {
panic(fmt.Errorf("failed to unmarshall place from dynamodb response, err: %w", err))
}
places = append(places, place)
}
}