1
votes

I saw several DynamoDB single-table design examples in which either the partition key or the sort key include values such as "name", "username" or "email address". Consider the following example (from AWS resources):

PK: HR-EMPLOYEE1, SK: John Smith

AWS GSI overloading table example

Would it be possible for the user to change his name?

If not, what would be a more suitable SK definition to allow this action?

2

2 Answers

3
votes

First a fact: Primary keys can not be updated. (Partition + Sort keys).

Answering your questions, Yes, a user could be able to change his/her name if the name is the sortKey, but it will enforce you to replace the current entry.

This require extra work on your side by handling all references and removing and creating a new item back. Dynamo does not have referencial integrity between rows. If you consider this path doing it inside a transaction might be a good idea.

As you might already saw on some videos & docs. It is a common practice having a sort key equal to the partition key. This could help later if you create a Reversed GSI enabling a good set of access patterns (while using single table design).

      PK               SK                ATTRIBUTES
USER#SOME_HASH  USER#SOME_HASH   NAME - EMAIL - ETC

from there, if you need to perform a search on the name, a Local Secondary Index (LSI) could do the trick. Something we usually do, is create a "slug" of the string to have a more powerful search.

Obviously a GSI would also enable you to perform this search, you could get it done by creating a sparse index.

Happy coding.

1
votes

You can't change a primary key after creation, so modeling either PK or SK on a changing attribute can be problematic. In the particular example you linked, it would be a better idea to select a unique ID to identify the user.

A common pattern to solve this problem includes creating a secondary index on the changing attribute. DynamoDB will copy all items from your main table into the secondary index in a reshaped form, allowing you to query on the reshaped form.

For example, consider the following user data, modeled with a unique ID and a GSI that includes the username as the sort key.

   PK              SK        username      GSI1PK           GSI1SK     

USER#<id>       USER#<id>    <username>    USER#<user_id>   <username>

The username can be changed and the index will update accordingly.