scan.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // +build example
  2. package main
  3. import (
  4. "flag"
  5. "fmt"
  6. "os"
  7. "github.com/aws/aws-sdk-go/aws"
  8. "github.com/aws/aws-sdk-go/aws/session"
  9. "github.com/aws/aws-sdk-go/service/dynamodb"
  10. "github.com/aws/aws-sdk-go/service/dynamodb/expression"
  11. )
  12. func exitWithError(err error) {
  13. fmt.Fprintln(os.Stderr, err)
  14. os.Exit(1)
  15. }
  16. func main() {
  17. cfg := Config{}
  18. if err := cfg.Load(); err != nil {
  19. exitWithError(fmt.Errorf("failed to load config, %v", err))
  20. }
  21. // Create the config specifying the Region for the DynamoDB table.
  22. // If Config.Region is not set the region must come from the shared
  23. // config or AWS_REGION environment variable.
  24. awscfg := &aws.Config{}
  25. if len(cfg.Region) > 0 {
  26. awscfg.WithRegion(cfg.Region)
  27. }
  28. // Create the session that the DynamoDB service will use.
  29. sess := session.Must(session.NewSession(awscfg))
  30. // Create the DynamoDB service client to make the query request with.
  31. svc := dynamodb.New(sess)
  32. // Create the Expression to fill the input struct with.
  33. filt := expression.Name("Artist").Equal(expression.Value("No One You Know"))
  34. proj := expression.NamesList(expression.Name("SongTitle"), expression.Name("AlbumTitle"))
  35. expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
  36. if err != nil {
  37. exitWithError(fmt.Errorf("failed to create the Expression, %v", err))
  38. }
  39. // Build the query input parameters
  40. params := &dynamodb.ScanInput{
  41. ExpressionAttributeNames: expr.Names(),
  42. ExpressionAttributeValues: expr.Values(),
  43. FilterExpression: expr.Filter(),
  44. ProjectionExpression: expr.Projection(),
  45. TableName: aws.String(cfg.Table),
  46. }
  47. if cfg.Limit > 0 {
  48. params.Limit = aws.Int64(cfg.Limit)
  49. }
  50. // Make the DynamoDB Query API call
  51. result, err := svc.Scan(params)
  52. if err != nil {
  53. exitWithError(fmt.Errorf("failed to make Query API call, %v", err))
  54. }
  55. fmt.Println(result)
  56. }
  57. type Config struct {
  58. Table string // required
  59. Region string // optional
  60. Limit int64 // optional
  61. }
  62. func (c *Config) Load() error {
  63. flag.Int64Var(&c.Limit, "limit", 0, "Limit is the max items to be returned, 0 is no limit")
  64. flag.StringVar(&c.Table, "table", "", "Table to Query on")
  65. flag.StringVar(&c.Region, "region", "", "AWS Region the table is in")
  66. flag.Parse()
  67. if len(c.Table) == 0 {
  68. flag.PrintDefaults()
  69. return fmt.Errorf("table name is required.")
  70. }
  71. return nil
  72. }