logo
post image

No Boolean Primary Key Allowed for DynamoDB Tables : How to Handle

DynamoDB has a boolean data type (BOOL) available however a boolean attribute cannot be set as the primary key (partition key or sort key) of a table or an index.

This comes as a shocker to people newly working on DynamoDB. While designing DynamoDB tables, the initial thought of setting a boolean attribute as the primary key usually comes up (most probably as a sort key).

So what to do ? : The solution is to use a String or Number data type instead of the Boolean type.

As an example to explain, let us take usefulangle.com which also uses DynamoDB as its database.

There is a Posts table that holds all posts. It has PostID (Number) as its primary (partition) key. An attribute PostVisible needs to signify whether the post is visible or not.

While creating or updating posts in the Posts table, I have used a String attribute for PostVisible that holds a value "YES" when the post is set as visible. For posts that are not set as visible, attribute PostVisible is not set for that row. I have done this to design a query to get the list of all visible posts.

I have also created a Global Secondary Index named PostsVisibleIndex whose primary key is PostVisible (partition key) and PostID (sort key). In this index obviously DynamoDB will store only the rows for which PostVisible has been set. Now I can query PostsVisibleIndex index to get the list of all visible posts. Since the sort key PostID is a Number, I can also query to get the list in ascending or descending order.

You may need a similar design to bypass the restriction of not able to set a boolean type as the primary key in DynamoDB tables or indexes.