Screenplay projection children: identify collection items
A Screenplay children block maintains a collection inside a read model, such as a group’s members or an order’s line items. Each event needs to identify both the item it changes and the parent that contains it. Keeping those identities separate lets you update or remove one item without replacing the collection.
The group examples below use userId for the member and groupId for the group. For one optional object with no collection identity, use nested objects instead.
Basic Syntax
Section titled “Basic Syntax”children {CollectionName} identified by {Identifier} {child blocks}Simple Example
Section titled “Simple Example”projection Group => GroupReadModel from GroupCreated Name = name
children members identified by userId from UserAddedToGroup key userId parent groupId Name = userName Role = roleidentified by userId names the identity property on each collection element. key userId takes that identity from the event, and parent groupId selects the group read-model instance. Another event with the same two keys updates the same member; it does not append a duplicate.
Identifier Expression
Section titled “Identifier Expression”Choose a property of the child element that stays stable as its other fields change. The identifier belongs to the element, not to the parent:
children orders identified by orderIdchildren members identified by userIdchildren items identified by itemNumberOrdering the Children
Section titled “Ordering the Children”A new child is added at the end of the collection. To place it somewhere else, put one ordering line directly inside the children block:
| Line | A new child goes |
|---|---|
insert last |
At the end. This is what a block without an ordering does. |
insert first |
At the start, so the newest child comes first. |
sort by <property> [ascending|descending] |
Where the child property puts it: the collection is sorted after the child is added. ascending is the default. |
projection Model => ModelReadModel children entries identified by entryId sort by addedAt descending from EntryAdded key entryId parent modelId title = title addedAt = $eventContext.occurredThe order is stored, not computed when the read model is read. A child is placed when it is added; an update to an existing child, even one that changes its sort property, leaves it where it is. Sorting is stable, and a child without a value sorts first when ascending and last when descending. The sort property can be a dotted path, and it is checked against the child type (PLAY0960). A block takes one ordering line (PLAY0959); an ordering anywhere but directly inside children is an error (PLAY0958). The line can stand anywhere among the block’s lines; the printer writes it right after the block’s automap or no automap line, as it normalizes layout elsewhere.
Parent Key
Section titled “Parent Key”Use parent when the event carries the parent’s identity in a field. The child’s key and its parent serve different lookups:
children members identified by userId from UserAddedToGroup key userId parent groupId Name = userNameparent groupId selects the group before key userId selects the member. Without an explicit parent expression, the event source identity is the default parent key. Do not rely on that default when the event source identifies the user instead of the group.
A child event whose parent does not yet exist is retained for later resolution. It does not create the parent. Once the parent is available, the retained event can be applied to its collection.
With AutoMap
Section titled “With AutoMap”Place automap inside children to map matching event fields to child fields. It does not choose the child or parent key for you; the following shorthand relies on the default key behavior:
children members identified by userId automap
from UserAddedToGroup Role = roleMultiple Events
Section titled “Multiple Events”Use the same child and parent keys for all events in a member’s lifecycle. A role change then reaches the member added by the earlier event:
children members identified by userId from UserAddedToGroup key userId parent groupId Name = userName Role = role
from UserRoleChanged key userId parent groupId Role = roleEvery Block in Children
Section titled “Every Block in Children”Use every for fields that should change whenever an event handled at this collection level is applied. Here the member’s name and update time are kept beside its role:
children members identified by userId from UserAddedToGroup key userId parent groupId Role = role
every Name = userName UpdatedAt = $eventContext.occurredThese mappings target the member, not the group’s root fields. Make sure every event that uses the shared mapping supplies the fields it reads. For example, the Name = userName mapping requires userName on each event to which it applies.
Joins in Children
Section titled “Joins in Children”A member identified by a user ID can receive profile updates from that user’s event stream. Child joins match the child’s identity, so this works because userId identifies the member as well as the related user:
children members identified by userId from UserAddedToGroup key userId parent groupId UserId = userId Role = role
join User on UserId with UserCreated Name = name Email = email with UserUpdated Name = name Email = emailRemoval in Children
Section titled “Removal in Children”Keep removal inside the collection block to remove one member rather than the whole group. Use the same identity and parent expressions as the add and update events:
children members identified by userId from UserAddedToGroup key userId parent groupId Role = role
remove with UserRemovedFromGroup key userId parent groupIdUserRemovedFromGroup removes the matching member from members; the group and its other members remain. See Removal for root deletion and removal triggered by related events.
Nested Children
Section titled “Nested Children”A child can contain another collection. At each level, parent identifies the immediate containing item: a department belongs to a company, and a team belongs to a department.
children departments identified by deptId from DepartmentCreated key deptId parent companyId Name = name
children teams identified by teamId from TeamCreated key teamId parent deptId Name = nameExamples
Section titled “Examples”Group Membership
Section titled “Group Membership”This complete member lifecycle uses the same userId and groupId pair for addition, role changes, and removal. Auto-map supplies matching fields; explicit mappings handle the occurrence time and role:
projection Group => GroupReadModel from GroupCreated Name = name Description = description
children members identified by userId automap
from UserAddedToGroup key userId parent groupId AddedAt = $eventContext.occurred
from UserRoleChanged key userId parent groupId Role = role
remove with UserRemovedFromGroup key userId parent groupIdOrder with Line Items
Section titled “Order with Line Items”An order line has its own identity even when several lines refer to the same product. Using lineNumber as the child key keeps a quantity change or removal scoped to one line in the selected order:
projection Order => OrderReadModel from OrderPlaced OrderNumber = orderNumber CustomerId = customerId Total = 0
children items identified by lineNumber from LineItemAdded key lineNumber parent orderId ProductId = productId Quantity = quantity UnitPrice = price LineTotal = total
from LineItemQuantityChanged key lineNumber parent orderId Quantity = quantity LineTotal = total
remove with LineItemRemoved key lineNumber parent orderIdProject with Tasks
Section titled “Project with Tasks”Task events use taskId to update the child and projectId to find its project. In Chronicle, the every block records when the task was last changed. Screenplay’s reference evaluator does not support $eventContext.occurred in every mappings at a level with joins, so it cannot execute this example as written.
The assignee join in this example has a separate constraint: child joins match the task’s identity, not an arbitrary AssignedTo property. A user event will not enrich a task whose taskId differs from that user’s event source identity. Treat the lifecycle mappings and assignee lookup as separate design decisions:
projection Project => ProjectReadModel from ProjectCreated Name = name Status = "Active"
children tasks identified by taskId every LastModified = $eventContext.occurred
from TaskAdded key taskId parent projectId Title = title AssignedTo = assigneeId Status = "Open" CreatedAt = $eventContext.occurred
from TaskCompleted key taskId parent projectId Status = "Completed" CompletedAt = $eventContext.occurred
from TaskAssigned key taskId parent projectId AssignedTo = assigneeId
join User on AssignedTo with UserCreated AssigneeName = nameInvoice with Payments
Section titled “Invoice with Payments”One event can update a root total and record a child payment. The child block uses paymentId and invoiceNumber; the root from PaymentReceived below uses the event source identity. For both changes to reach the same invoice, those parent identities must agree:
projection Invoice => InvoiceReadModel from InvoiceIssued InvoiceNumber = number CustomerId = customerId Amount = amount Balance = amount
children payments identified by paymentId from PaymentReceived key paymentId parent invoiceNumber Amount = amount ReceivedAt = $eventContext.occurred Method = paymentMethod
from PaymentReceived subtract Balance by amountBlog Post with Comments
Section titled “Blog Post with Comments”Comments use commentId and postId for edits and deletion. As with task assignees, the author join does not provide arbitrary foreign-key matching inside the collection: it matches the comment’s identity. Mapping AuthorId alone does not make user events update comments with different identities:
projection BlogPost => BlogPostReadModel from PostPublished Title = title Content = content AuthorId = authorId PublishedAt = $eventContext.occurred
from PostUpdated Content = content UpdatedAt = $eventContext.occurred
children comments identified by commentId from CommentAdded key commentId parent postId AuthorId = authorId Content = content CreatedAt = $eventContext.occurred
from CommentEdited key commentId parent postId Content = content EditedAt = $eventContext.occurred
remove with CommentDeleted key commentId parent postId
join User on AuthorId with UserRegistered AuthorName = nameMulti-Level Nesting
Section titled “Multi-Level Nesting”Follow the immediate parent at every level of this company hierarchy. MemberAdded points to a team, not directly to the company that holds the whole read model:
projection Company => CompanyReadModel from CompanyCreated Name = name
children departments identified by deptId from DepartmentCreated key deptId parent companyId Name = name
children teams identified by teamId from TeamCreated key teamId parent deptId Name = name
children members identified by memberId from MemberAdded key memberId parent teamId Name = name Role = roleParent Key Expressions
Section titled “Parent Key Expressions”Select the parent from an event field, the event source identity, or a nested event property. These are alternatives; choose the one that contains the parent instance’s key:
children items identified by itemId from ItemAdded key itemId parent orderId # Event property # or parent $eventContext.eventSourceId # Event source ID # or parent order.id # Nested propertyAutoMap with Children
Section titled “AutoMap with Children”Child-level auto-map applies to matching fields across the child events. Keep explicit keys alongside it so matching property names do not obscure how events reach a particular member:
children members identified by userId automap
from UserAdded key userId parent groupId # Name, Email, etc. are auto-mapped
from UserUpdated key userId parent groupId # Updates are auto-mappedCollection Property
Section titled “Collection Property”Declare the collection and its element shape on the read model before projecting into it. In the group example, each member carries an identity along with fields such as name and role. The identified by property must belong to that element shape; it is not a label for the collection or a field on the parent.
Best Practices
Section titled “Best Practices”Choose the child identity before writing its mappings. A display name or role can change; the key used to find the member should not change with it. Keep the parent expression consistent across add, update, and removal events.
In executable specifications, check that two events for the same child update one element, that removing it leaves its siblings intact, and that an event for another parent cannot change this collection. For joins, also check that the joined event’s source identity is the child’s identity.
Common Patterns
Section titled “Common Patterns”Add/Update/Remove
Section titled “Add/Update/Remove”The same key pair carries the item through its lifecycle:
children items identified by itemId from ItemAdded key itemId parent parentId # properties
from ItemUpdated key itemId parent parentId # updated properties
remove with ItemRemoved key itemId parent parentIdEnrichment with Joins
Section titled “Enrichment with Joins”Membership is a useful child-join shape because the member and the user share an identity:
children members identified by userId from MemberAdded key userId parent groupId UserId = userId
join User on UserId with UserCreated Name = name Email = email with UserUpdated Name = name Email = emailVersioning
Section titled “Versioning”A version number can identify a child within one document. Each new number creates a distinct entry under that document’s key:
children versions identified by versionNumber from VersionCreated key versionNumber parent documentId Content = content CreatedAt = $eventContext.occurred CreatedBy = authorId