Cratis Chronicle ad-hoc projection queries
Use IProjections.Query() in the Cratis Chronicle .NET client to inspect projected state without registering a permanent projection. Send a Projection Declaration Language (PDL) declaration and receive read model entries as JSON strings. You can omit the read model type when exploring a small set of events.
Basic Usage
Section titled “Basic Usage”Start with a connected .NET client and registered event types for the events named in your declaration. Inject IProjections into your service, then call Query() with the PDL string:
using Cratis.Chronicle.Projections;using System.Text.Json;
public class PdlOrderQueryService(IProjections projections){ public async Task<IEnumerable<PdlOrderSummary>> GetOrderSummaries() { var result = await projections.Query(""" projection OrderSummary from OrderPlaced """);
return result.ReadModelEntries .Select(json => JsonSerializer.Deserialize<PdlOrderSummary>(json)!); }}
public record PdlOrderSummary(string OrderId);import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.projections.ProjectionQueryResult
data class PdlOrderSummary(val orderId: String = "")
class PdlOrderQueryService(private val store: IEventStore) { suspend fun getOrderSummaries(): List<PdlOrderSummary> { val result = store.projections.query( """ projection OrderSummary from OrderPlaced """ )
return when (result) { is ProjectionQueryResult.Projected -> result.instancesOf(PdlOrderSummary::class) is ProjectionQueryResult.Invalid -> throw IllegalArgumentException("Invalid projection query: $result") } }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.java.ProjectionsServiceJavaBridge;import io.cratis.chronicle.projections.ProjectionQueryResult;
import java.util.List;
record PdlOrderSummary(String orderId) {}
class PdlOrderQueryService { private final EventStore store;
PdlOrderQueryService(EventStore store) { this.store = store; }
List<String> getOrderSummaries() { ProjectionQueryResult result = ProjectionsServiceJavaBridge.query( store.getProjections(), "projection OrderSummary\n from OrderPlaced" );
if (result instanceof ProjectionQueryResult.Projected projected) { // Raw JSON documents — instancesOf() takes a Kotlin KClass and has no Java-callable overload. return projected.getEntries(); } throw new IllegalArgumentException("Invalid projection query: " + result); }}{:ok, result} = Cratis.Chronicle.Projections.query(""" projection OrderSummary from OrderPlaced """)
Enum.each(result.instances, &IO.inspect/1)interface PdlOrderSummary { orderId: string;}
const result = await store.projections.query(` projection OrderSummary from OrderPlaced`);
const summaries = result.readModelEntries.map(json => JSON.parse(json) as PdlOrderSummary);ReadModelEntries is an IReadOnlyList<string>. Each string represents one projected read model instance. The example deserializes those strings into PdlOrderSummary records for the caller; that local result type does not need to be registered as a read model.
Explicit vs. Inferred Read Model
Section titled “Explicit vs. Inferred Read Model”Include => ReadModelType when you want to use an existing registered read model schema. The target must be its registered identifier, such as MyApp.ReadModels.PdlOrderReadModel, rather than a display name. Omit the target to let the server infer a schema from the event properties.
// Inferred — schema derived from OrderPlaced and OrderShipped event propertiesvar inferred = await projections.Query(""" projection Orders from OrderPlaced from OrderShipped """);
// Explicit — assuming PdlOrderReadModel is registered in the MyApp.ReadModels namespacevar explicitResult = await projections.Query(""" projection Orders => MyApp.ReadModels.PdlOrderReadModel from OrderPlaced from OrderShipped """);import io.cratis.chronicle.IEventStore
suspend fun compareInferredAndExplicit(store: IEventStore) { // Inferred — schema derived from OrderPlaced and OrderShipped event properties val inferred = store.projections.query( """ projection Orders from OrderPlaced from OrderShipped """ )
// Explicit — schema comes from the registered 'PdlOrderReadModel' type val explicitResult = store.projections.query( """ projection Orders => PdlOrderReadModel from OrderPlaced from OrderShipped """ )}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.java.ProjectionsServiceJavaBridge;import io.cratis.chronicle.projections.ProjectionQueryResult;
class InferredVsExplicitOrdersQuery { void compareInferredAndExplicit(EventStore store) { // Inferred — schema derived from OrderPlaced and OrderShipped event properties ProjectionQueryResult inferred = ProjectionsServiceJavaBridge.query( store.getProjections(), "projection Orders\n from OrderPlaced\n from OrderShipped" );
// Explicit — schema comes from the registered 'PdlOrderReadModel' type ProjectionQueryResult explicitResult = ProjectionsServiceJavaBridge.query( store.getProjections(), "projection Orders => PdlOrderReadModel\n from OrderPlaced\n from OrderShipped" ); }}# Inferred — schema derived from OrderPlaced and OrderShipped event properties, entries decode# as plain maps.{:ok, inferred} = Cratis.Chronicle.Projections.query(""" projection Orders from OrderPlaced from OrderShipped """)
# Explicit — assuming an Order read model is registered under the id "Order"; entries decode# as %MyApp.ReadModels.Order{} structs.{:ok, explicit} = Cratis.Chronicle.Projections.query( """ projection Orders => Order from OrderPlaced from OrderShipped """, read_model: MyApp.ReadModels.Order )
IO.inspect(inferred.instances)IO.inspect(explicit.instances)// Inferred - schema derived from OrderPlaced and OrderShipped event propertiesconst inferred = await store.projections.query(` projection Orders from OrderPlaced from OrderShipped`);
// Explicit - schema comes from the registered 'PdlOrderReadModel' typeconst explicitResult = await store.projections.query(` projection Orders => PdlOrderReadModel from OrderPlaced from OrderShipped`);In the inferred declaration, both from blocks contribute properties to the same schema. If those events share a property name, its types must be compatible. A string in one event and an integer in another produces a compiler error at query time:
// This declaration will throw UnableToQueryProjection:// OrderPlaced.value is string, but OrderShipped.value is intvar result = await projections.Query(""" projection Bad from OrderPlaced // value: string from OrderShipped // value: int → incompatible types """);import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.projections.ProjectionQueryResult
suspend fun queryBad(store: IEventStore) { // This declaration comes back as ProjectionQueryResult.Invalid: // OrderPlaced.value is a string, but OrderShipped.value is an int val result = store.projections.query( """ projection Bad from OrderPlaced // value: string from OrderShipped // value: int -> incompatible types """ )
if (result is ProjectionQueryResult.Invalid) { result.errors.forEach { println(it) } }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.java.ProjectionsServiceJavaBridge;import io.cratis.chronicle.projections.ProjectionDeclarationError;import io.cratis.chronicle.projections.ProjectionQueryResult;
class BadQuery { // This declaration comes back as ProjectionQueryResult.Invalid: // OrderPlaced.value is a string, but OrderShipped.value is an int void queryBad(EventStore store) { ProjectionQueryResult result = ProjectionsServiceJavaBridge.query( store.getProjections(), "projection Bad\n" + " from OrderPlaced // value: string\n" + " from OrderShipped // value: int -> incompatible types" );
if (result instanceof ProjectionQueryResult.Invalid invalid) { for (ProjectionDeclarationError error : invalid.getErrors()) { System.out.println(error); } } }}# This declaration returns {:error, {:invalid_declaration, _}}:# OrderPlaced.value is a string, but OrderShipped.value is an integer{:error, {:invalid_declaration, _errors}} = Cratis.Chronicle.Projections.query(""" projection Bad from OrderPlaced from OrderShipped """)// This declaration will throw UnableToQueryProjection:// OrderPlaced.value is a string, but OrderShipped.value is a numberconst result = await store.projections.query(` projection Bad from OrderPlaced // value: string from OrderShipped // value: number -> incompatible types`);Error Handling
Section titled “Error Handling”Query() throws UnableToQueryProjection when the declaration contains syntax or type errors. Read the exception message, correct the declaration or conflicting event property types, and submit the query again:
try{ var result = await projections.Query(""" projection Orders from OrderPlaced """);}catch (UnableToQueryProjection ex){ Console.WriteLine(ex.Message);}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.projections.ProjectionQueryResult
suspend fun queryOrders(store: IEventStore) { // A declaration that fails to parse is not an exception — it comes back as a result you branch on. when (val result = store.projections.query( """ projection Orders from OrderPlaced """ )) { is ProjectionQueryResult.Projected -> result.entries.forEach(::println) is ProjectionQueryResult.Invalid -> result.errors.forEach { println(it) } }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.java.ProjectionsServiceJavaBridge;import io.cratis.chronicle.projections.ProjectionDeclarationError;import io.cratis.chronicle.projections.ProjectionQueryResult;
class ErrorHandlingOrdersQuery { // A declaration that fails to parse is not an exception — it comes back as a result you branch on. void queryOrders(EventStore store) { ProjectionQueryResult result = ProjectionsServiceJavaBridge.query( store.getProjections(), "projection Orders\n from OrderPlaced" );
if (result instanceof ProjectionQueryResult.Projected projected) { for (String entry : projected.getEntries()) { System.out.println(entry); } } else if (result instanceof ProjectionQueryResult.Invalid invalid) { for (ProjectionDeclarationError error : invalid.getErrors()) { System.out.println(error); } } }}case Cratis.Chronicle.Projections.query(""" projection Orders from OrderPlaced """) do {:ok, _result} -> :ok {:error, {:invalid_declaration, errors}} -> Enum.each(errors, &IO.inspect/1)endimport { UnableToQueryProjection } from '@cratis/chronicle';
try { const result = await store.projections.query(` projection Orders from OrderPlaced `);} catch (error) { if (error instanceof UnableToQueryProjection) { console.log(error.message); }}Targeting a Different Event Sequence
Section titled “Targeting a Different Event Sequence”By default, Query() reads from the event-log sequence in the client’s event store and namespace. Pass a different sequence identifier as the second argument to inspect another sequence:
var result = await projections.Query( """ projection InboxMessages from MessageReceived """, eventSequenceId: "inbox");import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.eventSequences.EventSequenceId
suspend fun getInboxMessages(store: IEventStore) = store.projections.query( """ projection InboxMessages from MessageReceived """, EventSequenceId("inbox") )import io.cratis.chronicle.EventStore;import io.cratis.chronicle.java.ProjectionsServiceJavaBridge;import io.cratis.chronicle.projections.ProjectionQueryResult;
class InboxMessagesQuery { ProjectionQueryResult getInboxMessages(EventStore store) { return ProjectionsServiceJavaBridge.query( store.getProjections(), "projection InboxMessages\n from MessageReceived", "inbox" ); }}{:ok, result} = Cratis.Chronicle.Projections.query( """ projection InboxMessages from MessageReceived """, event_sequence_id: "inbox" )
Enum.each(result.instances, &IO.inspect/1)const result = await store.projections.query( ` projection InboxMessages from MessageReceived `, 'inbox');Practical Use Cases
Section titled “Practical Use Cases”Use an ad-hoc query when you need a one-off view of a known, small event set: inspecting an order during diagnosis, exploring event data while developing a feature, or asserting projected state in a test. Check the number of matching events before relying on the result. A successful call does not establish that the query processed the full history.
Limitations
Section titled “Limitations”| Concern | Detail |
|---|---|
| Event volume | The server reads at most 1,000 matching events. More matching events mean incomplete results. |
| No persistence | Results are not stored. Every call processes events again from the beginning of the selected sequence. |
| No registration | Query() does not register a projection, with or without an explicit => ReadModelType target. |
| No change notifications | Results are a point-in-time snapshot; this API has no observable or reactive variant. |
For a view that stays up to date as events arrive, define a registered projection. For declaration syntax and Chronicle’s naming rules, return to Projection Declaration Language.