首页 > 后端开发 > Golang > 如何使用 KeyConditionExpression 和 v2 Go SDK 查询 AWS DynamoDb?

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

WBOY
发布: 2024-02-08 20:48:04
转载
681 人浏览过

如何使用 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 的查询

<code>// 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)
}
</code>
登录后复制

但是,我从 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: %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 示例 此处

以上是如何使用 KeyConditionExpression 和 v2 Go SDK 查询 AWS DynamoDb?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板