amazon-web-servicesdatabase-designamazon-dynamodbdynamodb-queriescomposite-key

Composite Sort Keys - duplicating attributes separately


From my understanding of composite sort keys on DynamoDB it provides greater flexibility on querying and can be lower cost than creating global secondary indexes.

Suppose I'm creating a blog with time-limited posts, and I want to be able to query only for posts that are

I would consider adopting the following composite sort key:

expiry#category#featured

Questions:

AI answers tend to be very on-the-fence about what you should use, so specific recommendations would be appreciated. The primary access pattern would be showing posts by category, with the ability to search for posts by user. Expired posts should never be visible.


Solution

  • Sort keys are always evaluated from left to right, if that suits your access pattern then it makes perfect sense. Here are some things to be careful on while using composite sort keys:

    1. Make sure it suits your read access pattern, making sure that you're aware it's evaluated from left to right. You cannot use contains or ends_with on a sort key.
    2. Make sure any values stored in the sort key are not updated frequently, you cannot update sort key values, you would need to deleteItem and the putItem.

    As for storing the values as stand alone attributes, I always suggest that you should. Access patterns may change in the future and having the ability to index on one of the attributes is important. Furthermore, it allows you to filter easily for reads and/or conditional writes as well as filter on Lambda events.