If you use a composite primary key in DynamoDB, each item you write to the table must have two elements in the primary key: a partition key 和 a sort key. You can think of these as comparable to SQL's GROUP BY 和 ORDER BY -- the partition key groups 所有 items with the same partition key together, 和 the items are ordered by the value in the sort key.
However, this design causes some problems. When updating an item in DynamoDB, you may not change any elements of the primary key. In this case, your primary key includes the UpdatedAt field, which changes whenever you update a ticket. Thus, anytime you update a ticket item, we would need first to delete the existing ticket item, then create a new ticket item with the updated primary key.
Instead, let's try a different approach. For our primary key, let's use two attributes that won't change. We'll keep the organization name as the partition key but switch to using TicketId as the sort key.
Now we can add a secondary index where the partition key is OrgName 和 the sort key is UpdatedAt. Each item from the base table is copied into the secondary index, 和 it looks as follows:
When modeling multiple entity types in a single table, you need to change how you design things. In our ticket tracking example above, we used OrgName 和 TicketId as the names of the partition key 和 sort key, respectively, in our primary key. However, if you're storing multiple entity types in a single table, it's unlikely each type has the same types of attributes.
Instead, we'll use more generic names for the elements in our primary key, such as PK for partition key 和 SK for sort key.
For example, imagine we have an application that includes both Organizations 和 Users. A User belongs to a particular Organization. We might have our PK 和 SK values modeled as follows:
Notice how both types of entities are in the same table 和 use different patterns for the PK 和 SK to co-exist. By using generic primary key attributes 和 storing different values there for different types of entities, we're 超载 我们的主键。对于不同的实体类型，属性意味着不同的事物。
Instead of doing that, I'll add an attribute called CustomerIndexId on my Customer items. Now my table looks as follows:
Notice the Customer items now have an attribute named CustomerIndexId as outlined in red.
Then, I create a secondary index called CustomerIndex that uses CustomerIndexId as the partition key. Only Customer items have that attribute, so they are the only ones projected into that index.
Only the Customer items are projected into this table. Now when the marketing department wants to find 所有 Customers to send marketing emails, they can run a Scan operation on the CustomerIndex, which is much more targeted 和 efficient. By isolating 所有 items of a particular type in the index, our sparse index makes finding 所有 items of that type much faster.