AWS DynamoDB:解组BatchGetItem响应

时间:2019-07-04 14:21:03

标签: amazon-web-services go amazon-dynamodb aws-sdk-go

我正在使用GO SDK和DynamnoDB BatchGetItem API。

我看到了此代码示例-

https://github.com/aws/aws-sdk-go/blob/master/service/dynamodb/examples_test.go

是否还有其他代码示例显示了来自BatchGetItem API的响应的编组?

1 个答案:

答案 0 :(得分:2)

让我分享部分代码。理解它的关键是,当您向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)
    }
}