zoukankan      html  css  js  c++  java
  • dynamodb golang query one Item

    golang  dynamodb  query  oneItem  and unmarshal  to object 

    // +build example
    
    package main
    
    import (
        //    "flag"
        "fmt"
        "github.com/aws/aws-sdk-go/aws"
        "github.com/aws/aws-sdk-go/aws/session"
        "github.com/aws/aws-sdk-go/service/dynamodb"
        "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
        "os"
        "time"
    )
    
    func exitWithError(err error) {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    
    func main() {
        cfg := Config{}
        if err := cfg.Load(); err != nil {
            exitWithError(fmt.Errorf("failed to load config, %v", err))
        }
    
        // Create the config specifiing the Region for the DynamoDB table.
        // If Config.Region is not set the region must come from the shared
        // config or AWS_REGION environment variable.
        awscfg := &aws.Config{}
        if len(cfg.Region) > 0 {
            awscfg.WithRegion(cfg.Region)
        }
    
        // Create the session that the DynamoDB service will use.
        sess, err := session.NewSession(awscfg)
        if err != nil {
            exitWithError(fmt.Errorf("failed to create session, %v", err))
        }
    
        // Create the DynamoDB service client to make the query request with.
        svc := dynamodb.New(sess)
    
        // Build the query input parameters
        params := &dynamodb.ScanInput{
            TableName: aws.String(cfg.Table),
        }
        if cfg.Limit > 0 {
            params.Limit = aws.Int64(cfg.Limit)
        }
        fmt.Println("params is: ", params)
        // Make the DynamoDB Query API call
        result, err := svc.Scan(params)
        if err != nil {
            exitWithError(fmt.Errorf("failed to make Query API call, %v", err))
        }
    
        items := []Item{}
    
        // Unmarshal the Items field in the result value to the Item Go type.
        err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &items)
        if err != nil {
            exitWithError(fmt.Errorf("failed to unmarshal Query result items, %v", err))
        }
    
        // Print out the items returned
        for i, item := range items {
            fmt.Printf("%d:  UserID: %d, Time: %s Msg: %s  Count: %d SecretKey:%s DeviceId: %s CampaginId:%s 
         ", i, item.UserID, item.Time, item.Msg, item.Count, item.SecretKey, item.DeviceId, item.CampaginId)
            //fmt.Printf("	Num Data Values: %d
    ", len(item.Data))
        }
    
        /*    //1231241  deviceid
            params_del := &dynamodb.ScanInput{
                TableName: aws.String(cfg.Table),
    
            }
        */
        //query oneItem  demo
        params_get := &dynamodb.GetItemInput{
            Key: map[string]*dynamodb.AttributeValue{
                "deviceid": {
                    S: aws.String("1231241"),
                },
            },
            TableName: aws.String(cfg.Table), // Required
        }
    
        resp, err_get := svc.GetItem(params_get)
        oneItem := Item{}
        if err_get == nil {
            // resp is now filled
            fmt.Printf("resp type is %T 
     ", resp.Item)
            err = dynamodbattribute.UnmarshalMap(resp.Item, &oneItem)
            if err == nil {
                fmt.Printf("  UserID: %d, Time: %s Msg: %s  Count: %d SecretKey:%s DeviceId: %s CampaginId:%s 
         ", oneItem.UserID, oneItem.Time, oneItem.Msg, oneItem.Count, oneItem.SecretKey, oneItem.DeviceId, oneItem.CampaginId)
            } else {
                fmt.Println(" Unmarshal err :", err)
            }
            //fmt.Println("convert to Struct obj  err is ", err, "oneItem is:", oneItem)
        } else {
            fmt.Println("GetItem err is: ", err_get)
        }
    
    }
    
    type Item struct {
        UserID     int       // Hash key, a.k.a. partition key
        Time       time.Time // Range key, a.k.a. sort ke
        Msg        string    `dynamo:"Message"`
        Count      int       `dynamo:",omitempty"`
        SecretKey  string    `dynamo:"-"` // Ignored
        DeviceId   string    `dynamo:"deviceid"`
        CampaginId string    `dynamo:"campid"`
    }
    
    type Config struct {
        Table  string // required
        Region string // optional
        Limit  int64  // optional
    
    }
    
    func (c *Config) Load() error {
        //flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit")
        //flag.StringVar(&c.Table, "table", "", "Table to Query on")
        //flag.StringVar(&c.Region, "region", "", "AWS Region the table is in")
        //flag.Parse()
        c.Limit = 100
        c.Region = "ap-southeast-1"
        c.Table = "xxx_your_table_name"
        if len(c.Table) == 0 {
            //    flag.PrintDefaults()
            return fmt.Errorf("table name is required.")
        }
    
        return nil
    }
  • 相关阅读:
    第六章 优化服务器设置--高性能MySQL 施瓦茨--读书笔记
    skip-external-locking --mysql配置说明
    mysql配置文件my.cnf详解
    Response.Redirect 打开新窗口的两种方法
    .net中Response.End() 和Response.Redirect("http://dotnet.aspx.cc");
    onclientclick与onclick的问题.
    a href="javascript:void(0)" 是什么意思?加不加上有什么区别?
    ashx是什么文件
    CSS里的 no-repeat
    css中 repeat-x 的简单用法
  • 原文地址:https://www.cnblogs.com/lavin/p/6082502.html
Copyright © 2011-2022 走看看