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

我看到了这个代码示例-

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

是否还有其他代码示例显示对BatchGetItem API的响应进行编码?

最佳答案

让我分享一段代码。理解它的关键是,当您将GetBatchItem请求发送到dynamodb时,您指定了表名和该表的键的映射,因此得到的响应就是表名和匹配项的映射。

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)
    }
}

10-07 23:43