我用以下命令在dynamodb中创建了一个现有表

aws dynamodb create-table \
  --region us-east-1 \
  --table-name notifications \
  --attribute-definitions AttributeName=CustomerId,AttributeType=S AttributeName=Timestamp,AttributeType=N AttributeName=MessageId,AttributeType=S \
  --key-schema AttributeName=CustomerId,KeyType=HASH AttributeName=Timestamp,KeyType=RANGE \
  --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
  --global-secondary-indexes '[
      {
          "IndexName": "MessageId",
          "KeySchema": [
              {
                  "AttributeName": "MessageId",
                  "KeyType": "HASH"
              }
          ],
          "Projection": {
              "ProjectionType": "ALL"
          },
          "ProvisionedThroughput": {
              "ReadCapacityUnits": 5,
              "WriteCapacityUnits": 5
          }
      }
  ]'
}

我想在前面放一个API包装器,它允许我从CustomerId的表中获取所有记录,所以我try 使用v2 Go SDK中的查询

// GET /notifications/
func (api NotificationsApi) getNotifications(w http.ResponseWriter, r *http.Request) {
    var err error

    customerId := r.URL.Query().Get("customerId")
    if customerId == "" {
        api.errorResponse(w, "customerId query parameter required", http.StatusBadRequest)
        return
    }
    span, ctx := tracer.StartSpanFromContext(r.Context(), "notification.get")
    defer span.Finish(tracer.WithError(err))

    keyCond := expression.Key("CustomerId").Equal(expression.Value(":val"))
    expr, err := expression.NewBuilder().WithKeyCondition(keyCond).Build()

    input := &dynamodb.QueryInput{
        TableName:              aws.String("notifications"),
        KeyConditionExpression: expr.KeyCondition(),
        ExpressionAttributeValues: map[string]dynamodbTypes.AttributeValue{
            ":val": &dynamodbTypes.AttributeValueMemberS{Value: customerId},
        },
    }

    fmt.Println(*expr.KeyCondition())
    output, err := api.dynamoClient.Query(ctx, input)

    fmt.Println(output)
    fmt.Println(err)
}

但是,我从dynamodb得到了400分.

operation error DynamoDB: Query, https response error StatusCode: 400, RequestID: *****, api error ValidationException: Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #0

fmt.PrintLn(*expr.KeyCondition())的输出是#0 = :0

在本地运行此查询将返回预期结果

awslocal dynamodb query \
    --table-name notifications \
    --key-condition-expression "CustomerId = :val" \
    --expression-attribute-values '{":val":{"S":"localTesting"}}'

我也try 过包括时间戳,但我不认为这是必需的,因为我的终端命令没有它的工作.我不认为我取消引用是不恰当的.我知道我的发电机会话是有效的,因为我可以发布到我的包装器,并通过终端命令查看更新.

推荐答案

以下是可用作模板的查询示例:


// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
    DynamoDbClient *dynamodb.Client
    TableName      string
}



// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(releaseYear int) ([]Movie, error) {
    var err error
    var response *dynamodb.QueryOutput
    var movies []Movie
    keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
    expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
    if err != nil {
        log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
    } else {
        response, err = basics.DynamoDbClient.Query(context.TODO(), &dynamodb.QueryInput{
            TableName:                 aws.String(basics.TableName),
            ExpressionAttributeNames:  expr.Names(),
            ExpressionAttributeValues: expr.Values(),
            KeyConditionExpression:    expr.KeyCondition(),
        })
        if err != nil {
            log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
        } else {
            err = attributevalue.UnmarshalListOfMaps(response.Items, &movies)
            if err != nil {
                log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
            }
        }
    }
    return movies, err
}

您可以看到更多GoV2示例here

Go相关问答推荐

gorm插入不支持的数据

Term~T中的类型不能是类型参数,但可以是引用类型参数的切片

为什么Slices包中的函数定义Slice参数的类型参数?

如何在围棋中从多部分.Part中获取多部分.文件而不保存到磁盘?

如何执行asn 1 marshal/unmarshal和omit字段?

重新赋值变量时未清除动态类型-这是错误吗?

为什么要立即调用内联函数,而不仅仅是调用其包含的函数?

命令行参数在 Golang 程序中不正确地接受为参数

如何使用管理员权限启动 powershell 进程并重定向标准输入 (os.exec)

当图像是对象数组的元素时,如何显示存储为页面资源的图像?

errors.Wrap 和 errors.WithMessage 有什么区别

使用 os/exec 和在命令行执行之间的结果莫名其妙地不同

如何过滤来自 fsnotify 的重复系统消息

如何在切片增长时自动将切片的新元素添加到函数参数

获取切片元素的地址是否意味着 Go 中元素的副本?

使用 go.work 文件在多个测试文件上运行 go test 命令

我如何解码 aes-256-cfb

在 go 中将运行命令的标准输出发送到其标准输入

正则表达式处理数字签名的多个条目

Go:为一组单个结果实现 ManyDecode