In the previous module, you set up access to your core entities in DynamoDB. The primary key structure solved a number of our main access patterns. This includes all patterns to read or write a single entity, as well as patterns to fetch multiple related entities, such as all photos that belong to a particular user.
In this module, you will learn about using an inverted index, a common design pattern for DynamoDB.
Secondary indexes are crucial data modeling tools in DynamoDB. They allow you to reshape your data to allow for alternate query patterns.
An inverted index is a common secondary index design pattern with DynamoDB. With an inverted index, you create a secondary index that is the inverse of the primary key for your table. The HASH key for your table becomes the RANGE key in your index, and the RANGE key for your table becomes the primary key for your index.
An inverted index is helpful in two scenarios. First, an inverted index is useful to query the “other” side of a many-to-many relationship. This is the case for your Friendship entity. With your primary key structure, you can query all followers for a particular user with a query against the table’s primary key. When you add an inverted index, you will be able to find the users that a user is following (the “followed”) by querying the inverted index.
An inverted index is also useful to query a one-to-many relationship for an entity that is itself the subject of a one-to-many relationship. You can see this with the Reaction entity in your table. There can be multiple reactions on a single photo, and each reaction will include the photo to which the reaction applies, the username of the reacting user, and the type of reaction. However, because a user can have many photos, the main identifier for a photo is in its RANGE key -- PHOTO#<USERNAME>#<TIMESTAMP>. Because of that, you cannot use your primary key to tie reactions to photos.
To satisfy the “View photo and reactions” access pattern, the data model places the photo identifier for a Reaction entity in the RANGE key. Now, when querying the inverted index, you can use the photo identifier to select the photo and all of its reactions in a single request. This is shown in Step 2 below.
Time to Complete Module: 40 Minutes