【问题标题】:AWS DynamoDB : Unmarshalliing BatchGetItem responseAWS DynamoDB:解组 BatchGetItem 响应
【发布时间】:2019-11-15 07:29:50
【问题描述】:

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

我看到了这个代码示例 -

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

是否有任何其他代码示例显示来自BatchGetItem API 的响应的解组?

【问题讨论】:

  • 响应只是 json。这个例子有什么问题?

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


【解决方案1】:

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

【讨论】:

  • 您最初在哪里定义places?会不会是:places := []Place{} 就在外部 for _, table 循环之前?
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 2021-01-02
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多