首页 > 解决方案 > Amazon DynamoDB how to read populated Database in Golang?

问题描述

I have populated a local DynamoDB instance with some values from this JSON

[
    {
        "Id": 1,
        "Type": "fruit",
        "Name": "bananas",
        "Price": 0.25
    },
    {   
        "Id": 2,
        "Type": "fruit",
        "Name": "apples",
        "Price": 0.50
    },
    {
        "Id": 3,
        "Type": "fruit",
        "Name": "avocados",
        "Price": 1.25
    },
    {
        "Id": 4, 
        "Type": "vegetable",
        "Name": "carrots",
        "Price": 1.00
    } ]

And want to read, say all the items in this database. I believe Querying the database can do this, but in for my query input code I have

func main() {

    type Product struct {
        Id      int         `json:"Id"`
        Type    string      `json:"Type"`
        Name  string         `json:"Name"`
        Price float64      `json:"Price"`
    }

    config := &aws.Config{
        Region:   aws.String("us-west-2"),
        Endpoint: aws.String("http://localhost:8000"),
    }

    sess := session.Must(session.NewSession(config))

    svc := dynamodb.New(sess)


    input := &dynamodb.QueryInput{
        TableName:              aws.String("Products"),
        KeyConditions: map[string]*dynamodb.Condition{
            "Id": {
                ComparisonOperator: aws.String("EQ"),
                AttributeValueList: []*dynamodb.AttributeValue{
                    {
                        N: aws.String("1"),
                    },
                },

            },
        },

    }

    result, err := svc.Query(input)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    var products []Product
    err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &products)

    // print the response data
    for _, m := range products {
        fmt.Printf("Product: '%s' (%f)\n", m.Name, m.Price)
    }
}

so far and it only outputs bananas as the since the query is trying to match id = 1 (Id is my hash primary key).

I tried to modify the keycondition to something like this instead

"Id": {
        ComparisonOperator: aws.String("BETWEEN"),
        AttributeValueList: []*dynamodb.AttributeValue{
            {
                N: aws.String("0"),
            },
            {
                N: aws.String("5"),
            },
        },
    },

in an attempt to read every item but it says "ValidationException: Query key condition not supported". Am I doing the query statement incorrectly? Or is there some better way of listing items in dynamoDB? (Like if I wanted to list everything with "Type" == "fruit" for example, then output the first 3 items in the database.

标签: amazon-web-servicesgoamazon-dynamodb

解决方案


推荐阅读