Cratis Chronicle projections: map properties with Set
Use Set() in a Cratis Chronicle projection when a read-model property needs a different source than its matching event property. You can select an event property, a constant, or event metadata while leaving automatic mapping enabled for the rest.
Explicit property mapping
Section titled “Explicit property mapping”Choose the read-model property with Set(), then its source with To(). In this account example, AccountNumber comes from Number, and CustomerName comes from the nested event property Owner.Name:
using Cratis.Chronicle.Projections;
public class DecSetPropsAccountProjection : IProjectionFor<DecSetPropsAccount>{ public void Define(IProjectionBuilderFor<DecSetPropsAccount> builder) => builder .From<DecSetPropsAccountOpened>(_ => _ .Set(m => m.AccountNumber).To(e => e.Number) .Set(m => m.CustomerName).To(e => e.Owner.Name) .Set(m => m.Balance).ToValue(42.0m) .Set(m => m.IsActive).ToValue(true) .Set(m => m.OpenedAt).To(e => e.Timestamp)) .From<DecSetPropsMoneyDeposited>(_ => _ .Set(m => m.Balance).To(e => e.Amount) .Set(m => m.LastTransaction).To(e => e.Timestamp));}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
class DecSetPropsAccountProjection : IProjectionFor<DecSetPropsAccount> { override fun define(builder: IProjectionBuilderFor<DecSetPropsAccount>) { builder .from(DecSetPropsAccountOpened::class) { it.set(DecSetPropsAccount::accountNumber).toProperty("number") it.set(DecSetPropsAccount::customerName).toProperty("owner.name") it.set(DecSetPropsAccount::isActive).toValue(true) it.set(DecSetPropsAccount::openedAt).toProperty("timestamp") } .from(DecSetPropsMoneyDeposited::class) { it.set(DecSetPropsAccount::balance).toProperty("amount") it.set(DecSetPropsAccount::lastTransaction).toProperty("timestamp") } }}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
class DecSetPropsAccountProjection implements IProjectionFor<DecSetPropsAccount> { @Override public void define(IProjectionBuilderFor<DecSetPropsAccount> builder) { builder .from(DecSetPropsAccountOpened.class, fb -> { fb.<String>set("accountNumber").toProperty("number"); fb.<String>set("customerName").toProperty("owner.name"); fb.<Boolean>set("isActive").toValue(true); fb.<String>set("openedAt").toProperty("timestamp"); }) .from(DecSetPropsMoneyDeposited.class, fb -> { fb.<Double>set("balance").toProperty("amount"); fb.<String>set("lastTransaction").toProperty("timestamp"); }); }}defmodule MyApp.Projections.DecSetPropsAccountProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecSetPropsAccount
alias MyApp.Events.{DecSetPropsAccountOpened, DecSetPropsMoneyDeposited}
from DecSetPropsAccountOpened, set: [ account_number: :number, # `owner` is a nested object on the event — the dot-path expression # reaches into it the same way Chronicle's kernel resolves any other # nested event property. customer_name: "owner.name", balance: "$value(42.0)", is_active: "$value(true)", opened_at: :timestamp ]
from DecSetPropsMoneyDeposited, set: [ balance: :amount, last_transaction: :timestamp ]endimport { IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@projection()class DecSetPropsAccountProjection implements IProjectionFor<DecSetPropsAccount> { define(builder: IProjectionBuilderFor<DecSetPropsAccount>): void { builder .from(DecSetPropsAccountOpened, _ => _ .set(m => m.accountNumber).to(e => e.number) .set(m => m.customerName).to(e => e.owner.name) .set(m => m.balance).toValue(42.0) .set(m => m.isActive).toValue(true) .set(m => m.openedAt).to(e => e.timestamp)) .from(DecSetPropsMoneyDeposited, _ => _ .set(m => m.balance).to(e => e.amount) .set(m => m.lastTransaction).to(e => e.timestamp)); }}Combining AutoMap with explicit mapping
Section titled “Combining AutoMap with explicit mapping”AutoMap, Chronicle’s automatic property mapping, is enabled by default at the projection root. You do not need to call .AutoMap() there. Add explicit mappings for exceptions; they take precedence over automatic mappings for the same target property:
public class DecSetPropsCombinedAccountProjection : IProjectionFor<DecSetPropsAccount>{ public void Define(IProjectionBuilderFor<DecSetPropsAccount> builder) => builder .From<DecSetPropsAccountOpened>(_ => _ .Set(m => m.CustomerName).To(e => e.Owner.Name) // Custom mapping for nested property .Set(m => m.IsActive).ToValue(true)) // Custom mapping for constant .From<DecSetPropsMoneyDeposited>(); // Uses AutoMap for all properties}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
class DecSetPropsCombinedAccountProjection : IProjectionFor<DecSetPropsAccount> { override fun define(builder: IProjectionBuilderFor<DecSetPropsAccount>) { builder // AutoMap is on by default for matching event properties. .from(DecSetPropsAccountOpened::class) { // Map the property AutoMap cannot find: it is nested on the event. it.set(DecSetPropsAccount::customerName).toProperty("owner.name") it.set(DecSetPropsAccount::isActive).toValue(true) } .from(DecSetPropsMoneyDeposited::class) // Uses AutoMap for all properties }}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
class DecSetPropsCombinedAccountProjection implements IProjectionFor<DecSetPropsAccount> { @Override public void define(IProjectionBuilderFor<DecSetPropsAccount> builder) { builder // AutoMap is on by default for matching event properties. .from(DecSetPropsAccountOpened.class, fb -> { // Map the property AutoMap cannot find: it is nested on the event. fb.<String>set("customerName").toProperty("owner.name"); fb.<Boolean>set("isActive").toValue(true); }) .from(DecSetPropsMoneyDeposited.class); // Uses AutoMap for all properties }}defmodule MyApp.Projections.DecSetPropsCombinedAccountProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecSetPropsAccount
alias MyApp.Events.{DecSetPropsAccountOpened, DecSetPropsMoneyDeposited}
# AutoMap fills every property whose name matches the event automatically; # only the two exceptions below need an explicit set:. from DecSetPropsAccountOpened, set: [ customer_name: "owner.name", is_active: "$value(true)" ]
# Uses AutoMap for every property. from DecSetPropsMoneyDepositedendimport { IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@projection()class DecSetPropsCombinedAccountProjection implements IProjectionFor<DecSetPropsAccount> { define(builder: IProjectionBuilderFor<DecSetPropsAccount>): void { builder .autoMap() // Automatically maps matching properties .from(DecSetPropsAccountOpened, _ => _ .set(m => m.customerName).to(e => e.owner.name) // Custom mapping for nested property .set(m => m.isActive).toValue(true)) // Custom mapping for constant .from(DecSetPropsMoneyDeposited); // Uses AutoMap for all properties }}AutoMap copies matching properties with compatible types, including nested structures and collections. It does not infer that Amount means Balance or that Timestamp means LastTransaction, so the parameterless deposit subscription above does not map those values to those targets. Use the explicit mappings from the first example for that behavior.
NoAutoMap() disables automatic mapping at the scope where it is called. Child scopes inherit the parent’s setting unless they override it with .AutoMap() or NoAutoMap(). There is no per-event-type toggle; put event-specific .Set() calls inside that event’s .From<TEvent>() block. See auto mapping for the matching rules.
Read model definition
Section titled “Read model definition”The read model uses names suited to the query rather than copying the event’s structure. Each selected value must still be compatible with its target property:
public record DecSetPropsAccount( string AccountNumber, string CustomerName, decimal Balance, bool IsActive, DateTimeOffset OpenedAt, DateTimeOffset? LastTransaction);import java.math.BigDecimalimport java.time.OffsetDateTime
data class DecSetPropsAccount( val accountNumber: String = "", val customerName: String = "", val balance: BigDecimal = BigDecimal.ZERO, val isActive: Boolean = false, val openedAt: OffsetDateTime? = null, val lastTransaction: OffsetDateTime? = null)class DecSetPropsAccount { public String accountNumber = ""; public String customerName = ""; public double balance = 0.0; public boolean isActive = false; public String openedAt = null; public String lastTransaction = null;}defmodule MyApp.ReadModels.DecSetPropsAccount do use Cratis.Chronicle.ReadModels.ReadModel
defstruct [ :account_number, :customer_name, :balance, :is_active, :opened_at, :last_transaction ]endclass DecSetPropsAccount { accountNumber = ''; customerName = ''; balance = 0; isActive = false; openedAt = new Date(); lastTransaction: Date | null = null;}Event definitions
Section titled “Event definitions”The account-opened event nests customer details under Owner, while the deposit event supplies an amount and timestamp:
using Cratis.Chronicle.Events;
[EventType]public record DecSetPropsAccountOpened( string Number, DecSetPropsCustomer Owner, DateTimeOffset Timestamp);
[EventType]public record DecSetPropsMoneyDeposited( decimal Amount, DateTimeOffset Timestamp);
public record DecSetPropsCustomer(string Name, string Email);import io.cratis.chronicle.events.EventTypeimport java.math.BigDecimalimport java.time.OffsetDateTime
data class DecSetPropsCustomer(val name: String, val email: String)
@EventTypedata class DecSetPropsAccountOpened( val number: String, val owner: DecSetPropsCustomer, val timestamp: OffsetDateTime)
@EventTypedata class DecSetPropsMoneyDeposited( val amount: BigDecimal, val timestamp: OffsetDateTime)import io.cratis.chronicle.events.EventType;
record DecSetPropsCustomer(String name, String email) {}
@EventTyperecord DecSetPropsAccountOpened( String number, DecSetPropsCustomer owner, String timestamp) {}
@EventTyperecord DecSetPropsMoneyDeposited( double amount, String timestamp) {}defmodule MyApp.Events.DecSetPropsCustomer do defstruct [:name, :email]end
defmodule MyApp.Events.DecSetPropsAccountOpened do use Cratis.Chronicle.Events.EventType, id: "dec-set-props-account-opened"
defstruct [:number, :owner, :timestamp]end
defmodule MyApp.Events.DecSetPropsMoneyDeposited do use Cratis.Chronicle.Events.EventType, id: "dec-set-props-money-deposited"
defstruct [:amount, :timestamp]endimport { eventType } from '@cratis/chronicle';
class DecSetPropsCustomer { name = ''; email = '';}
@eventType()class DecSetPropsAccountOpened { number = ''; owner = new DecSetPropsCustomer(); timestamp = new Date();}
@eventType()class DecSetPropsMoneyDeposited { amount = 0; timestamp = new Date();}Property mapping options
Section titled “Property mapping options”Choose the source that represents the fact you want to store. Event context is the metadata accompanying an event, such as its occurrence time.
| Source | Mapping |
|---|---|
| Event property | .Set(m => m.CustomerName).To(e => e.Owner.Name) |
| Constant value | .Set(m => m.IsActive).ToValue(true) |
| Event context | .Set(m => m.OpenedAt).ToEventContextProperty(c => c.Occurred) |
| Event source ID | .Set(m => m.Id).ToEventSourceId() |
Setting a value only once
Section titled “Setting a value only once”A set-once mapping assigns its value only while the target property has no value - it is missing or null. Once the property holds a value, later events leave it unchanged and produce no change for the read model. Use it for facts that belong to the first event that supplies them, such as who created something or when it was first seen.
In the next example every revision updates Title and LastRevised, while OriginalTitle, CreatedBy and Created keep what the first revision supplied:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecSetOnceDocumentRevised(string Title);
public record DecSetOnceDocument(string OriginalTitle, string Title, string CreatedBy, DateTimeOffset Created, DateTimeOffset LastRevised);
public class DecSetOnceDocumentProjection : IProjectionFor<DecSetOnceDocument>{ public void Define(IProjectionBuilderFor<DecSetOnceDocument> builder) => builder .From<DecSetOnceDocumentRevised>(_ => _ .SetOnce(m => m.OriginalTitle).To(e => e.Title) .Set(m => m.Title).To(e => e.Title) .SetOnce(m => m.CreatedBy).ToEventContextProperty(c => c.CausedBy.Subject) .SetOnce(m => m.Created).ToEventContextProperty(c => c.Occurred) .Set(m => m.LastRevised).ToEventContextProperty(c => c.Occurred));}defmodule MyApp.Events.DecSetOnceDocumentRevised do use Cratis.Chronicle.Events.EventType, id: "dec-set-once-document-revised"
defstruct title: ""end
defmodule MyApp.ReadModels.DecSetOnceDocument do use Cratis.Chronicle.ReadModels.ReadModel, types: [created: :datetime, last_revised: :datetime]
defstruct original_title: nil, title: "", created_by: nil, created: nil, last_revised: nilend
defmodule MyApp.Projections.DecSetOnceDocumentProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecSetOnceDocument
from MyApp.Events.DecSetOnceDocumentRevised, set_once: [ original_title: :title, created_by: {:caused_by, :subject}, created: :occurred ], set: [title: :title, last_revised: :occurred]endimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@eventType()class DecSetOnceDocumentRevised { title = '';}
class DecSetOnceDocument { originalTitle = ''; title = ''; createdBy = ''; created = new Date(0); lastRevised = new Date(0);}
@projection()class DecSetOnceDocumentProjection implements IProjectionFor<DecSetOnceDocument> { define(builder: IProjectionBuilderFor<DecSetOnceDocument>): void { builder .from(DecSetOnceDocumentRevised, _ => _ .setOnce(m => m.originalTitle).to(e => e.title) .set(m => m.title).to(e => e.title) .setOnce(m => m.createdBy).toCausedBy('subject') .setOnce(m => m.created).toEventContextProperty('occurred') .set(m => m.lastRevised).toEventContextProperty('occurred')); }}The source can be anything a normal mapping can read: an event property, a constant, the event source ID, event context such as Occurred, or the identity that caused the event. Set once works on root properties, children, nested objects and dictionary entries, including dictionaries keyed by event content.
The decision depends only on the read model state built from earlier events, so a replay assigns the same value. A property that is cleared back to null can be set once more by a later event.
Multiple events
Section titled “Multiple events”Each From<TEvent>() block defines the changes for that event type. In the first example, opening the account sets its number, customer name, balance, active flag, and opening time. A deposit replaces Balance with the event’s Amount and updates LastTransaction; properties not mapped by that event retain their previous values.
Set() assigns a value; it does not add a deposit to the existing balance. For accumulation, use the operations described in projection functions.