如何在DynamoDB的serverless.yml中定义组合键?
问题描述:
我试图定义一个拥有3列复合键dynamodb表。这可能吗?如何在DynamoDB的serverless.yml中定义组合键?
我见过有这样的代码示例和教程:
resources:
Resources:
TodosDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
-
AttributeName: id
AttributeType: S
KeySchema:
-
AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_TABLE}
但是,只有一个列,一个键。我的表看起来像这样:
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: N
- AttributeName: server
AttributeType: S
- AttributeName: room
AttributeType: S
- AttributeName: friendlyName
AttributeType: S
我要上id
,server
和room
的关键。用户可以位于同一台服务器上的多个房间中,也可以位于多台服务器上的多个房间中。但是,在三个键中,它总是独一无二的。
我不知道如何定义KeySchema
部分。任何帮助?
答
首先,您无法在DynamoDB中创建组合键(如在关系数据库中)。
您在表中获得的密钥是哈希和范围(也称为排序和可选)键。由于这限制了查询功能,因此DynamoDB支持创建名为全局二级索引(GSI)和本地二级索引(LSI)的索引来扩展查询功能。
根据您的模式,由于ID,服务器和房间的组合是唯一的,因此可以使用Hash密钥的连接,例如id_server_room
,以便表中的项目为唯一性强制执行。
然后,您可以创建ID,服务器和一房的属性。要有效地从这些属性查询,请根据需要创建GSI。