Golang的DynamoDB包,支持map、list和JSON。

huangapple go评论86阅读模式
英文:

Golang Package for dynamodb with map , list and JSON support

问题

我正在尝试将JSON对象保存在DynamoDB中,使用新添加的JSON类型支持(我理解JSON类型基本上是映射+列表),以便可以查询和修改嵌套的JSON文档。

我找不到任何支持新添加的数据类型的DynamoDB的Golang包。

请问有什么建议吗?

英文:

I'm trying save JSON objects as such in dynamodb ,using newly added support for JSON type(my understanding is JSON type is basically maps+lists) so that I can query and modify nested JSON documents.

I couldn't find any golang package for dynamodb with newly added data types support.

Any suggestion on this please ?

答案1

得分: 2

从sdk的第2个版本开始,特定的包已经暴露出来。这使得将任何接口转换为attributevalue.MarshalMap(r)变得更加容易。

根据他们的示例:

type Record struct {
    ID     string
    URLs   []string
}

//...

r := Record{
    ID:   "ABC123",
    URLs: []string{
        "https://example.com/first/link",
        "https://example.com/second/url",
    },
}
av, err := attributevalue.MarshalMap(r)
if err != nil {
    return fmt.Errorf("failed to marshal Record, %w", err)
}

_, err = client.PutItem(context.TODO(), &dynamodb.PutItemInput{
    TableName: aws.String(myTableName),
    Item:      av,
})
if err != nil {
    return fmt.Errorf("failed to put Record, %w", err)
}
英文:

As of version 2 of the sdk a specific package has been exposed. This makes it a lot easier to convert any interface to attributevalue.MarshalMap(r).

As per their example:

type Record struct {
    ID     string
    URLs   []string
}

//...

r := Record{
    ID:   "ABC123",
    URLs: []string{
        "https://example.com/first/link",
        "https://example.com/second/url",
    },
}
av, err := attributevalue.MarshalMap(r)
if err != nil {
    return fmt.Errorf("failed to marshal Record, %w", err)
}

_, err = client.PutItem(context.TODO(), &dynamodb.PutItemInput{
    TableName: aws.String(myTableName),
    Item:      av,
})
if err != nil {
    return fmt.Errorf("failed to put Record, %w", err)
}

答案2

得分: 1

将JSON放入aws-dynamodb中,我们首先需要遍历JSON结构的每个属性,并按以下方式将其转换为dynamodb.AttributeValue:

func (e *DB) saveToDynamodb(data map[string]interface{}) {
    var vv = make(map[string]*dynamodb.AttributeValue)

    for k, v := range data {
        x := (v.(string)) //根据需要进行类型断言
        xx := &(x)
        vv[k] = &dynamodb.AttributeValue{S: xx}
    }
    //s := data["asset_id"].(string)
    params := &dynamodb.PutItemInput{
        Item:      vv,
        TableName: aws.String("Asset_Data"), //必需
    }
    resp, err := e.dynamodb.PutItem(params)

    if err != nil {
        //打印错误,将err转换为awserr.Error以获取错误的Code和Message。
        fmt.Println(err.Error())
        return
    }

    //漂亮地打印响应数据。
    fmt.Println(resp)
}
英文:

To put JSON in aws-dynamodb we first need to iterate through each attribute of JSON struct and convert it to dynamodb.AttributeValue in the following manner:

func (e *DB) saveToDynamodb(data map[string]interface{}){
	var vv=make(map[string]*dynamodb.AttributeValue)

	for k,v:=range data{
		x:=(v.(string))  //assert type as required
		xx:=&(x)
		vv[k]=&dynamodb.AttributeValue{S: xx,}
	}
	//s:=data["asset_id"].(string)
	params := &dynamodb.PutItemInput{
		Item: vv,
		TableName: aws.String("Asset_Data"), // Required
	}
	resp, err := e.dynamodb.PutItem(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}

答案3

得分: 0

要存储一个JSON或嵌套的映射,你可以将其存储在结构体中作为map[string]interface{},并在存储到DynamoDB之前使用attributevalue.MarshalMap进行转换:

type Record struct {
    ID   string
    JSON map[string]interface{}
}

r := Record{
    ID:   "ABC123",
    JSON: map[string]interface{}{
        "Parent": "aa",
        "Children": map[string]interface{}{
            "Child1": "foo",
            "Child2": "bar",
        },
    },
}

av, err := attributevalue.MarshalMap(r)
if err != nil {
    return fmt.Errorf("failed to marshal Record, %w", err)
}

_, err = client.PutItem(context.TODO(), &dynamodb.PutItemInput{
    TableName: aws.String(myTableName),
    Item:      av,
})
if err != nil {
    return fmt.Errorf("failed to put Record, %w", err)
}

以上代码将Record结构体中的数据转换为DynamoDB可以接受的格式,并将其存储到指定的表中。

英文:

To store a JSON or nested maps, you can store it in your struct as a map[string]interface{} and use attributevalue.MarshalMap before storing it into ddb:

type Record struct {
	ID   string
	JSON map[string]interface{}
}

r := Record{
	ID:   "ABC123",
	JSON: map[string]interface{}{
		"Parent": "aa",
		"Children": map[string]interface{}{
			"Child1": "foo",
			"Child2": "bar",
		},
	},
}

av, err := attributevalue.MarshalMap(r)
if err != nil {
	return fmt.Errorf("failed to marshal Record, %w", err)
}

_, err = client.PutItem(context.TODO(), &dynamodb.PutItemInput{
	TableName: aws.String(myTableName),
	Item:      av,
})
if err != nil {
	return fmt.Errorf("failed to put Record, %w", err)
}

huangapple
  • 本文由 发表于 2014年10月15日 17:19:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/26378863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定