如何使用DocumentClient.get在Amazon DynamoDB中按非主键属性查询表

时间:2018-08-17 21:13:20

标签: amazon-dynamodb serverless-framework

我似乎很难用AWS.DynamoDB.DocumentClient()。get()查询数据。

我正在使用无服务器,并使用以下模式设置serverless.yml

resources:
  Resources:
    ShortUrlsTable:
      Type: "AWS::DynamoDB::Table"
      Properties:
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
          - AttributeName: longUrl
            AttributeType: S
          - AttributeName: shortPath
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH
        GlobalSecondaryIndexes:
          - IndexName: longUrlIndex
            KeySchema:
              - AttributeName: longUrl
                KeyType: HASH
            ProvisionedThroughput:
              ReadCapacityUnits: 1
              WriteCapacityUnits: 1
            Projection:
              ProjectionType: ALL
          - IndexName: shortPathIndex
            KeySchema:
              - AttributeName: shortPath
                KeyType: HASH
            Projection:
              ProjectionType: ALL
            ProvisionedThroughput:
              ReadCapacityUnits: 1
              WriteCapacityUnits: 1
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:custom.tableName}

我想做的是使用shortUrlItemlongUrl在数据库中搜索shortPath

到目前为止,我已完成此设置:

dynamoDb = new AWS.DynamoDB.DocumentClient()

app.get("/:longUrl", (req, res) => {
  const {longUrl} = req.params

  const getParams = {
    TableName: SHORT_URLS_TABLE,
    Key: {longUrl},
  }

  dynamoDb.get(getParams, (error, result) => {
    res.send({...error, ...result})
  })
})

我似乎得到的只是此错误消息返回给我:

"message":"The provided key element does not match the schema","code":"ValidationException","time":"2018-08-17T20:39:27.765Z","requestId":"4RKNVG7ET1ORVF10H71M7AUABRVV4KQNSO5AEMVJF66Q9ASUAAJG","statusCode":400,"retryable":false,"retryDelay":21.513795782119505,"TableName":"short-urls-table-dev"

我似乎无法弄清楚是否正确查询或正确设置架构以使辅助索引成为表中的可搜索键。

1 个答案:

答案 0 :(得分:4)

我可以看到两个错误

1 :您的getParams错误。您在PK上提出了get请求,但在params部分中提供了GSI密钥。应该是

const getParams = {
  TableName: SHORT_URLS_TABLE,
  Key: {
    id: id, // Because id is the attribute of your HASH key. 
  }
}

这是错误的原因。您的哈希键不在属性longUrl上。

2 :无论如何,您无法在GSI上发出get请求。它没有GSI的设计。 GSI不会强制唯一性,因此同一GSI哈希密钥中可以有多个项目,因此您只能使用query而不是get

您要尝试的操作类似

const queryParams = {
    TableName: SHORT_URLS_TABLE,
    IndexName: 'longUrlIndex',
    KeyConditionExpression: 'longUrl = :longUrlValue',
    ExpressionAttributeValues: {
      'longUrlValue': longUrl
    }
};

dynamoDb.query(queryParams, (error, result) => {
  res.send({...error, ...result})
})