๐ Data Engineering
Materialize
A streaming database
A streaming database
Materialize is a streaming database that can run standard SQL queries on streaming data in real time. It uses Incremental View Maintenance technology to update query results immediately when data changes.
| Characteristics | Materialize | Flink SQL | ksqlDB |
|---|---|---|---|
| SQL Compatibility | PostgreSQL | ANSI SQL | KSQL |
| Join Complexity | Multiple tables | Limited | Limited |
| Latency | Milliseconds | Milliseconds to seconds | Milliseconds to seconds |
| State Management | Built-in | RocksDB | RocksDB |
| Ease of Use | High (SQL) | Medium | High |
-- Materialize ์คํธ๋ฆฌ๋ฐ SQL ์์
-- 1. Kafka ์์ค ์ฐ๊ฒฐ ์์ฑ
CREATE CONNECTION kafka_connection TO KAFKA (
BROKER 'kafka:9092',
SECURITY PROTOCOL = 'SASL_SSL',
SASL MECHANISMS = 'PLAIN',
SASL USERNAME = SECRET kafka_username,
SASL PASSWORD = SECRET kafka_password
);
-- 2. ์ฃผ๋ฌธ ์ด๋ฒคํธ ์คํธ๋ฆผ ์์ค ์์ฑ
CREATE SOURCE orders_source
FROM KAFKA CONNECTION kafka_connection (
TOPIC 'orders'
)
FORMAT JSON
WITH (
TIMESTAMP FIELD = 'order_time',
RETENTION = '7d'
);
-- 3. ์ํ ์ ๋ณด ์คํธ๋ฆผ ์์ค ์์ฑ
CREATE SOURCE products_source
FROM KAFKA CONNECTION kafka_connection (
TOPIC 'products'
)
FORMAT JSON;
-- 4. ์ค์๊ฐ ์ฃผ๋ฌธ ๋ทฐ ์์ฑ
CREATE MATERIALIZED VIEW orders AS
SELECT
(data->>'order_id')::int AS order_id,
(data->>'customer_id')::int AS customer_id,
(data->>'product_id')::int AS product_id,
(data->>'quantity')::int AS quantity,
(data->>'price')::decimal AS price,
(data->>'order_time')::timestamp AS order_time
FROM orders_source;
-- 5. ์ํ ์ ๋ณด ๋ทฐ ์์ฑ
CREATE MATERIALIZED VIEW products AS
SELECT
(data->>'product_id')::int AS product_id,
data->>'product_name' AS product_name,
data->>'category' AS category,
(data->>'unit_price')::decimal AS unit_price
FROM products_source;
-- 6. ์ค์๊ฐ ๋งค์ถ ์ง๊ณ (1์๊ฐ ์๋์ฐ)
CREATE MATERIALIZED VIEW hourly_sales AS
SELECT
date_trunc('hour', order_time) AS hour,
p.category,
COUNT(*) AS order_count,
SUM(o.quantity) AS total_quantity,
SUM(o.quantity * o.price) AS total_revenue
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE order_time > now() - INTERVAL '24 hours'
GROUP BY date_trunc('hour', order_time), p.category;
-- 7. ์ค์๊ฐ ๊ณ ๊ฐ๋ณ ๊ตฌ๋งค ํํฉ
CREATE MATERIALIZED VIEW customer_metrics AS
SELECT
customer_id,
COUNT(*) AS total_orders,
SUM(quantity * price) AS total_spent,
AVG(quantity * price) AS avg_order_value,
MAX(order_time) AS last_order_time
FROM orders
WHERE order_time > now() - INTERVAL '30 days'
GROUP BY customer_id;
-- ์ค์๊ฐ ์ด์ ํ์ง๋ฅผ ์ํ Materialized Views
-- 1๋ถ ๋จ์ ๊ฑฐ๋๋ ๋ชจ๋ํฐ๋ง
CREATE MATERIALIZED VIEW transaction_rate AS
SELECT
date_trunc('minute', order_time) AS minute,
COUNT(*) AS transaction_count,
SUM(price * quantity) AS total_value
FROM orders
WHERE order_time > now() - INTERVAL '1 hour'
GROUP BY date_trunc('minute', order_time);
-- ์ด์ ๊ฑฐ๋ ํ์ง (ํ๊ท ์ 3๋ฐฐ ์ด์)
CREATE MATERIALIZED VIEW anomaly_alerts AS
WITH stats AS (
SELECT
AVG(transaction_count) AS avg_count,
STDDEV(transaction_count) AS stddev_count
FROM transaction_rate
WHERE minute > now() - INTERVAL '24 hours'
)
SELECT
t.minute,
t.transaction_count,
t.total_value,
'HIGH_VOLUME' AS alert_type
FROM transaction_rate t, stats s
WHERE t.minute > now() - INTERVAL '5 minutes'
AND t.transaction_count > s.avg_count + 3 * s.stddev_count;
-- ๊ณ ๊ฐ๋ณ ์ด์ ํ๋ ํ์ง (5๋ถ ๋ด 10๊ฑด ์ด์ ์ฃผ๋ฌธ)
CREATE MATERIALIZED VIEW suspicious_customers AS
SELECT
customer_id,
COUNT(*) AS order_count_5min,
SUM(price * quantity) AS total_value_5min
FROM orders
WHERE order_time > now() - INTERVAL '5 minutes'
GROUP BY customer_id
HAVING COUNT(*) > 10;
# Python์์ Materialize ์ฌ์ฉํ๊ธฐ (psycopg2)
import psycopg2
import pandas as pd
from psycopg2 import sql
import time
# Materialize ์ฐ๊ฒฐ (PostgreSQL ํ๋กํ ์ฝ ์ฌ์ฉ)
conn = psycopg2.connect(
host="materialize.example.com",
port=6875,
user="materialize",
password="secret",
database="materialize"
)
conn.autocommit = True
def execute_query(query):
"""์ฟผ๋ฆฌ ์คํ ๋ฐ ๊ฒฐ๊ณผ ๋ฐํ"""
with conn.cursor() as cur:
cur.execute(query)
if cur.description:
columns = [desc[0] for desc in cur.description]
return pd.DataFrame(cur.fetchall(), columns=columns)
return None
# Materialized View ์์ฑ
create_view_sql = """
CREATE MATERIALIZED VIEW IF NOT EXISTS realtime_dashboard AS
SELECT
date_trunc('minute', order_time) AS minute,
COUNT(*) AS orders,
SUM(price * quantity) AS revenue
FROM orders
WHERE order_time > now() - INTERVAL '1 hour'
GROUP BY date_trunc('minute', order_time)
ORDER BY minute DESC
"""
execute_query(create_view_sql)
# ์ค์๊ฐ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ์กฐํ
def get_dashboard_data():
"""๋์๋ณด๋ ๋ฐ์ดํฐ ์กฐํ"""
df = execute_query("SELECT * FROM realtime_dashboard LIMIT 60")
return df
# SUBSCRIBE๋ฅผ ์ฌ์ฉํ ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ (๋ณ๊ฒฝ ์ฌํญ ํธ์)
def subscribe_to_changes():
"""๋ทฐ ๋ณ๊ฒฝ์ฌํญ์ ์ค์๊ฐ์ผ๋ก ๊ตฌ๋
"""
with conn.cursor() as cur:
# SUBSCRIBE ์์
cur.execute("SUBSCRIBE (SELECT * FROM realtime_dashboard)")
print("์ค์๊ฐ ๊ตฌ๋
์์...")
while True:
# ๋ณ๊ฒฝ์ฌํญ ์์
cur.execute("FETCH ALL FROM realtime_dashboard")
rows = cur.fetchall()
for row in rows:
mz_timestamp, mz_diff, minute, orders, revenue = row
action = "INSERT" if mz_diff > 0 else "DELETE"
print(f"[{action}] minute={minute}, orders={orders}, revenue={revenue}")
# ์ฐ๊ฒฐ ์ข
๋ฃ
def cleanup():
conn.close()
# dbt_project.yml
name: 'streaming_analytics'
version: '1.0.0'
profile: 'materialize'
models:
streaming_analytics:
+materialized: materializedview # Materialize ์ ์ฉ
# profiles.yml
materialize:
target: dev
outputs:
dev:
type: materialize
host: materialize.example.com
port: 6875
user: materialize
password: "{{ env_var('MZ_PASSWORD') }}"
database: materialize
schema: analytics
-- models/customer_lifetime_value.sql
-- dbt ๋ชจ๋ธ: ์ค์๊ฐ ๊ณ ๊ฐ ์์ ๊ฐ์น
{{ config(materialized='materializedview') }}
WITH customer_orders AS (
SELECT
customer_id,
order_id,
order_time,
price * quantity AS order_value
FROM {{ source('kafka', 'orders') }}
),
customer_stats AS (
SELECT
customer_id,
COUNT(DISTINCT order_id) AS total_orders,
SUM(order_value) AS total_revenue,
MIN(order_time) AS first_order,
MAX(order_time) AS last_order,
AVG(order_value) AS avg_order_value
FROM customer_orders
GROUP BY customer_id
)
SELECT
customer_id,
total_orders,
total_revenue,
first_order,
last_order,
avg_order_value,
-- ๊ฐ๋จํ CLV ๊ณ์ฐ (์ค์ ๋ก๋ ๋ ๋ณต์กํ ๋ชจ๋ธ ์ฌ์ฉ)
total_revenue *
GREATEST(1, EXTRACT(EPOCH FROM (now() - first_order)) /
EXTRACT(EPOCH FROM (last_order - first_order + INTERVAL '1 day')))
AS estimated_clv
FROM customer_stats
WHERE total_orders > 0