Reputation: 1255
Say I am storing cars via event sourcing. I have a CarAggregate, which can save/load events correctly using a car repo:
CarAggregateRepository
{
CarAggregate GetById(Guid id)
{
var events = EventStore.LoadEventsById(id);
var carAggregate = new CarAggregate(id);
carAggregate.ApplyEvents(events);
return carAggregate;
}
void Save(CarAggregate car)
{
EventStore.StoreEvents(car.Id, car.UncommittedEvents);
}
}
I now want a method to find cars that match a specific query, for example, all cars made by Mercedes:
List<CarAggregate> Find(string manufacturer)
{
// What goes here?
}
The only way I can think of doing this is:
Surely this is incredibly inefficient, as I could end up loading hundreds of thousands of individual events from the event store? That's a lot of data transmission. Also many of these aggregates loaded could be for things that aren't even CarAggregates. Maybe they're UserAggregates whose events are also stored in the same event store?
I must be missing something. How can I list all CarAggregates matching my query?
Upvotes: 0
Views: 893
Reputation: 57214
// What goes here?
The usual answer is that an interface to a read model goes there.
Which is to say, you will have some logic that takes events from your event store and from them creates/updates a report with the information you need in some shape/data structure/persistence store that makes queries easier (hence: CQRS).
One common answer is to have a process that subscribes to the event store, which is to say that it listens for changes, queries the store to get copies of new events, and then updates rows in some RDBMS that you can use to generate your reports.
You can think of the reports as a cached copy of the information in the event store. The information will be just a little bit stale (where this will depend in part on how much you are willing to spend to reduce the latency).
You could take a checkpoint of your event store, and then walk through all of the events up to that checkpoint figuring out which Cars match your query, but the latency of that sucks, and it requires a lot of repetitive work. So instead we do that work in the background, and you run your queries not against what the event store looks like "now", but instead against what the event store looked like as of the most recently reported checkpoint.
Upvotes: 2