卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34326本站已运行393

如何使用 KeyConditionExpression 和 v2 Go SDK 查询 AWS DynamoDb?

如何使用 keyconditionexpression 和 v2 go sdk 查询 aws dynamodb?

问题内容

我在 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 的表中获取所有记录,因此我尝试使用来自 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"}}'

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


正确答案


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

// 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: %vn", 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: %vn", releaseYear, err)
        } else {
            err = attributevalue.UnmarshalListOfMaps(response.Items, &movies)
            if err != nil {
                log.Printf("Couldn't unmarshal query response. Here's why: %vn", err)
            }
        }
    }
    return movies, err
}

您可以查看更多 GoV2 示例 此处

卓越飞翔博客
上一篇: 尝试 Twilio Whatsappp api 调用但收到错误 20422
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏