A Collection is a grouping of multiple Entities that share the same Partition Key. It allows you to perform a single, efficient DynamoDB query to retrieve related data across different entity types, similar to how a SQL VIEW works with joined tables.
Key Characteristics:
- Single Query: Collections use one DynamoDB query to retrieve results for all associated Entities, supporting Single Table Design.
- Index-Based: Collections are defined on an Index. To create a collection, multiple entities must point to the same
index and use the same collection name. - Uniqueness: A
collection name must be unique to a single common index across all entities within a Service. - Ordering Note: DynamoDB returns records in order of the Entity's sort key. In very large partitions, pagination might cause some entities to be missed; this can be mitigated using specific Index Types.
// Example of defining a collection via an index in two different entities
// Entity 1
const Employee = new Entity({
model: { entity: "employee", version: "1", service: "taskapp" },
// ... attributes
indexes: {
employee: {
collection: "assignments", // The collection name
index: "gsi2",
pk: { field: "gsi2pk", composite: ["employeeId"] },
sk: { field: "gsi2sk", composite: [] },
},
},
});
// Entity 2
const Task = new Entity({
model: { entity: "tasks", version: "1", service: "taskapp" },
// ... attributes
indexes: {
assigned: {
collection: "assignments", // Must match the collection name above
index: "gsi2", // Must match the index name above
pk: { field: "gsi2pk", composite: ["employeeId"] },
sk: { field: "gsi2sk", composite: ["projectId"] },
},
},
});