Communitygithub.com

clickhouse-io

ClickHouse-Datenbankmuster, Query-Optimierung, Analytik und Data-Engineering-Best-Practices für leistungsstarke Analyse-Workloads. Verwenden Sie dies beim Schreiben von ClickHouse-Schemas oder -Queries oder wenn eine analytische Abfrage zu langsam ist.

Was ist clickhouse-io?

Diese Fähigkeit bietet eine umfassende Referenz für die Arbeit mit ClickHouse, einer spaltenorientierten DBMS für Online Analytical Processing (OLAP). Sie deckt die wichtigsten Tabellen-Design-Muster ab, darunter MergeTree, ReplacingMergeTree und AggregatingMergeTree mit praktischen SQL-Beispielen. Optimierungstechniken wie effizientes Filtern, Aggregationen und Fensterfunktionen werden detailliert beschrieben, um Query-Performance zu steigern. Für die Dateneingabe empfiehlt die Fähigkeit Batch- und Streaming-Insert-Muster über die ClickHouse-Client-Bibliothek für TypeScript/Node.js. Materialisierte Sichten, Performance-Monitoring über system.query_log und gängige Analytik-Abfragen (Zeitreihen, Trichter, Kohorten) sind enthalten. Best Practices zu Partitionierung, Ordering Keys, Datentypen und das Vermeiden häufiger Fallstricke runden die Anleitung ab – ideal für Entwickler und Data Engineers, die ClickHouse für Echtzeit-Analytik einsetzen.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/clickhouse-io

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

ClickHouse Analytics-Muster

ClickHouse-spezifische Muster für leistungsstarke Analytik und Data Engineering.

Wann aktivieren

  • Entwerfen von ClickHouse-Tabellenschemas (MergeTree-Engine-Auswahl)
  • Schreiben analytischer Abfragen (Aggregationen, Fensterfunktionen, Joins)
  • Optimieren der Abfrageleistung (Partitions-Pruning, Projections, materialisierte Ansichten)
  • Aufnehmen großer Datenmengen (Batch-Inserts, Kafka-Integration)
  • Migration von PostgreSQL/MySQL zu ClickHouse für Analytik
  • Implementieren von Echtzeit-Dashboards oder Zeitreihen-Analytik

Überblick

ClickHouse ist ein spaltenorientiertes Datenbankmanagementsystem (DBMS) für die Online Analytical Processing (OLAP). Es ist optimiert für schnelle analytische Abfragen auf großen Datensätzen.

Wichtige Funktionen:

  • Spaltenorientierte Speicherung
  • Datenkompression
  • Parallele Abfrageausführung
  • Verteiltes Abfragen
  • Echtzeit-Analytik

Tabellen-Design-Muster

MergeTree-Engine (Am häufigsten)

CREATE TABLE markets_analytics (
    date Date,
    market_id String,
    market_name String,
    volume UInt64,
    trades UInt32,
    unique_traders UInt32,
    avg_trade_size Float64,
    created_at DateTime
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(date)
ORDER BY (date, market_id)
SETTINGS index_granularity = 8192;

ReplacingMergeTree (Deduplizierung)

-- Für Daten, die Duplikate enthalten können (z. B. aus mehreren Quellen)
CREATE TABLE user_events (
    event_id String,
    user_id String,
    event_type String,
    timestamp DateTime,
    properties String
) ENGINE = ReplacingMergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (user_id, event_id, timestamp)
PRIMARY KEY (user_id, event_id);

AggregatingMergeTree (Voraggregation)

-- Zum Verwalten aggregierter Metriken
CREATE TABLE market_stats_hourly (
    hour DateTime,
    market_id String,
    total_volume AggregateFunction(sum, UInt64),
    total_trades AggregateFunction(count, UInt32),
    unique_users AggregateFunction(uniq, String)
) ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(hour)
ORDER BY (hour, market_id);

-- Aggregierte Daten abfragen
SELECT
    hour,
    market_id,
    sumMerge(total_volume) AS volume,
    countMerge(total_trades) AS trades,
    uniqMerge(unique_users) AS users
FROM market_stats_hourly
WHERE hour >= toStartOfHour(now() - INTERVAL 24 HOUR)
GROUP BY hour, market_id
ORDER BY hour DESC;

Abfrageoptimierungs-Muster

Effizientes Filtern

-- PASS: GUT: Indizierte Spalten zuerst verwenden
SELECT *
FROM markets_analytics
WHERE date >= '2025-01-01'
  AND market_id = 'market-123'
  AND volume > 1000
ORDER BY date DESC
LIMIT 100;

-- FAIL: SCHLECHT: Filtern auf nicht indizierte Spalten zuerst
SELECT *
FROM markets_analytics
WHERE volume > 1000
  AND market_name LIKE '%election%'
  AND date >= '2025-01-01';

Aggregationen

-- PASS: GUT: ClickHouse-spezifische Aggregationsfunktionen verwenden
SELECT
    toStartOfDay(created_at) AS day,
    market_id,
    sum(volume) AS total_volume,
    count() AS total_trades,
    uniq(trader_id) AS unique_traders,
    avg(trade_size) AS avg_size
FROM trades
WHERE created_at >= today() - INTERVAL 7 DAY
GROUP BY day, market_id
ORDER BY day DESC, total_volume DESC;

-- PASS: Quantile für Perzentile verwenden (effizienter als percentile)
SELECT
    quantile(0.50)(trade_size) AS median,
    quantile(0.95)(trade_size) AS p95,
    quantile(0.99)(trade_size) AS p99
FROM trades
WHERE created_at >= now() - INTERVAL 1 HOUR;

Fensterfunktionen

-- Laufende Summen berechnen
SELECT
    date,
    market_id,
    volume,
    sum(volume) OVER (
        PARTITION BY market_id
        ORDER BY date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS cumulative_volume
FROM markets_analytics
WHERE date >= today() - INTERVAL 30 DAY
ORDER BY market_id, date;

Daten-Einfügemuster

Massen-Einfügen (Empfohlen)

import { createClient } from '@clickhouse/client'

const clickhouse = createClient({
  url: process.env.CLICKHOUSE_URL ?? 'http://localhost:8123',
  username: process.env.CLICKHOUSE_USER,
  password: process.env.CLICKHOUSE_PASSWORD
})

// PASS: Batch-Insert (effizient)
async function bulkInsertTrades(trades: Trade[]) {
  await clickhouse.insert({
    table: 'trades',
    values: trades.map(trade => ({
      id: trade.id,
      market_id: trade.market_id,
      user_id: trade.user_id,
      amount: trade.amount,
      timestamp: trade.timestamp.toISOString()
    })),
    format: 'JSONEachRow'
  })
}

// FAIL: Einzelne Inserts (langsam)
async function insertTrade(trade: Trade) {
  // Nicht in einer Schleife verwenden!
  await clickhouse.insert({
    table: 'trades',
    values: [{
      id: trade.id,
      market_id: trade.market_id,
      user_id: trade.user_id,
      amount: trade.amount,
      timestamp: trade.timestamp.toISOString()
    }],
    format: 'JSONEachRow'
  })
}

Streaming-Insert

// Für kontinuierliche Datenerfassung
import { Readable } from 'node:stream'

async function streamInserts(dataSource: AsyncIterable<Record<string, unknown>>) {
  await clickhouse.insert({
    table: 'trades',
    values: Readable.from(dataSource, { objectMode: true }),
    format: 'JSONEachRow'
  })
}

Materialisierte Ansichten

Echtzeit-Aggregationen

-- Materialisierte Ansicht für stündliche Statistiken erstellen
CREATE MATERIALIZED VIEW market_stats_hourly_mv
TO market_stats_hourly
AS SELECT
    toStartOfHour(timestamp) AS hour,
    market_id,
    sumState(amount) AS total_volume,
    countState() AS total_trades,
    uniqState(user_id) AS unique_users
FROM trades
GROUP BY hour, market_id;

-- Materialisierte Ansicht abfragen
SELECT
    hour,
    market_id,
    sumMerge(total_volume) AS volume,
    countMerge(total_trades) AS trades,
    uniqMerge(unique_users) AS users
FROM market_stats_hourly
WHERE hour >= now() - INTERVAL 24 HOUR
GROUP BY hour, market_id;

Performance-Überwachung

Abfrageleistung

-- Langsame Abfragen überprüfen
SELECT
    query_id,
    user,
    query,
    query_duration_ms,
    read_rows,
    read_bytes,
    memory_usage
FROM system.query_log
WHERE type = 'QueryFinish'
  AND query_duration_ms > 1000
  AND event_time >= now() - INTERVAL 1 HOUR
ORDER BY query_duration_ms DESC
LIMIT 10;

Tabellenstatistiken

-- Tabellengrößen überprüfen
SELECT
    database,
    table,
    formatReadableSize(sum(bytes)) AS size,
    sum(rows) AS rows,
    max(modification_time) AS latest_modification
FROM system.parts
WHERE active
GROUP BY database, table
ORDER BY sum(bytes) DESC;

Häufige Analytik-Abfragen

Zeitreihenanalyse

-- Tägliche aktive Nutzer
SELECT
    toDate(timestamp) AS date,
    uniq(user_id) AS daily_active_users
FROM events
WHERE timestamp >= today() - INTERVAL 30 DAY
GROUP BY date
ORDER BY date;

-- Bindungsanalyse
SELECT
    signup_date,
    countIf(days_since_signup = 0) AS day_0,
    countIf(days_since_signup = 1) AS day_1,
    countIf(days_since_signup = 7) AS day_7,
    countIf(days_since_signup = 30) AS day_30
FROM (
    SELECT
        user_id,
        min(toDate(timestamp)) AS signup_date,
        toDate(timestamp) AS activity_date,
        dateDiff('day', signup_date, activity_date) AS days_since_signup
    FROM events
    GROUP BY user_id, activity_date
)
GROUP BY signup_date
ORDER BY signup_date DESC;

Trichteranalyse

-- Conversion-Trichter
SELECT
    countIf(step = 'viewed_market') AS viewed,
    countIf(step = 'clicked_trade') AS clicked,
    countIf(step = 'completed_trade') AS completed,
    round(clicked / viewed * 100, 2) AS view_to_click_rate,
    round(completed / clicked * 100, 2) AS click_to_completion_rate
FROM (
    SELECT
        user_id,
        session_id,
        event_type AS step
    FROM events
    WHERE event_date = today()
)
GROUP BY session_id;

Kohortenanalyse

-- Nutzerkohorten nach Anmeldemonat
SELECT
    toStartOfMonth(signup_date) AS cohort,
    toStartOfMonth(activity_date) AS month,
    dateDiff('month', cohort, month) AS months_since_signup,
    count(DISTINCT user_id) AS active_users
FROM (
    SELECT
        user_id,
        min(toDate(timestamp)) OVER (PARTITION BY user_id) AS signup_date,
        toDate(timestamp) AS activity_date
    FROM events
)
GROUP BY cohort, month, months_since_signup
ORDER BY cohort, months_since_signup;

Daten-Pipeline-Muster

ETL-Muster

// Extrahieren, Transformieren, Laden
async function etlPipeline() {
  // 1. Aus Quelle extrahieren
  const rawData = await extractFromPostgres()

  // 2. Transformieren
  const transformed = rawData.map(row => ({
    date: new Date(row.created_at).toISOString().split('T')[0],
    market_id: row.market_slug,
    volume: parseFloat(row.total_volume),
    trades: parseInt(row.trade_count)
  }))

  // 3. In ClickHouse laden
  await bulkInsertToClickHouse(transformed)
}

// Regelmäßig ausführen
setInterval(etlPipeline, 60 * 60 * 1000)  // Jede Stunde

Change Data Capture (CDC)

// Auf PostgreSQL-Änderungen hören und mit ClickHouse synchronisieren
import { Client } from 'pg'

const pgClient = new Client({ connectionString: process.env.DATABASE_URL })

pgClient.query('LISTEN market_updates')

pgClient.on('notification', async (msg) => {
  const update = JSON.parse(msg.payload)

  await clickhouse.insert({
    table: 'market_updates',
    values: [
      {
        market_id: update.id,
        event_type: update.operation,  // INSERT, UPDATE, DELETE
        timestamp: new Date(),
        data: JSON.stringify(update.new_data)
      }
    ],
    format: 'JSONEachRow'
  })
})

Best Practices

1. Partitionierungsstrategie

  • Nach Zeit partitionieren (normalerweise Monat oder Tag)
  • Zu viele Partitionen vermeiden (Leistungsauswirkung)
  • DATE-Typ für Partitionsschlüssel verwenden

2. Ordering-Key

  • Am häufigsten gefilterte Spalten zuerst setzen
  • Kardinalität berücksichtigen (hohe Kardinalität zuerst)
  • Die Reihenfolge wirkt sich auf die Kompression aus

3. Datentypen

  • Kleinstmöglichen passenden Typ verwenden (UInt32 vs. UInt64)
  • LowCardinality für wiederholte Zeichenfolgen verwenden
  • Enum für kategorische Daten verwenden

4. Vermeiden

  • SELECT * (Spalten angeben)
  • FINAL (Daten stattdessen vor der Abfrage zusammenführen)
  • Zu viele JOINs (für Analytik denormalisieren)
  • Kleine, häufige Inserts (stattdessen bündeln)

5. Überwachung

  • Abfrageleistung verfolgen
  • Speichernutzung überwachen
  • Merge-Operationen prüfen
  • Langsame Abfragen im Log überprüfen

Denken Sie daran: ClickHouse ist für analytische Workloads optimiert. Entwerfen Sie Tabellen für Ihre Abfragemuster, führen Sie Batch-Inserts durch und nutzen Sie materialisierte Ansichten für Echtzeit-Aggregationen.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Verwandte Skills