Cratis Chronicle projections: use a constant key
A constant key in Cratis Chronicle directs events from different event sources into one read model instance. Use it when you need one order count or engagement total rather than a separate result for each source. Apply the same key to every event mapping that contributes to that result.
Defining a constant key
Section titled “Defining a constant key”Use UsingConstantKey(string value) on a From mapping to select a fixed read model key. The read model remains a normal record or class; you do not need a different model shape to share one instance across event sources.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecConstantKeyOrderPlaced(decimal Total);
public record DecConstantKeyGlobalCounter(int TotalOrders);
public class DecConstantKeyGlobalCounterProjection : IProjectionFor<DecConstantKeyGlobalCounter>{ public void Define(IProjectionBuilderFor<DecConstantKeyGlobalCounter> builder) => builder .From<DecConstantKeyOrderPlaced>(_ => _ .UsingConstantKey("global") .Count(m => m.TotalOrders));}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.DecConstantKeyOrderPlaced do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-order-placed"
defstruct [:total]end
defmodule MyApp.ReadModels.DecConstantKeyGlobalCounter do use Cratis.Chronicle.ReadModels.ReadModel
defstruct total_orders: 0end
defmodule MyApp.Projections.DecConstantKeyGlobalCounterProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecConstantKeyGlobalCounter
alias MyApp.Events.DecConstantKeyOrderPlaced
from DecConstantKeyOrderPlaced, key: "global", count: :total_ordersendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class DecConstantKeyOrderPlaced { @field(Number) readonly total: number;
constructor(total: number) { this.total = total; }}
class DecConstantKeyGlobalCounter { totalOrders = 0;}
@projection()class DecConstantKeyGlobalCounterProjection implements IProjectionFor<DecConstantKeyGlobalCounter> { define(builder: IProjectionBuilderFor<DecConstantKeyGlobalCounter>): void { builder .from(DecConstantKeyOrderPlaced, _ => _ .usingConstantKey('global') .count(m => m.totalOrders)); }}Every handled order-placement event updates the same counter with the key "global", regardless of its event source ID. A constant key changes where events are mapped; it does not subscribe the projection to additional event types or sequences.
Combining with functions
Section titled “Combining with functions”Use Count for the number of registrations and Increment/Decrement for a total that can rise and fall, such as active sessions. Each contributing mapping below uses the key "site" so the totals stay in one instance:
[EventType]public record DecConstantKeyUserRegistered(string Name);
[EventType]public record DecConstantKeyUserLoggedIn;
[EventType]public record DecConstantKeyUserLoggedOut;
public record DecConstantKeySiteStatistics( int TotalUsers, int ActiveSessions);
public class DecConstantKeySiteStatisticsProjection : IProjectionFor<DecConstantKeySiteStatistics>{ public void Define(IProjectionBuilderFor<DecConstantKeySiteStatistics> builder) => builder .From<DecConstantKeyUserRegistered>(_ => _ .UsingConstantKey("site") .Count(m => m.TotalUsers)) .From<DecConstantKeyUserLoggedIn>(_ => _ .UsingConstantKey("site") .Increment(m => m.ActiveSessions)) .From<DecConstantKeyUserLoggedOut>(_ => _ .UsingConstantKey("site") .Decrement(m => m.ActiveSessions));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class DecConstantKeyUserRegistered(val name: String)
@EventTypedata class DecConstantKeyUserLoggedIn(val placeholder: Boolean = true)
@EventTypedata class DecConstantKeyUserLoggedOut(val placeholder: Boolean = true)
data class DecConstantKeySiteStatistics( val totalUsers: Int = 0, val activeSessions: Int = 0)
class DecConstantKeySiteStatisticsProjection : IProjectionFor<DecConstantKeySiteStatistics> { override fun define(builder: IProjectionBuilderFor<DecConstantKeySiteStatistics>) { builder .from(DecConstantKeyUserRegistered::class) { it.usingConstantKey("site") it.count(DecConstantKeySiteStatistics::totalUsers) } .from(DecConstantKeyUserLoggedIn::class) { it.usingConstantKey("site") it.increment(DecConstantKeySiteStatistics::activeSessions) } .from(DecConstantKeyUserLoggedOut::class) { it.usingConstantKey("site") it.decrement(DecConstantKeySiteStatistics::activeSessions) } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
@EventTyperecord DecConstantKeyUserRegistered(String name) {}
@EventTyperecord DecConstantKeyUserLoggedIn() {}
@EventTyperecord DecConstantKeyUserLoggedOut() {}
class DecConstantKeySiteStatistics { public int totalUsers = 0; public int activeSessions = 0;}
class DecConstantKeySiteStatisticsProjection implements IProjectionFor<DecConstantKeySiteStatistics> { @Override public void define(IProjectionBuilderFor<DecConstantKeySiteStatistics> builder) { builder .from(DecConstantKeyUserRegistered.class, fb -> { fb.usingConstantKey("site"); fb.count("totalUsers"); }) .from(DecConstantKeyUserLoggedIn.class, fb -> { fb.usingConstantKey("site"); fb.increment("activeSessions"); }) .from(DecConstantKeyUserLoggedOut.class, fb -> { fb.usingConstantKey("site"); fb.decrement("activeSessions"); }); }}defmodule MyApp.Events.DecConstantKeyUserRegistered do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-user-registered"
defstruct [:name]end
defmodule MyApp.Events.DecConstantKeyUserLoggedIn do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-user-logged-in"
defstruct []end
defmodule MyApp.Events.DecConstantKeyUserLoggedOut do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-user-logged-out"
defstruct []end
defmodule MyApp.ReadModels.DecConstantKeySiteStatistics do use Cratis.Chronicle.ReadModels.ReadModel
defstruct total_users: 0, active_sessions: 0end
defmodule MyApp.Projections.DecConstantKeySiteStatisticsProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecConstantKeySiteStatistics
alias MyApp.Events.{DecConstantKeyUserRegistered, DecConstantKeyUserLoggedIn, DecConstantKeyUserLoggedOut}
from DecConstantKeyUserRegistered, key: "site", count: :total_users
from DecConstantKeyUserLoggedIn, key: "site", add: [active_sessions: 1]
from DecConstantKeyUserLoggedOut, key: "site", subtract: [active_sessions: 1]endimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@eventType()class DecConstantKeyUserLoggedIn {}
@eventType()class DecConstantKeyUserLoggedOut {}
class DecConstantKeySiteStatistics { activeSessions = 0;}
@projection()class DecConstantKeySiteStatisticsProjection implements IProjectionFor<DecConstantKeySiteStatistics> { define(builder: IProjectionBuilderFor<DecConstantKeySiteStatistics>): void { builder .from(DecConstantKeyUserLoggedIn, _ => _ .usingConstantKey('site') .increment(m => m.activeSessions)) .from(DecConstantKeyUserLoggedOut, _ => _ .usingConstantKey('site') .decrement(m => m.activeSessions)); }}Constant parent keys
Section titled “Constant parent keys”Use UsingConstantParentKey(string value) to send child events to one shared parent. The child still needs its own key so Chronicle can distinguish items within that parent’s collection:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecConstantKeyUserJoined(string UserId, string UserName);
public record DecConstantKeyTeamMember(string UserId, string Name);
public record DecConstantKeyTeam(IEnumerable<DecConstantKeyTeamMember> Members);
public class DecConstantKeyTeamActivityProjection : IProjectionFor<DecConstantKeyTeam>{ public void Define(IProjectionBuilderFor<DecConstantKeyTeam> builder) => builder .Children(m => m.Members, children => children .IdentifiedBy(e => e.UserId) .From<DecConstantKeyUserJoined>(_ => _ .UsingConstantParentKey("main-team") .Set(m => m.Name).To(e => e.UserName)));}Kotlin does not support this workflow yet.`IChildFromBuilderFor` only has `usingKey(String)` and `usingParentKey(String)` — there is no`usingConstantParentKey` for targeting the same parent instance from every child event.Java does not support this workflow yet.`IChildFromBuilderFor` only has `usingKey(String)` and `usingParentKey(String)` — there is no`usingConstantParentKey` for targeting the same parent instance from every child event.defmodule MyApp.Events.DecConstantKeyUserJoined do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-user-joined"
defstruct [:user_id, :user_name]end
defmodule MyApp.ReadModels.DecConstantKeyTeamMember do use Cratis.Chronicle.ReadModels.ReadModel
defstruct user_id: nil, name: nilend
defmodule MyApp.ReadModels.DecConstantKeyTeam do use Cratis.Chronicle.ReadModels.ReadModel, types: [members: {:list, MyApp.ReadModels.DecConstantKeyTeamMember}]
defstruct members: []end
defmodule MyApp.Projections.DecConstantKeyTeamActivityProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecConstantKeyTeam
children :members, identified_by: :user_id do from MyApp.Events.DecConstantKeyUserJoined, parent_key: "$value(main-team)", set: [user_id: :user_id, name: :user_name] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class DecConstantKeyUserJoined { @field(String) readonly userId: string; @field(String) readonly userName: string;
constructor(userId: string, userName: string) { this.userId = userId; this.userName = userName; }}
class DecConstantKeyTeamMember { userId = ''; name = '';}
class DecConstantKeyTeam { members: DecConstantKeyTeamMember[] = [];}
@projection()class DecConstantKeyTeamActivityProjection implements IProjectionFor<DecConstantKeyTeam> { define(builder: IProjectionBuilderFor<DecConstantKeyTeam>): void { builder .children<DecConstantKeyTeamMember>(m => m.members, children => children .identifiedBy(e => e.userId) .from(DecConstantKeyUserJoined, _ => _ .usingConstantParentKey('main-team') .set(m => m.name).to(e => e.userName))); }}Comparison to other key strategies
Section titled “Comparison to other key strategies”| Strategy | Method | When to use |
|---|---|---|
| Event source ID | (default) | Keep one instance per event source ID. |
| Event property | UsingKey(e => e.Property) |
Identify the instance from event content. |
| Event context | UsingKeyFromContext(c => c.Property) |
Identify the instance from event metadata. |
| Composite | UsingCompositeKey<T>(...) |
Use several values together as the identity. |
| Constant | UsingConstantKey("value") |
Direct the configured events to one shared instance. |
Full example
Section titled “Full example”Use the same key across several event types to collect their metrics in one document:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecConstantKeyPageViewed(string PageUrl);
[EventType]public record DecConstantKeyButtonClicked(string ButtonId);
[EventType]public record DecConstantKeyFormSubmitted(string FormId);
public record DecConstantKeyEngagementMetrics( int PageViews, int ButtonClicks, int FormSubmissions);
public class DecConstantKeyEngagementMetricsProjection : IProjectionFor<DecConstantKeyEngagementMetrics>{ public void Define(IProjectionBuilderFor<DecConstantKeyEngagementMetrics> builder) => builder .From<DecConstantKeyPageViewed>(_ => _ .UsingConstantKey("metrics") .Count(m => m.PageViews)) .From<DecConstantKeyButtonClicked>(_ => _ .UsingConstantKey("metrics") .Count(m => m.ButtonClicks)) .From<DecConstantKeyFormSubmitted>(_ => _ .UsingConstantKey("metrics") .Count(m => m.FormSubmissions));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class DecConstantKeyPageViewed(val pageUrl: String)
@EventTypedata class DecConstantKeyButtonClicked(val buttonId: String)
@EventTypedata class DecConstantKeyFormSubmitted(val formId: String)
data class DecConstantKeyEngagementMetrics( val pageViews: Int = 0, val buttonClicks: Int = 0, val formSubmissions: Int = 0)
class DecConstantKeyEngagementMetricsProjection : IProjectionFor<DecConstantKeyEngagementMetrics> { override fun define(builder: IProjectionBuilderFor<DecConstantKeyEngagementMetrics>) { builder .from(DecConstantKeyPageViewed::class) { it.usingConstantKey("metrics") it.count(DecConstantKeyEngagementMetrics::pageViews) } .from(DecConstantKeyButtonClicked::class) { it.usingConstantKey("metrics") it.count(DecConstantKeyEngagementMetrics::buttonClicks) } .from(DecConstantKeyFormSubmitted::class) { it.usingConstantKey("metrics") it.count(DecConstantKeyEngagementMetrics::formSubmissions) } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
@EventTyperecord DecConstantKeyPageViewed(String pageUrl) {}
@EventTyperecord DecConstantKeyButtonClicked(String buttonId) {}
@EventTyperecord DecConstantKeyFormSubmitted(String formId) {}
class DecConstantKeyEngagementMetrics { public int pageViews = 0; public int buttonClicks = 0; public int formSubmissions = 0;}
class DecConstantKeyEngagementMetricsProjection implements IProjectionFor<DecConstantKeyEngagementMetrics> { @Override public void define(IProjectionBuilderFor<DecConstantKeyEngagementMetrics> builder) { builder .from(DecConstantKeyPageViewed.class, fb -> { fb.usingConstantKey("metrics"); fb.count("pageViews"); }) .from(DecConstantKeyButtonClicked.class, fb -> { fb.usingConstantKey("metrics"); fb.count("buttonClicks"); }) .from(DecConstantKeyFormSubmitted.class, fb -> { fb.usingConstantKey("metrics"); fb.count("formSubmissions"); }); }}defmodule MyApp.Events.DecConstantKeyPageViewed do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-page-viewed"
defstruct [:page_url]end
defmodule MyApp.Events.DecConstantKeyButtonClicked do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-button-clicked"
defstruct [:button_id]end
defmodule MyApp.Events.DecConstantKeyFormSubmitted do use Cratis.Chronicle.Events.EventType, id: "dec-constant-key-form-submitted"
defstruct [:form_id]end
defmodule MyApp.ReadModels.DecConstantKeyEngagementMetrics do use Cratis.Chronicle.ReadModels.ReadModel
defstruct page_views: 0, button_clicks: 0, form_submissions: 0end
defmodule MyApp.Projections.DecConstantKeyEngagementMetricsProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecConstantKeyEngagementMetrics
alias MyApp.Events.{DecConstantKeyPageViewed, DecConstantKeyButtonClicked, DecConstantKeyFormSubmitted}
from DecConstantKeyPageViewed, key: "metrics", count: :page_views
from DecConstantKeyButtonClicked, key: "metrics", count: :button_clicks
from DecConstantKeyFormSubmitted, key: "metrics", count: :form_submissionsendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class DecConstantKeyPageViewed { @field(String) readonly pageUrl: string;
constructor(pageUrl: string) { this.pageUrl = pageUrl; }}
@eventType()class DecConstantKeyButtonClicked { @field(String) readonly buttonId: string;
constructor(buttonId: string) { this.buttonId = buttonId; }}
@eventType()class DecConstantKeyFormSubmitted { @field(String) readonly formId: string;
constructor(formId: string) { this.formId = formId; }}
class DecConstantKeyEngagementMetrics { pageViews = 0; buttonClicks = 0; formSubmissions = 0;}
@projection()class DecConstantKeyEngagementMetricsProjection implements IProjectionFor<DecConstantKeyEngagementMetrics> { define(builder: IProjectionBuilderFor<DecConstantKeyEngagementMetrics>): void { builder .from(DecConstantKeyPageViewed, _ => _ .usingConstantKey('metrics') .count(m => m.pageViews)) .from(DecConstantKeyButtonClicked, _ => _ .usingConstantKey('metrics') .count(m => m.buttonClicks)) .from(DecConstantKeyFormSubmitted, _ => _ .usingConstantKey('metrics') .count(m => m.formSubmissions)); }}The configured engagement events contribute to a single metrics document with the key "metrics". To keep separate totals for combinations such as customer and reporting period, use composite keys. For the operations available on each total, see projection functions.