Documentation
Welcome to docs|Projections|Using aggregated projections

Using aggregated projections

This page describes how to use aggregated projections in Serialized.

Aggregated projections are projections that are built from multiple aggregates to produce a single projection result. Aggregate projections does not have a projection ID and their result is always stored on the projection name. You can see the projection name as the query key for an aggregated projection.

The processing of aggregated projections work exactly the same as for single projections. The only difference is that the output result is stored on the projection name instead of the projection ID.

Creating an aggregated projection

To create an aggregated projection you need to specify that the projection is aggregated. Using our SDKs there are explicit methods/arguments for creating aggregated projections, and if you use the API directly you need to set the aggregated property to true in the projection definition.

The following example shows how to create an aggregated projection called total-orders-paid that counts the total amount of paid orders and their total amount. The predefined arithmetic functions add and inc is used to calculate the totals.

var incCountOnOrderPaid = newHandler("OrderPaid")    .addFunction(Functions.inc().with(targetSelector("count")).build())    .build();var addAmountOnOrderPaid = newHandler("OrderPaid")    .addFunction(Functions.inc().with(targetSelector("totalAmount")).build())    .build();projectionClient.createDefinition(aggregatedProjection("total-orders-paid")    .feed("order")    .addHandler(incCountOnOrderPaid)    .addHandler(addAmountOnOrderPaid)    .build());
const incCountOnOrderPaid = {  eventType: 'OrderPaid',  functions: [{function: 'inc', targetSelector: '$.projection.count'}]}const addAmountOnOrderPaid = {  eventType: 'OrderPaid',  functions: [{function: 'add', targetSelector: '$.projection.totalAmount'}]}const request = {  projectionName: 'total-orders-paid',  aggregated: true,  feedName: 'order',  handlers: [incCountOnOrderPaid, addAmountOnOrderPaid]}await projectionsClient.createOrUpdateDefinition(request)

Query an aggregated projection

Aggregated projections are queried by their projection name.

The following example describes how to query the total-orders-paid projection to get the total count of paid orders and their total amount in a single response:

var request = ProjectionQueries.aggregated("total-orders-paid").build(OrderTotalsProjection.class);OrderTotalsProjection totals = projectionClient.<OrderTotalsProjection>query(request).data();
const request = {  projectionName: 'total-orders-paid'}const totals = (await projectionsClient.getAggregatedProjection(request)).data