无法正确使用goamz dynamodb的GetItem方法。

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

Cant get GetItem to work properly with goamz dynamodb

问题

我正在翻译你提供的内容,请稍等片刻。

我遵循了这个教程,并使用Python设置了表格,我可以使用Python获取项目,但无法使用golang获取。我做错了什么?

我按照以下方式创建了我的表格(几乎是从教程中复制粘贴的):

from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-west-2')

table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

我按照以下方式加载数据(使用Python):

my_item = {"year": 1999, "title": "MyMovie", "info": {"Plot": "DynamoDB"}}
table.put_item(Item=my_item)

当我读取数据时(使用Python):

response = table.get_item(Key={"year":1999,
                        "title":"MyMovie",
                    }
    )
print response

我的输出是:

{'Item': {'info': {'Plot': 'DynamoDB'}, 'year': Decimal('1999'), 'title': 'MyMovie'}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'C8I2Q46K06T030INBCFN35RELVVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPHeaders': {'x-amzn-requestid': 'C8I2Q46K06T030INBCFN35RELVVV4KQNSO5AEMVJF66Q9ASUAAJG', 'content-length': '93', 'server': 'Server', 'connection': 'keep-alive', 'x-amz-crc32': '4025342458', 'date': 'Wed, 02 Nov 2016 18:20:14 GMT', 'content-type': 'application/x-amz-json-1.0'}}}

我的golang代码:

package main

import (
	"fmt"
	"github.com/goamz/goamz/aws"
	"github.com/goamz/goamz/dynamodb"
)


func main() {

	access_key := "MyAccessKey"
	secret_key := "MySecretKey"

	auth := aws.Auth{AccessKey: access_key, SecretKey: secret_key}

	server := &dynamodb.Server{Auth: auth, Region: aws.USWest2}

	desc_ptr, err := server.DescribeTable("Movies")

	if err != nil {
		fmt.Println(err)
	}

	primary_key, err := desc_ptr.BuildPrimaryKey()

	if err != nil {
		fmt.Println(err)
	}

	table := server.NewTable("Movies", primary_key)

	my_key := dynamodb.Key{HashKey: "1999", RangeKey: "MyMovie"}

	result, err := table.GetItem(&my_key)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Printing Result")

	for k, v := range(result) {
		fmt.Println(k, *v)
	}
}

结果是:

Printing Result
title {S title MyMovie [] }
year {N year 1999 [] }

除了我提供的titleyear之外,缺少其他所有内容。我漏掉了什么?

编辑:

我的go版本:

go version go1.7.3 linux/amd64

我不知道我使用的goamz版本,但我非常确定我使用的是最新版本。

英文:

I was following this tutorial, and set up the table using Python, and I can get item with Python but not with golang. What am I doing wrong?

I made my table like this (almost copy and paste from the tutorial):

from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-west-2')

table = dynamodb.create_table(
    TableName='Movies',
    KeySchema=[
        {
            'AttributeName': 'year',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'title',
            'KeyType': 'RANGE'  #Sort key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'year',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'title',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10
    }
)

I loaded the data like this (in Python):

my_item = {"year": 1999, "title": "MyMovie", "info": {"Plot": "DynamoDB"}}
table.put_item(Item=my_item)

And when I read data (in Python):

response = table.get_item(Key={"year":1999,
                        "title":"MyMovie",
                    }
    )
print response

My output is:

{u'Item': {u'info': {u'Plot': u'DynamoDB'}, u'year': Decimal('1999'), u'title': u'MyMovie'}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'C8I2Q46K06T030INBCFN35RELVVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPHeaders': {'x-amzn-requestid': 'C8I2Q46K06T030INBCFN35RELVVV4KQNSO5AEMVJF66Q9ASUAAJG', 'content-length': '93', 'server': 'Server', 'connection': 'keep-alive', 'x-amz-crc32': '4025342458', 'date': 'Wed, 02 Nov 2016 18:20:14 GMT', 'content-type': 'application/x-amz-json-1.0'}}}

My golang code:

package main

import (
	"fmt"
	"github.com/goamz/goamz/aws"
	"github.com/goamz/goamz/dynamodb"
)


func main() {

	access_key := "MyAccessKey"
	secret_key := "MySecretKey"

	auth := aws.Auth{AccessKey: access_key, SecretKey: secret_key}
	
	server := &dynamodb.Server{Auth: auth, Region: aws.USWest2}

	desc_ptr, err := server.DescribeTable("Movies")

	if err != nil {
		fmt.Println(err)
	}

	primary_key, err := desc_ptr.BuildPrimaryKey()

	if err != nil {
		fmt.Println(err)
	}

	table := server.NewTable("Movies", primary_key)

	my_key := dynamodb.Key{HashKey: "1999", RangeKey: "MyMovie"}

	result, err := table.GetItem(&my_key)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Printing Result")
	
	for k, v := range(result) {
		fmt.Println(k, *v)
	}
}

Results in:

Printing Result
title {S title MyMovie [] }
year {N year 1999 [] }

This is missing everything besides title and year that I provide. What am I missing?

Edit:

My go version:

go version go1.7.3 linux/amd64

I don't know what goamz version I have, but I am very sure that I am on the tip of master.

答案1

得分: 1

我相信这可能是**goamz**库中的一个错误。parseAttribute函数具有解析不同数据类型的逻辑。然而,看起来对于MAP、LIST、BOOL等数据类型似乎不起作用。

根据我的观察,String、Number和SS数据类型都正常工作。如果你可以添加一个非键字符串属性并执行程序,你应该能在结果中得到该属性。

goamz项目的Go源代码供参考

英文:

I believe it could be a bug in the goamz library. The function parseAttribute has logic to parse the different data types. However, it looks like it doesn't seems to be working for data types MAP, LIST, BOOL etc.

Per my observation, String, Number and SS data types are working fine. If you can add a non-key string attribute and execute the program. You should get the attribute in the result.

goamz item go source code for reference

答案2

得分: 1

我(OP)最终使用了.. aws-sdk-go

它运行良好,我使用的代码:

package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/endpoints"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
)

func main() {

    sess := session.Must(session.NewSession(&aws.Config{
        Region: aws.String(endpoints.UsWest2RegionID),
    }))

    svc := dynamodb.New(sess)

    input := &dynamodb.GetItemInput{
        Key: map[string]*dynamodb.AttributeValue{
            "year": {
                N: aws.String("1999"),
            },
            "title": {
                S: aws.String("MyMovie"),
            },
        },
        TableName: aws.String("Movies"),
    }

    result, err := svc.GetItem(input)

    fmt.Println(result)
    fmt.Println(err)
}
英文:

I (the OP) ended up using .. aws-sdk-go

And it works fine, the code I used:

package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/endpoints"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
)

func main() {

    sess := session.Must(session.NewSession(&aws.Config{
        Region: aws.String(endpoints.UsWest2RegionID),
    }))

    svc := dynamodb.New(sess)

    input := &dynamodb.GetItemInput{
        Key: map[string]*dynamodb.AttributeValue{
            "year": {
                N: aws.String("1999"),
            },
            "title": {
                S: aws.String("MyMovie"),
            },
        },
        TableName: aws.String("Movies"),
    }

    result, err := svc.GetItem(input)

    fmt.Println(result)
    fmt.Println(err)
}

huangapple
  • 本文由 发表于 2016年11月3日 03:04:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/40387845.html
匿名

发表评论

匿名网友

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

确定