How To Create The Dynamodb Table Using Serverless.yml And Delete The Items Of It Using Python Boto3?
Solution 1:
If you want to keep your KeySchema
you have to droplastname
from AttributeDefinitions
:
Resources:myTable:Type:AWS::DynamoDB::TableDeletionPolicy:RetainProperties:TableName:myTableAttributeDefinitions:-AttributeName:idAttributeType:S-AttributeName:firstnameAttributeType:SKeySchema:-AttributeName:idKeyType:HASH-AttributeName:firstnameKeyType:RANGEBillingMode:PAY_PER_REQUESTSSESpecification:SSEEnabled:true
But if you want to keep lastname
, you could definelocal secondary index for your table:
Resources:myTable:Type:AWS::DynamoDB::TableDeletionPolicy:RetainProperties:TableName:myTableAttributeDefinitions:-AttributeName:idAttributeType:S-AttributeName:firstnameAttributeType:S-AttributeName:lastnameAttributeType:SKeySchema:-AttributeName:idKeyType:HASH-AttributeName:firstnameKeyType:RANGELocalSecondaryIndexes:-IndexName:by-lastnameKeySchema:-AttributeName:idKeyType:HASH-AttributeName:lastnameKeyType:RANGEProjection:ProjectionType:ALLBillingMode:PAY_PER_REQUESTSSESpecification:SSEEnabled:true
With the above, you can sort for lastname
using the LSI, while firstname
would be used in the primary table.
how can I delete the items that first name is "First" in this table using python boto3?
You can't do it directly with or without boto3, unless you want to perform scan, which should be avoided as it can be expensive and is not efficient. To general solution is to define a Global Secondary Indexes where the firstname
would be the new primary key. Then you would query the GSI for the firstname
of interest to obtain the id
of the record you want to delete. If you have several records with same firstname
, which probably will be the case, you get a number of records back (GSI primary keys don't need to be unique, unlike for the primary table).
Example table with LSI and GSI:
Resources:myTable:Type:AWS::DynamoDB::TableDeletionPolicy:RetainProperties:TableName:myTableAttributeDefinitions:-AttributeName:idAttributeType:S-AttributeName:firstnameAttributeType:S-AttributeName:lastnameAttributeType:SKeySchema:-AttributeName:idKeyType:HASH-AttributeName:firstnameKeyType:RANGELocalSecondaryIndexes:-IndexName:by-lastnameKeySchema:-AttributeName:idKeyType:HASH-AttributeName:lastnameKeyType:RANGEProjection:ProjectionType:ALLGlobalSecondaryIndexes:-IndexName:firstname-gsiKeySchema:-AttributeName:firstnameKeyType:HASHProjection:ProjectionType:ALL#ProvisionedThroughput: # ProvisionedThroughput BillingMode:PAY_PER_REQUESTSSESpecification:SSEEnabled:true
Solution 2:
Reason is that all of your AttributeNames in AttributeDefinitions
must be included in the KeySchema
as well. I can see the lastname
attribute is missing in there.
Post a Comment for "How To Create The Dynamodb Table Using Serverless.yml And Delete The Items Of It Using Python Boto3?"