Cratis Chronicle projections: build child collections
Child collections in Cratis Chronicle let you keep related items inside one read model, such as members inside a group. Configure both the parent key, which selects the group, and the child key, which selects the member to add, update, or remove.
Defining a projection with children
Section titled “Defining a projection with children”Use Children to select the collection property, then IdentifiedBy() to select the property that identifies each stored child. Each event mapping supplies the child key with UsingKey(). The example maps group details at the root and membership changes inside Members.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedForChildren(string Name, string Description);
[EventType]public record UserAddedToGroupForChildren(string UserId, string Role);
[EventType]public record UserRoleChangedForChildren(string UserId, string Role);
[EventType]public record UserRemovedFromGroupForChildren(string UserId);
public record GroupForChildren( string Name, string Description, IEnumerable<GroupMemberForChildren> Members);
public record GroupMemberForChildren( string UserId, string Role);
public class GroupProjectionForChildren : IProjectionFor<GroupForChildren>{ public void Define(IProjectionBuilderFor<GroupForChildren> builder) => builder .From<GroupCreatedForChildren>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<UserAddedToGroupForChildren>(b => b .UsingKey(e => e.UserId)) .From<UserRoleChangedForChildren>(b => b .UsingKey(e => e.UserId)) .RemovedWith<UserRemovedFromGroupForChildren>(b => b .UsingKey(e => e.UserId)));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class GroupCreatedForChildren(val name: String, val description: String)
@EventTypedata class UserAddedToGroupForChildren(val userId: String, val role: String)
@EventTypedata class UserRoleChangedForChildren(val userId: String, val role: String)
data class GroupForChildren( val name: String = "", val description: String = "", val members: List<GroupMemberForChildren> = emptyList())
data class GroupMemberForChildren( val userId: String = "", val role: String = "")
class GroupProjectionForChildren : IProjectionFor<GroupForChildren> { override fun define(builder: IProjectionBuilderFor<GroupForChildren>) { builder .from(GroupCreatedForChildren::class) .children(GroupForChildren::members, GroupMemberForChildren::class) { children -> children .identifiedBy("userId") .from(UserAddedToGroupForChildren::class) { it.usingKey("userId") } .from(UserRoleChangedForChildren::class) { it.usingKey("userId") } } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
import java.util.List;
@EventTyperecord GroupCreatedForChildren(String name, String description) {}
@EventTyperecord UserAddedToGroupForChildren(String userId, String role) {}
@EventTyperecord UserRoleChangedForChildren(String userId, String role) {}
record GroupForChildren(String name, String description, List<GroupMemberForChildren> members) {}
record GroupMemberForChildren(String userId, String role) {}
class GroupProjectionForChildren implements IProjectionFor<GroupForChildren> { @Override public void define(IProjectionBuilderFor<GroupForChildren> builder) { builder .from(GroupCreatedForChildren.class) .children("members", GroupMemberForChildren.class, children -> { children .identifiedBy("userId") .from(UserAddedToGroupForChildren.class, fb -> { fb.usingKey("userId"); }) .from(UserRoleChangedForChildren.class, fb -> { fb.usingKey("userId"); }); }); }}defmodule MyApp.Events.GroupCreatedForChildren do use Chronicle.Events.EventType, id: "group-created-for-children"
defstruct [:name, :description]end
defmodule MyApp.Events.UserAddedToGroupForChildren do use Chronicle.Events.EventType, id: "user-added-to-group-for-children"
defstruct [:user_id, :role]end
defmodule MyApp.Events.UserRoleChangedForChildren do use Chronicle.Events.EventType, id: "user-role-changed-for-children"
defstruct [:user_id, :role]end
defmodule MyApp.Events.UserRemovedFromGroupForChildren do use Chronicle.Events.EventType, id: "user-removed-from-group-for-children"
defstruct [:user_id]end
defmodule MyApp.ReadModels.GroupMemberForChildren do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupForChildren do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMemberForChildren}]
defstruct name: nil, description: nil, members: []end
defmodule MyApp.Projections.GroupProjectionForChildren do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupForChildren
alias MyApp.Events.{ GroupCreatedForChildren, UserAddedToGroupForChildren, UserRemovedFromGroupForChildren, UserRoleChangedForChildren }
from GroupCreatedForChildren
children :members, identified_by: :user_id do from UserAddedToGroupForChildren, key: :user_id, set: [user_id: :user_id, role: :role]
from UserRoleChangedForChildren, key: :user_id, set: [role: :role]
removed_with UserRemovedFromGroupForChildren, key: :user_id endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedForChildren { @field(String) readonly name: string; @field(String) readonly description: string;
constructor(name: string, description: string) { this.name = name; this.description = description; }}
@eventType()class UserAddedToGroupForChildren { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class UserRoleChangedForChildren { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class UserRemovedFromGroupForChildren { @field(String) readonly userId: string;
constructor(userId: string) { this.userId = userId; }}
class GroupMemberForChildren { userId = ''; role = '';}
class GroupForChildren { name = ''; description = ''; members: GroupMemberForChildren[] = [];}
@projection()class GroupProjectionForChildren implements IProjectionFor<GroupForChildren> { define(builder: IProjectionBuilderFor<GroupForChildren>): void { builder .from(GroupCreatedForChildren) .children<GroupMemberForChildren>(m => m.members, children => children .identifiedBy(m => m.userId) .from(UserAddedToGroupForChildren, b => b .usingKey(e => e.userId)) .from(UserRoleChangedForChildren, b => b .usingKey(e => e.userId)) .removedWith(UserRemovedFromGroupForChildren, b => b .usingKey(e => e.userId))); }}Read model with children
Section titled “Read model with children”The read model includes a collection property for the children:
public record GroupWithMembers( string Name, string Description, IEnumerable<GroupMember> Members);
public record GroupMember( string UserId, string Role);data class GroupWithMembers( val name: String = "", val description: String = "", val members: List<GroupMember> = emptyList())
data class GroupMember( val userId: String = "", val role: String = "")import java.util.List;
record GroupWithMembers(String name, String description, List<GroupMember> members) {}
record GroupMember(String userId, String role) {}defmodule MyApp.ReadModels.GroupMember do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupWithMembers do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMember}]
defstruct name: nil, description: nil, members: []endclass GroupMember { userId = ''; role = '';}
class GroupWithMembers { name = ''; description = ''; members: GroupMember[] = [];}Event definitions
Section titled “Event definitions”Membership events carry a UserId so the projection can find the affected member. The event source ID will identify the parent group in this example:
using Cratis.Chronicle.Events;
[EventType]public record GroupCreatedForChildEvents(string Name, string Description);
[EventType]public record UserAddedToGroupForChildEvents(string UserId, string Role);
[EventType]public record UserRoleChangedForChildEvents(string UserId, string Role);
[EventType]public record UserRemovedFromGroupForChildEvents(string UserId);import io.cratis.chronicle.events.EventType
@EventTypedata class GroupCreatedForChildEvents(val name: String, val description: String)
@EventTypedata class UserAddedToGroupForChildEvents(val userId: String, val role: String)
@EventTypedata class UserRoleChangedForChildEvents(val userId: String, val role: String)
@EventTypedata class UserRemovedFromGroupForChildEvents(val userId: String)import io.cratis.chronicle.events.EventType;
@EventTyperecord GroupCreatedForChildEvents(String name, String description) {}
@EventTyperecord UserAddedToGroupForChildEvents(String userId, String role) {}
@EventTyperecord UserRoleChangedForChildEvents(String userId, String role) {}
@EventTyperecord UserRemovedFromGroupForChildEvents(String userId) {}defmodule MyApp.Events.GroupCreatedForChildEvents do use Chronicle.Events.EventType, id: "group-created-for-child-events"
defstruct [:name, :description]end
defmodule MyApp.Events.UserAddedToGroupForChildEvents do use Chronicle.Events.EventType, id: "user-added-to-group-for-child-events"
defstruct [:user_id, :role]end
defmodule MyApp.Events.UserRoleChangedForChildEvents do use Chronicle.Events.EventType, id: "user-role-changed-for-child-events"
defstruct [:user_id, :role]end
defmodule MyApp.Events.UserRemovedFromGroupForChildEvents do use Chronicle.Events.EventType, id: "user-removed-from-group-for-child-events"
defstruct [:user_id]endimport { eventType } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedForChildEvents { @field(String) readonly name: string; @field(String) readonly description: string;
constructor(name: string, description: string) { this.name = name; this.description = description; }}
@eventType()class UserAddedToGroupForChildEvents { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class UserRoleChangedForChildEvents { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class UserRemovedFromGroupForChildEvents { @field(String) readonly userId: string;
constructor(userId: string) { this.userId = userId; }}How children work
Section titled “How children work”The root From mapping updates group details. The mappings inside Children update members instead. For each membership event, Chronicle first resolves the parent group, then matches the event’s child key against the property selected by IdentifiedBy().
A member with that key is updated if it exists, or added if it does not. Removal uses a separate RemovedWith<>() mapping.
Parent key resolution
Section titled “Parent key resolution”By default, Chronicle uses EventSourceId, the identifier attached when the event is appended, as the parent key. Leave that default when membership events are appended under the group’s ID. Choose a parent key from event content when they are appended under another ID, such as the user’s.
Default behavior (EventSourceId as parent key)
Section titled “Default behavior (EventSourceId as parent key)”When the event source ID is the group’s ID, only the child key needs an explicit mapping:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedWithDefaultParentKey(string Name);
[EventType]public record UserAddedWithDefaultParentKey(string UserId, string Role);
public record GroupWithDefaultParentKey( string Name, IEnumerable<GroupMemberWithDefaultParentKey> Members);
public record GroupMemberWithDefaultParentKey( string UserId, string Role);
public class GroupWithDefaultParentKeyProjection : IProjectionFor<GroupWithDefaultParentKey>{ public void Define(IProjectionBuilderFor<GroupWithDefaultParentKey> builder) => builder .From<GroupCreatedWithDefaultParentKey>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<UserAddedWithDefaultParentKey>(b => b .UsingKey(e => e.UserId)));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class GroupCreatedWithDefaultParentKey(val name: String)
@EventTypedata class UserAddedWithDefaultParentKey(val userId: String, val role: String)
data class GroupWithDefaultParentKey( val name: String = "", val members: List<GroupMemberWithDefaultParentKey> = emptyList())
data class GroupMemberWithDefaultParentKey( val userId: String = "", val role: String = "")
class GroupWithDefaultParentKeyProjection : IProjectionFor<GroupWithDefaultParentKey> { override fun define(builder: IProjectionBuilderFor<GroupWithDefaultParentKey>) { builder .from(GroupCreatedWithDefaultParentKey::class) .children(GroupWithDefaultParentKey::members, GroupMemberWithDefaultParentKey::class) { children -> children .identifiedBy("userId") .from(UserAddedWithDefaultParentKey::class) { it.usingKey("userId") } } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
import java.util.List;
@EventTyperecord GroupCreatedWithDefaultParentKey(String name) {}
record GroupWithDefaultParentKey(String name, List<GroupMemberWithDefaultParentKey> members) {}
record GroupMemberWithDefaultParentKey(String userId, String role) {}
class GroupWithDefaultParentKeyProjection implements IProjectionFor<GroupWithDefaultParentKey> { @Override public void define(IProjectionBuilderFor<GroupWithDefaultParentKey> builder) { builder .from(GroupCreatedWithDefaultParentKey.class) .children("members", GroupMemberWithDefaultParentKey.class, children -> { children .identifiedBy("userId") .from(UserAddedWithDefaultParentKey.class, fb -> { fb.usingKey("userId"); }); }); }}defmodule MyApp.Events.GroupCreatedWithDefaultParentKey do use Chronicle.Events.EventType, id: "group-created-with-default-parent-key"
defstruct [:name]end
defmodule MyApp.Events.UserAddedWithDefaultParentKey do use Chronicle.Events.EventType, id: "user-added-with-default-parent-key"
defstruct [:user_id, :role]end
defmodule MyApp.ReadModels.GroupMemberWithDefaultParentKey do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupWithDefaultParentKey do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMemberWithDefaultParentKey}]
defstruct name: nil, members: []end
defmodule MyApp.Projections.GroupWithDefaultParentKeyProjection do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupWithDefaultParentKey
alias MyApp.Events.{GroupCreatedWithDefaultParentKey, UserAddedWithDefaultParentKey}
from GroupCreatedWithDefaultParentKey
# parent_key is not given, so the event source id of UserAddedWithDefaultParentKey # identifies the group the member belongs to. children :members, identified_by: :user_id do from UserAddedWithDefaultParentKey, key: :user_id, set: [user_id: :user_id, role: :role] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedWithDefaultParentKey { @field(String) readonly name: string;
constructor(name: string) { this.name = name; }}
@eventType()class UserAddedWithDefaultParentKey { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
class GroupMemberWithDefaultParentKey { userId = ''; role = '';}
class GroupWithDefaultParentKey { name = ''; members: GroupMemberWithDefaultParentKey[] = [];}
@projection()class GroupWithDefaultParentKeyProjection implements IProjectionFor<GroupWithDefaultParentKey> { define(builder: IProjectionBuilderFor<GroupWithDefaultParentKey>): void { builder .from(GroupCreatedWithDefaultParentKey) .children<GroupMemberWithDefaultParentKey>(m => m.members, children => children .identifiedBy(m => m.userId) .from(UserAddedWithDefaultParentKey, b => b .usingKey(e => e.userId))); }}When you append the event:
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;
public class GroupMembershipWithDefaultParentKey(IEventStore eventStore){ public Task AddUserToGroup(EventSourceId groupId, string userId, string role) => eventStore.EventLog.Append(groupId, new UserAddedWithDefaultParentKey(userId, role));}import io.cratis.chronicle.IEventStore
class GroupMembershipWithDefaultParentKey(private val eventStore: IEventStore) { suspend fun addUserToGroup(groupId: String, userId: String, role: String) = eventStore.eventLog.append(groupId, UserAddedWithDefaultParentKey(userId, role))}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.EventLogJavaBridge;
@EventTyperecord UserAddedWithDefaultParentKey(String userId, String role) {}
class GroupMembershipWithDefaultParentKey { private final EventStore eventStore;
GroupMembershipWithDefaultParentKey(EventStore eventStore) { this.eventStore = eventStore; }
void addUserToGroup(String groupId, String userId, String role) { EventLogJavaBridge.append(eventStore.getEventLog(), groupId, new UserAddedWithDefaultParentKey(userId, role), null); }}defmodule MyApp.GroupMembershipWithDefaultParentKey do alias MyApp.Events.UserAddedWithDefaultParentKey
def add_user_to_group(group_id, user_id, role) do Chronicle.append( group_id, struct!(UserAddedWithDefaultParentKey, user_id: user_id, role: role) ) endendimport { IEventStore } from '@cratis/chronicle';
class GroupMembershipWithDefaultParentKey { constructor(private readonly eventStore: IEventStore) {}
addUserToGroup(groupId: string, userId: string, role: string): Promise<unknown> { return this.eventStore.eventLog.append(groupId, new UserAddedWithDefaultParentKey(userId, role)); }}The groupId passed to Append selects the parent group. The event’s UserId selects the member within it.
Extracting parent key from event content
Section titled “Extracting parent key from event content”Use UsingParentKey() when the event contains the parent’s ID but is appended under a different event source ID:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedWithEventParentKey(string Name);
[EventType]public record UserAddedWithEventParentKey(string GroupId, string UserId, string Role);
public record GroupWithEventParentKey( string Name, IEnumerable<GroupMemberWithEventParentKey> Members);
public record GroupMemberWithEventParentKey( string UserId, string Role);
public class GroupWithEventParentKeyProjection : IProjectionFor<GroupWithEventParentKey>{ public void Define(IProjectionBuilderFor<GroupWithEventParentKey> builder) => builder .From<GroupCreatedWithEventParentKey>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<UserAddedWithEventParentKey>(b => b .UsingParentKey(e => e.GroupId) .UsingKey(e => e.UserId)));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class GroupCreatedWithEventParentKey(val name: String)
@EventTypedata class UserAddedWithEventParentKey(val groupId: String, val userId: String, val role: String)
data class GroupWithEventParentKey( val name: String = "", val members: List<GroupMemberWithEventParentKey> = emptyList())
data class GroupMemberWithEventParentKey( val userId: String = "", val role: String = "")
class GroupWithEventParentKeyProjection : IProjectionFor<GroupWithEventParentKey> { override fun define(builder: IProjectionBuilderFor<GroupWithEventParentKey>) { builder .from(GroupCreatedWithEventParentKey::class) .children(GroupWithEventParentKey::members, GroupMemberWithEventParentKey::class) { children -> children .identifiedBy("userId") .from(UserAddedWithEventParentKey::class) { it.usingParentKey("groupId") .usingKey("userId") } } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
import java.util.List;
@EventTyperecord GroupCreatedWithEventParentKey(String name) {}
record GroupWithEventParentKey(String name, List<GroupMemberWithEventParentKey> members) {}
record GroupMemberWithEventParentKey(String userId, String role) {}
class GroupWithEventParentKeyProjection implements IProjectionFor<GroupWithEventParentKey> { @Override public void define(IProjectionBuilderFor<GroupWithEventParentKey> builder) { builder .from(GroupCreatedWithEventParentKey.class) .children("members", GroupMemberWithEventParentKey.class, children -> { children .identifiedBy("userId") .from(UserAddedWithEventParentKey.class, fb -> { fb.usingParentKey("groupId"); fb.usingKey("userId"); }); }); }}defmodule MyApp.Events.GroupCreatedWithEventParentKey do use Chronicle.Events.EventType, id: "group-created-with-event-parent-key"
defstruct [:name]end
defmodule MyApp.Events.UserAddedWithEventParentKey do use Chronicle.Events.EventType, id: "user-added-with-event-parent-key"
defstruct [:group_id, :user_id, :role]end
defmodule MyApp.ReadModels.GroupMemberWithEventParentKey do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupWithEventParentKey do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMemberWithEventParentKey}]
defstruct name: nil, members: []end
defmodule MyApp.Projections.GroupWithEventParentKeyProjection do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupWithEventParentKey
alias MyApp.Events.{GroupCreatedWithEventParentKey, UserAddedWithEventParentKey}
from GroupCreatedWithEventParentKey
children :members, identified_by: :user_id do from UserAddedWithEventParentKey, parent_key: :group_id, key: :user_id, set: [user_id: :user_id, role: :role] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedWithEventParentKey { @field(String) readonly name: string;
constructor(name: string) { this.name = name; }}
@eventType()class UserAddedWithEventParentKey { @field(String) readonly groupId: string; @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(groupId: string, userId: string, role: string) { this.groupId = groupId; this.userId = userId; this.role = role; }}
class GroupMemberWithEventParentKey { userId = ''; role = '';}
class GroupWithEventParentKey { name = ''; members: GroupMemberWithEventParentKey[] = [];}
@projection()class GroupWithEventParentKeyProjection implements IProjectionFor<GroupWithEventParentKey> { define(builder: IProjectionBuilderFor<GroupWithEventParentKey>): void { builder .from(GroupCreatedWithEventParentKey) .children<GroupMemberWithEventParentKey>(m => m.members, children => children .identifiedBy(m => m.userId) .from(UserAddedWithEventParentKey, b => b .usingParentKey(e => e.groupId) .usingKey(e => e.userId))); }}When you append the event:
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;
public class GroupMembershipWithEventParentKey(IEventStore eventStore){ public Task AddUserToGroup(EventSourceId userId, string groupId, string role) => eventStore.EventLog.Append(userId, new UserAddedWithEventParentKey(groupId, userId.Value, role));}import io.cratis.chronicle.IEventStore
class GroupMembershipWithEventParentKey(private val eventStore: IEventStore) { suspend fun addUserToGroup(userId: String, groupId: String, role: String) = eventStore.eventLog.append(userId, UserAddedWithEventParentKey(groupId, userId, role))}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.EventLogJavaBridge;
@EventTyperecord UserAddedWithEventParentKey(String groupId, String userId, String role) {}
class GroupMembershipWithEventParentKey { private final EventStore eventStore;
GroupMembershipWithEventParentKey(EventStore eventStore) { this.eventStore = eventStore; }
void addUserToGroup(String userId, String groupId, String role) { EventLogJavaBridge.append(eventStore.getEventLog(), userId, new UserAddedWithEventParentKey(groupId, userId, role), null); }}defmodule MyApp.GroupMembershipWithEventParentKey do alias MyApp.Events.UserAddedWithEventParentKey
def add_user_to_group(user_id, group_id, role) do Chronicle.append( user_id, struct!(UserAddedWithEventParentKey, group_id: group_id, user_id: user_id, role: role) ) endendimport { IEventStore } from '@cratis/chronicle';
class GroupMembershipWithEventParentKey { constructor(private readonly eventStore: IEventStore) {}
addUserToGroup(userId: string, groupId: string, role: string): Promise<unknown> { return this.eventStore.eventLog.append(userId, new UserAddedWithEventParentKey(groupId, userId, role)); }}Here, the event is appended under userId. Its GroupId property selects the parent group, and UserId still selects the member.
Using EventSourceId explicitly with UsingParentKeyFromContext
Section titled “Using EventSourceId explicitly with UsingParentKeyFromContext”Use UsingParentKeyFromContext(ctx => ctx.EventSourceId) if you want the default parent-key choice to be visible in the definition:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedWithContextParentKey(string Name);
[EventType]public record UserAddedWithContextParentKey(string UserId, string Role);
public record GroupWithContextParentKey( string Name, IEnumerable<GroupMemberWithContextParentKey> Members);
public record GroupMemberWithContextParentKey( string UserId, string Role);
public class GroupWithContextParentKeyProjection : IProjectionFor<GroupWithContextParentKey>{ public void Define(IProjectionBuilderFor<GroupWithContextParentKey> builder) => builder .From<GroupCreatedWithContextParentKey>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<UserAddedWithContextParentKey>(b => b .UsingParentKeyFromContext(c => c.EventSourceId) .UsingKey(e => e.UserId)));}Kotlin does not support this workflow yet.`IChildFromBuilderFor` only has `usingParentKey(eventPropertyName: String)`, which reads the parentkey from an event property. There is no `usingParentKeyFromContext`-equivalent for explicitlydocumenting that the EventSourceId is used — that is only ever the implicit default.Java does not support this workflow yet.`IChildFromBuilderFor` only has `usingParentKey(eventPropertyName: String)`, which reads the parentkey from an event property. There is no `usingParentKeyFromContext`-equivalent for explicitlydocumenting that the EventSourceId is used — that is only ever the implicit default.defmodule MyApp.Events.GroupCreatedWithContextParentKey do use Chronicle.Events.EventType, id: "group-created-with-context-parent-key"
defstruct [:name]end
defmodule MyApp.Events.UserAddedWithContextParentKey do use Chronicle.Events.EventType, id: "user-added-with-context-parent-key"
defstruct [:user_id, :role]end
defmodule MyApp.ReadModels.GroupMemberWithContextParentKey do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupWithContextParentKey do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMemberWithContextParentKey}]
defstruct name: nil, members: []end
defmodule MyApp.Projections.GroupWithContextParentKeyProjection do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupWithContextParentKey
alias MyApp.Events.{GroupCreatedWithContextParentKey, UserAddedWithContextParentKey}
from GroupCreatedWithContextParentKey
children :members, identified_by: :user_id do from UserAddedWithContextParentKey, parent_key: :event_source_id, key: :user_id, set: [user_id: :user_id, role: :role] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedWithContextParentKey { @field(String) readonly name: string;
constructor(name: string) { this.name = name; }}
@eventType()class UserAddedWithContextParentKey { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
class GroupMemberWithContextParentKey { userId = ''; role = '';}
class GroupWithContextParentKey { name = ''; members: GroupMemberWithContextParentKey[] = [];}
@projection()class GroupWithContextParentKeyProjection implements IProjectionFor<GroupWithContextParentKey> { define(builder: IProjectionBuilderFor<GroupWithContextParentKey>): void { builder .from(GroupCreatedWithContextParentKey) .children<GroupMemberWithContextParentKey>(m => m.members, children => children .identifiedBy(m => m.userId) .from(UserAddedWithContextParentKey, b => b .usingParentKeyFromContext('eventSourceId') .usingKey(e => e.userId))); }}This selects the same parent as leaving the parent key unspecified.
When to use each approach
Section titled “When to use each approach”| Parent identifier location | Mapping |
|---|---|
| Event source ID | Leave the parent key unspecified. |
| Event content | Use UsingParentKey(e => e.Property). |
| Event source ID, stated explicitly | Use UsingParentKeyFromContext(ctx => ctx.EventSourceId). |
Child lifecycle
Section titled “Child lifecycle”A From mapping adds a child when its key is new and updates the child when the key already exists. This means an event named as an update can also create a missing child. Use RemovedWith<>() for removal rather than mapping a deletion event through From.
Removing children
Section titled “Removing children”Configure the removal event with the same child-key strategy used by the add and update mappings:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedWithRemoval(string Name);
[EventType]public record UserAddedWithRemoval(string UserId, string Role);
[EventType]public record UserRemovedWithRemoval(string UserId);
public record GroupWithRemoval( string Name, IEnumerable<GroupMemberWithRemoval> Members);
public record GroupMemberWithRemoval( string UserId, string Role);
public class GroupWithRemovalProjection : IProjectionFor<GroupWithRemoval>{ public void Define(IProjectionBuilderFor<GroupWithRemoval> builder) => builder .From<GroupCreatedWithRemoval>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<UserAddedWithRemoval>(b => b .UsingKey(e => e.UserId)) .RemovedWith<UserRemovedWithRemoval>(b => b .UsingKey(e => e.UserId)));}Kotlin does not support this workflow yet.`IChildrenBuilderFor`/`IChildFromBuilderFor` have no `removedWith`-equivalent method, and`ProjectionsService` never wires a removal list into the children definition it builds from thefluent builder — only model-bound `@RemovedWith`/`@RemovedWithJoin` on a `@ChildrenFrom` propertycan remove a single child today.Java does not support this workflow yet.`IChildrenBuilderFor`/`IChildFromBuilderFor` have no `removedWith`-equivalent method, and`ProjectionsService` never wires a removal list into the children definition it builds from thefluent builder — only model-bound `@RemovedWith`/`@RemovedWithJoin` on a `@ChildrenFrom` propertycan remove a single child today.defmodule MyApp.Events.GroupCreatedWithRemoval do use Chronicle.Events.EventType, id: "group-created-with-removal"
defstruct [:name]end
defmodule MyApp.Events.UserAddedWithRemoval do use Chronicle.Events.EventType, id: "user-added-with-removal"
defstruct [:user_id, :role]end
defmodule MyApp.Events.UserRemovedWithRemoval do use Chronicle.Events.EventType, id: "user-removed-with-removal"
defstruct [:user_id]end
defmodule MyApp.ReadModels.GroupMemberWithRemoval do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupWithRemoval do use Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.GroupMemberWithRemoval}]
defstruct name: nil, members: []end
defmodule MyApp.Projections.GroupWithRemovalProjection do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupWithRemoval
alias MyApp.Events.{GroupCreatedWithRemoval, UserAddedWithRemoval, UserRemovedWithRemoval}
from GroupCreatedWithRemoval
children :members, identified_by: :user_id do from UserAddedWithRemoval, key: :user_id, set: [user_id: :user_id, role: :role] removed_with UserRemovedWithRemoval, key: :user_id endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedWithRemoval { @field(String) readonly name: string;
constructor(name: string) { this.name = name; }}
@eventType()class UserAddedWithRemoval { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class UserRemovedWithRemoval { @field(String) readonly userId: string;
constructor(userId: string) { this.userId = userId; }}
class GroupMemberWithRemoval { userId = ''; role = '';}
class GroupWithRemoval { name = ''; members: GroupMemberWithRemoval[] = [];}
@projection()class GroupWithRemovalProjection implements IProjectionFor<GroupWithRemoval> { define(builder: IProjectionBuilderFor<GroupWithRemoval>): void { builder .from(GroupCreatedWithRemoval) .children<GroupMemberWithRemoval>(m => m.members, children => children .identifiedBy(m => m.userId) .from(UserAddedWithRemoval, b => b .usingKey(e => e.userId)) .removedWith(UserRemovedWithRemoval, b => b .usingKey(e => e.userId))); }}When the removal event arrives, Chronicle finds the member by e.UserId and removes it. If no member has that key, the collection stays unchanged. Add separate RemovedWith<>() mappings for other event types that remove members.
Multiple child collections
Section titled “Multiple child collections”Call Children for each collection the read model needs. Each collection has its own identity and event mappings:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record GroupCreatedWithMultipleCollections(string Name);
[EventType]public record MemberAddedToGroup(string UserId, string Role);
[EventType]public record TaskAssignedToGroup(string TaskId, string Title);
public record GroupWithMultipleCollections( string Name, IEnumerable<GroupMemberInMultipleCollections> Members, IEnumerable<GroupTaskInMultipleCollections> Tasks);
public record GroupMemberInMultipleCollections( string UserId, string Role);
public record GroupTaskInMultipleCollections( string TaskId, string Title);
public class GroupWithMultipleCollectionsProjection : IProjectionFor<GroupWithMultipleCollections>{ public void Define(IProjectionBuilderFor<GroupWithMultipleCollections> builder) => builder .From<GroupCreatedWithMultipleCollections>() .Children(m => m.Members, children => children .IdentifiedBy(m => m.UserId) .From<MemberAddedToGroup>(b => b .UsingKey(e => e.UserId))) .Children(m => m.Tasks, children => children .IdentifiedBy(m => m.TaskId) .From<TaskAssignedToGroup>(b => b .UsingKey(e => e.TaskId)));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class GroupCreatedWithMultipleCollections(val name: String)
@EventTypedata class MemberAddedToGroup(val userId: String, val role: String)
@EventTypedata class TaskAssignedToGroup(val taskId: String, val title: String)
data class GroupWithMultipleCollections( val name: String = "", val members: List<GroupMemberInMultipleCollections> = emptyList(), val tasks: List<GroupTaskInMultipleCollections> = emptyList())
data class GroupMemberInMultipleCollections( val userId: String = "", val role: String = "")
data class GroupTaskInMultipleCollections( val taskId: String = "", val title: String = "")
class GroupWithMultipleCollectionsProjection : IProjectionFor<GroupWithMultipleCollections> { override fun define(builder: IProjectionBuilderFor<GroupWithMultipleCollections>) { builder .from(GroupCreatedWithMultipleCollections::class) .children(GroupWithMultipleCollections::members, GroupMemberInMultipleCollections::class) { children -> children .identifiedBy("userId") .from(MemberAddedToGroup::class) { it.usingKey("userId") } } .children(GroupWithMultipleCollections::tasks, GroupTaskInMultipleCollections::class) { children -> children .identifiedBy("taskId") .from(TaskAssignedToGroup::class) { it.usingKey("taskId") } } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
import java.util.List;
@EventTyperecord GroupCreatedWithMultipleCollections(String name) {}
@EventTyperecord MemberAddedToGroup(String userId, String role) {}
@EventTyperecord TaskAssignedToGroup(String taskId, String title) {}
record GroupWithMultipleCollections( String name, List<GroupMemberInMultipleCollections> members, List<GroupTaskInMultipleCollections> tasks) {}
record GroupMemberInMultipleCollections(String userId, String role) {}
record GroupTaskInMultipleCollections(String taskId, String title) {}
class GroupWithMultipleCollectionsProjection implements IProjectionFor<GroupWithMultipleCollections> { @Override public void define(IProjectionBuilderFor<GroupWithMultipleCollections> builder) { builder .from(GroupCreatedWithMultipleCollections.class) .children("members", GroupMemberInMultipleCollections.class, children -> { children .identifiedBy("userId") .from(MemberAddedToGroup.class, fb -> { fb.usingKey("userId"); }); }) .children("tasks", GroupTaskInMultipleCollections.class, children -> { children .identifiedBy("taskId") .from(TaskAssignedToGroup.class, fb -> { fb.usingKey("taskId"); }); }); }}defmodule MyApp.Events.GroupCreatedWithMultipleCollections do use Chronicle.Events.EventType, id: "group-created-with-multiple-collections"
defstruct [:name]end
defmodule MyApp.Events.MemberAddedToGroup do use Chronicle.Events.EventType, id: "member-added-to-group"
defstruct [:user_id, :role]end
defmodule MyApp.Events.TaskAssignedToGroup do use Chronicle.Events.EventType, id: "task-assigned-to-group"
defstruct [:task_id, :title]end
defmodule MyApp.ReadModels.GroupMemberInMultipleCollections do defstruct user_id: nil, role: nilend
defmodule MyApp.ReadModels.GroupTaskInMultipleCollections do defstruct task_id: nil, title: nilend
defmodule MyApp.ReadModels.GroupWithMultipleCollections do use Chronicle.ReadModels.ReadModel, types: [ members: {:list, MyApp.ReadModels.GroupMemberInMultipleCollections}, tasks: {:list, MyApp.ReadModels.GroupTaskInMultipleCollections} ]
defstruct name: nil, members: [], tasks: []end
defmodule MyApp.Projections.GroupWithMultipleCollectionsProjection do use Chronicle.Projections.Projection, model: MyApp.ReadModels.GroupWithMultipleCollections
alias MyApp.Events.{GroupCreatedWithMultipleCollections, MemberAddedToGroup, TaskAssignedToGroup}
from GroupCreatedWithMultipleCollections
children :members, identified_by: :user_id do from MemberAddedToGroup, key: :user_id, set: [user_id: :user_id, role: :role] end
children :tasks, identified_by: :task_id do from TaskAssignedToGroup, key: :task_id, set: [task_id: :task_id, title: :title] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GroupCreatedWithMultipleCollections { @field(String) readonly name: string;
constructor(name: string) { this.name = name; }}
@eventType()class MemberAddedToGroup { @field(String) readonly userId: string; @field(String) readonly role: string;
constructor(userId: string, role: string) { this.userId = userId; this.role = role; }}
@eventType()class TaskAssignedToGroup { @field(String) readonly taskId: string; @field(String) readonly title: string;
constructor(taskId: string, title: string) { this.taskId = taskId; this.title = title; }}
class GroupMemberInMultipleCollections { userId = ''; role = '';}
class GroupTaskInMultipleCollections { taskId = ''; title = '';}
class GroupWithMultipleCollections { name = ''; members: GroupMemberInMultipleCollections[] = []; tasks: GroupTaskInMultipleCollections[] = [];}
@projection()class GroupWithMultipleCollectionsProjection implements IProjectionFor<GroupWithMultipleCollections> { define(builder: IProjectionBuilderFor<GroupWithMultipleCollections>): void { builder .from(GroupCreatedWithMultipleCollections) .children<GroupMemberInMultipleCollections>(m => m.members, children => children .identifiedBy(m => m.userId) .from(MemberAddedToGroup, b => b .usingKey(e => e.userId))) .children<GroupTaskInMultipleCollections>(m => m.tasks, children => children .identifiedBy(m => m.taskId) .from(TaskAssignedToGroup, b => b .usingKey(e => e.taskId))); }}If a child needs several values to identify it, continue with composite keys. For an object without a collection, use a nested projection.