๐Ÿ“Š Data Engineering

ClickHouse

ClickHouse

A column-oriented OLAP database. Ultra-fast analytic queries.

Detailed Explanation

ClickHouse is an open-source column-oriented OLAP database developed by Yandex, offering extreme performance by processing billions of rows per second in real-time analytical queries. It is optimized for workloads that require large-scale aggregation, such as web analytics, log analytics, time-series data, and real-time dashboards.

The secret to ClickHouse's performance is a combination of several optimization techniques. Columnar storage minimizes I/O by reading only the necessary columns, and vectorized query execution uses SIMD instructions to maximize CPU efficiency. Data compression (LZ4, ZSTD) reduces storage space while also decreasing disk I/O, and the sparse index and granule-based skip indexes prevent unnecessary data scans.

The MergeTree engine family is the core of ClickHouse, storing data as sorted parts and merging them in the background. ReplacingMergeTree is used for deduplication, AggregatingMergeTree for pre-aggregation, and CollapsingMergeTree for tracking state changes. Distributed queries are handled by Distributed tables, which read data across multiple shards in parallel and merge the results.

ClickHouse supports standard SQL while also providing extensions useful for analytics, such as array functions, aggregate combinators (Combinators), and window functions. Integration with external systems such as Kafka, S3, PostgreSQL, and MySQL can also be implemented easily through table engines or table functions.

Code Example

-- ClickHouse ํ…Œ์ด๋ธ” ์ƒ์„ฑ ๋ฐ ๋ถ„์„ ์ฟผ๋ฆฌ ์˜ˆ์ œ

-- ============================================
-- 1. MergeTree ํ…Œ์ด๋ธ” ์ƒ์„ฑ
-- ============================================

-- ๊ธฐ๋ณธ ์ด๋ฒคํŠธ ํ…Œ์ด๋ธ”
CREATE TABLE events (
    event_id UUID DEFAULT generateUUIDv4(),
    event_date Date,
    event_timestamp DateTime64(3),
    user_id UInt64,
    session_id String,
    event_type LowCardinality(String),
    page_url String,
    referrer String,
    device_type LowCardinality(String),
    country LowCardinality(String),
    city String,
    revenue Decimal(18, 2) DEFAULT 0,
    properties String  -- JSON ๋ฌธ์ž์—ด
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_date)
ORDER BY (event_type, user_id, event_timestamp)
TTL event_date + INTERVAL 1 YEAR
SETTINGS index_granularity = 8192;

-- ์ธ๋ฑ์Šค ์ถ”๊ฐ€
ALTER TABLE events ADD INDEX idx_country (country) TYPE set(100) GRANULARITY 3;
ALTER TABLE events ADD INDEX idx_session (session_id) TYPE bloom_filter GRANULARITY 1;

-- ============================================
-- 2. ์‹ค์‹œ๊ฐ„ ๋ถ„์„ ์ฟผ๋ฆฌ
-- ============================================

-- ์‹œ๊ฐ„๋Œ€๋ณ„ ์ด๋ฒคํŠธ ์ง‘๊ณ„ (์‹ค์‹œ๊ฐ„ ๋Œ€์‹œ๋ณด๋“œ์šฉ)
SELECT
    toStartOfMinute(event_timestamp) AS minute,
    event_type,
    count() AS event_count,
    uniq(user_id) AS unique_users,
    sum(revenue) AS total_revenue
FROM events
WHERE event_date = today()
  AND event_timestamp >= now() - INTERVAL 1 HOUR
GROUP BY minute, event_type
ORDER BY minute DESC, event_count DESC;

-- ํผ๋„ ๋ถ„์„
SELECT
    user_id,
    anyIf(event_timestamp, event_type = 'page_view') AS step1_time,
    anyIf(event_timestamp, event_type = 'add_to_cart') AS step2_time,
    anyIf(event_timestamp, event_type = 'checkout') AS step3_time,
    anyIf(event_timestamp, event_type = 'purchase') AS step4_time
FROM events
WHERE event_date >= today() - 7
GROUP BY user_id
HAVING step1_time IS NOT NULL;

-- windowFunnel ํ•จ์ˆ˜๋กœ ํผ๋„ ๋ถ„์„ (๋” ์ •ํ™•)
SELECT
    level,
    count() AS users
FROM (
    SELECT
        user_id,
        windowFunnel(3600)(
            event_timestamp,
            event_type = 'page_view',
            event_type = 'add_to_cart',
            event_type = 'checkout',
            event_type = 'purchase'
        ) AS level
    FROM events
    WHERE event_date >= today() - 7
    GROUP BY user_id
)
GROUP BY level
ORDER BY level;

-- ============================================
-- 3. ๋ฐฐ์—ด ํ•จ์ˆ˜ ํ™œ์šฉ
-- ============================================

-- ์„ธ์…˜๋ณ„ ์ด๋ฒคํŠธ ์‹œํ€€์Šค
SELECT
    session_id,
    groupArray(event_type) AS event_sequence,
    groupArray(event_timestamp) AS timestamps,
    length(groupArray(event_type)) AS event_count
FROM events
WHERE event_date = today()
GROUP BY session_id
HAVING event_count > 3
LIMIT 100;

-- ๋ฐฐ์—ด ์š”์†Œ๋ณ„ ์ง‘๊ณ„
SELECT
    arrayJoin(splitByChar(',', tags)) AS tag,
    count() AS usage_count
FROM products
GROUP BY tag
ORDER BY usage_count DESC
LIMIT 20;

-- ============================================
-- 4. ์ง‘๊ณ„ ์กฐํ•ฉ์ž (Combinators)
-- ============================================

-- ์กฐ๊ฑด๋ถ€ ์ง‘๊ณ„
SELECT
    event_date,
    countIf(event_type = 'page_view') AS page_views,
    countIf(event_type = 'purchase') AS purchases,
    sumIf(revenue, event_type = 'purchase') AS total_revenue,
    uniqIf(user_id, event_type = 'purchase') AS purchasing_users,
    avgIf(revenue, revenue > 0) AS avg_purchase_value
FROM events
WHERE event_date >= today() - 30
GROUP BY event_date
ORDER BY event_date;

-- ์ƒํƒœ ์ €์žฅ ์ง‘๊ณ„ (์‹ค์‹œ๊ฐ„ ์—…๋ฐ์ดํŠธ์šฉ)
-- AggregatingMergeTree ํ…Œ์ด๋ธ”
CREATE TABLE events_aggregated (
    event_date Date,
    event_type LowCardinality(String),
    event_count AggregateFunction(count),
    unique_users AggregateFunction(uniq, UInt64),
    total_revenue AggregateFunction(sum, Decimal(18, 2))
)
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(event_date)
ORDER BY (event_date, event_type);

-- Materialized View๋กœ ์ž๋™ ์ง‘๊ณ„
CREATE MATERIALIZED VIEW events_aggregated_mv
TO events_aggregated
AS SELECT
    event_date,
    event_type,
    countState() AS event_count,
    uniqState(user_id) AS unique_users,
    sumState(revenue) AS total_revenue
FROM events
GROUP BY event_date, event_type;

-- ์ง‘๊ณ„ ๊ฒฐ๊ณผ ์กฐํšŒ
SELECT
    event_date,
    event_type,
    countMerge(event_count) AS events,
    uniqMerge(unique_users) AS users,
    sumMerge(total_revenue) AS revenue
FROM events_aggregated
GROUP BY event_date, event_type;

-- ============================================
-- 5. ์™ธ๋ถ€ ๋ฐ์ดํ„ฐ ์†Œ์Šค ์—ฐ๋™
-- ============================================

-- Kafka์—์„œ ์‹ค์‹œ๊ฐ„ ์ˆ˜์ง‘
CREATE TABLE events_kafka (
    event_id String,
    user_id UInt64,
    event_type String,
    event_timestamp DateTime64(3),
    properties String
)
ENGINE = Kafka()
SETTINGS
    kafka_broker_list = 'kafka:9092',
    kafka_topic_list = 'user-events',
    kafka_group_name = 'clickhouse-consumer',
    kafka_format = 'JSONEachRow';

-- Kafka -> MergeTree ํŒŒ์ดํ”„๋ผ์ธ
CREATE MATERIALIZED VIEW events_kafka_mv
TO events
AS SELECT
    generateUUIDv4() AS event_id,
    toDate(event_timestamp) AS event_date,
    event_timestamp,
    user_id,
    '' AS session_id,
    event_type,
    '' AS page_url,
    '' AS referrer,
    '' AS device_type,
    '' AS country,
    '' AS city,
    0 AS revenue,
    properties
FROM events_kafka;

-- S3์—์„œ ์ง์ ‘ ์ฟผ๋ฆฌ
SELECT *
FROM s3(
    'https://bucket.s3.amazonaws.com/data/*.parquet',
    'AWS_ACCESS_KEY',
    'AWS_SECRET_KEY',
    'Parquet'
)
WHERE event_date = '2024-01-15'
LIMIT 100;

-- ============================================
-- 6. ์„ฑ๋Šฅ ์ตœ์ ํ™”
-- ============================================

-- ์ฟผ๋ฆฌ ์‹คํ–‰ ๊ณ„ํš ํ™•์ธ
EXPLAIN PLAN
SELECT event_type, count()
FROM events
WHERE event_date = today()
GROUP BY event_type;

-- ํŒŒ์ดํ”„๋ผ์ธ ๋ถ„์„
EXPLAIN PIPELINE
SELECT event_type, count()
FROM events
WHERE event_date = today()
GROUP BY event_type;

-- ์‹œ์Šคํ…œ ํ…Œ์ด๋ธ”๋กœ ์„ฑ๋Šฅ ๋ชจ๋‹ˆํ„ฐ๋ง
SELECT
    query_id,
    query,
    read_rows,
    read_bytes,
    memory_usage,
    query_duration_ms
FROM system.query_log
WHERE type = 'QueryFinish'
  AND event_date = today()
ORDER BY query_duration_ms DESC
LIMIT 10;

-- ํŒŒํŠธ ์ •๋ณด ํ™•์ธ
SELECT
    partition,
    name,
    rows,
    bytes_on_disk,
    modification_time
FROM system.parts
WHERE table = 'events'
  AND active
ORDER BY modification_time DESC;

-- ============================================
-- 7. Python ํด๋ผ์ด์–ธํŠธ ์˜ˆ์ œ
-- ============================================
"""
from clickhouse_driver import Client
import pandas as pd

# ํด๋ผ์ด์–ธํŠธ ์—ฐ๊ฒฐ
client = Client(
    host='localhost',
    port=9000,
    user='default',
    password='',
    database='analytics'
)

# ์ฟผ๋ฆฌ ์‹คํ–‰
result = client.execute('''
    SELECT
        event_date,
        count() as events,
        uniq(user_id) as users
    FROM events
    WHERE event_date >= today() - 7
    GROUP BY event_date
    ORDER BY event_date
''')

# DataFrame์œผ๋กœ ๋ณ€ํ™˜
df = pd.DataFrame(result, columns=['event_date', 'events', 'users'])
print(df)

# ๋ฐฐ์น˜ ์‚ฝ์ž…
data = [
    {'user_id': 1, 'event_type': 'click', 'event_timestamp': '2024-01-15 10:00:00'},
    {'user_id': 2, 'event_type': 'view', 'event_timestamp': '2024-01-15 10:01:00'},
]

client.execute(
    'INSERT INTO events (user_id, event_type, event_timestamp) VALUES',
    data
)
"""

How it is used in practice

Backend developer: "Our real-time analytics dashboard queries take more than 5 seconds. Is there a way to make them faster?"

Data engineer: "If you adopt ClickHouse, the same query can drop to a few hundred milliseconds. Thanks to columnar storage and vectorized execution, aggregation queries are very fast."

Backend developer: "Can it also handle real-time data ingestion?"

Data engineer: "Yes, you can ingest streaming data with the Kafka engine and even aggregate automatically with Materialized Views. You can query right after ingestion, so it's perfect for real-time dashboards."

Interviewer: "Why is ORDER BY key design important in ClickHouse, and how should it be designed?"

Candidate: "The ORDER BY key determines the data sort order and the primary index. You should place columns that are frequently filtered in queries first so that the sparse index can be used effectively. Placing columns with low cardinality (e.g., event_type) first and those with high cardinality (e.g., user_id) later also improves the data compression ratio. However, since the ORDER BY key cannot be changed after the table is created, you must decide after thoroughly analyzing the main query patterns."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "You defined user_id as String, but if it's numeric, UInt64 is more efficient."

Developer: "It's in UUID form, so I used String."

Reviewer: "ClickHouse natively supports the UUID type. Also, for columns with low cardinality like event_type, using LowCardinality(String) applies dictionary encoding, which improves both storage space and query performance."

Cautions

Related Terms

Learn More