/
Materialized View Pattern

Materialized View Pattern

Problem

  • Query only needs a subset of the data from some entities, such as a summary of orders for several customers without all of the order details. How to extract data from relevant entities.

 

Solution

  • Typical uses of the events published by the event store are to maintain materialized views of entities as actions in the application change them, and for integration with external systems.

  • Materialized views, which only contain data required by a query, allow applications to quickly obtain the information they need.

  • Data it contains is completely disposable because it can be entirely rebuilt from the source data stores.

image-20240812-195755.png

Materialized View in Practice

CREATE MATERIALIZED VIEW user_purchase_summary AS SELECT u.id as user_id, COUNT(*) as total_purchases, SUM(CASE when p.status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_purchases FROM users u JOIN purchases p ON p.user_id = u.id;