I have tried to create a global secondary index in dynamodb using the list type attribute as the hash key. I was able to create the index while the table creation but was not able to put items to that table. I have created the index using roles as the hash key. getting the following error when I'm going to save data.
An error occurred (ValidationException) when calling the PutItem operation: Invalid attribute value type
This is the data format that going to save
{
"product": {"S":"CHEMISTRY"},
"endDate": {"S":"2022-04-21T00:00:00.000Z"},
"roles": "L": [
{
"S": "INSTRUCTOR"
}
],
"Id": {"S":"1"},
"lifeCycle": {"S":"PUBLISHED"},
"courseId": {"S":"chem123"},
"startDate": {"S":"2021-09-27T00:00:00.000Z"}
}
The requirement is I need to get all the records from a particular table that contains the given user role in the list. Is it possible to create a GSI with a list type hash key or is there any method to fulfill this?
Thank you.
CodePudding user response:
Sadly you can't. From docs:
each primary key attribute must be defined as type string, number, or binary.
But you can create composite key instead.
CodePudding user response:
You can only use scalar values as key attributes in DynamoDB which means Sets and Lists won't work.
It sounds like your Role-Item relationship is many to many, which makes it tricky to model it in DynamoDB. In your case it may make sense to store the information twice:
- There is a list of roles at your item
- There is an item with the partition key role name and the sort key would be the product.
You'd have to update both of them when the relationship changes, but you can use a query to get all products that have a certain role.