optimizing-clickhouse-and-hogql-queries
Workflow for optimizing ClickHouse and HogQL queries. Use when a HogQL query, query runner, insight, or report is too slow; when a hand-written ClickHouse…
от PostHog★ 41 278 звёзд на GitHub
Установить optimizing-clickhouse-and-hogql-queries в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Optimizing ClickHouse and HogQL queries
Optimizes ClickHouse and HogQL queries (HogQL compiles to ClickHouse), not Postgres / Django ORM. For an app-DB query (Model.objects.filter(...)), stop and use profiling-slow-api-endpoints; Step 0 has the full triage.
Work from the ClickHouse SQL, not the HogQL. Get the ClickHouse SQL the query produces, optimize that, then translate the change back into the HogQL query, query runner, printer, or a migration. Reasoning about HogQL alone hides what ClickHouse executes.
Assumes you can write HogQL. For new queries from scratch use /writing-clickhouse-queries; for migration mechanics, /clickhouse-migrations.
Optimizing every query a team owns
When the job is "optimize all of team X's queries," build the full inventory first or you'll miss some.
- Resolve the team to its owned paths with
/establishing-code-ownership. Owned paths span backend Python andfrontend/src/..., often across several products; don't silently narrow to one product or to the backend. - Find queries across every path. Most are Python (
*QueryRunner,execute_hogql_query, rawsync_execute), but plenty are built client-side and POSTed to/query. Grepfrontend/for:api.queryHogQL(...),HogQLQueryString, thehogql`...`templateNodeKind.HogQLQuery/kind: 'HogQLQuery'with aquery:string- nodes that compile to ClickHouse:
DataTableNode,EventsQuery,TrendsQuery/InsightVizNode,PropertyFilterType.HogQL - literals with
SELECT ... FROM events, or product markers ('survey sent',$survey_id)
The same query is sometimes implemented twice (backend runner plus frontend HogQL, often a stalled migration). Both are in-scope; a backend printer/function fix won't reach a hand-built frontend string.
Step 0: confirm you're at the right layer
Check how the query is built:
| What you see | Where it goes | What to use |
|---|---|---|
execute_hogql_query(...), HogQLQuery, a *QueryRunner, an insight, a HogQL .ambr |
ClickHouse via the HogQL printer | This skill |
sync_execute(...), client.execute(...), hand-written SELECT ... FROM events, a migration |
ClickHouse directly (no HogQL) | This skill (steps 2-5; skip step 1) |
Model.objects.filter(...), .raw(...), a queryset, RawSQL over the app DB |
Postgres via Django ORM | Not this skill. profiling-slow-api-endpoints |
personhog_client.*, get_personhog_client(), get_person_by_* |
personhog (gRPC, Postgres) | Not this skill. posthog/personhog_client/README.md |
If you were pointed at a coordinator / orchestrator / Celery task / Temporal workflow / management command, the ClickHouse query is usually one layer in (the dispatched activity, child workflow, or apply_async target). Follow the dispatch to the layer that builds the HogQL. A file may mix Postgres (pick work) and HogQL (do work); treat them as separate tasks.
If the slow query is raw ClickHouse SQL in production code (f-strings / strings to sync_execute, client.execute, client.read_query, not printer output), flag it, then continue. The printer gives HogQL materialized-column substitution, property-group dispatch, lazy joins, and team-id guards for free; raw SQL reimplements or loses each. The structural fix is to express it in HogQL, but that's larger; offer both options (local fix now, HogQL move later).
Single-team vs multi-team decides whether raw SQL is excusable. execute_hogql_query is team-scoped (one team, injects the team_id guard).
- One team should almost always be HogQL. A single-team
team_id = Xquery that's hand-written leaks materialization, lazy joins, and the team-id guard. Treat raw single-teamsync_executeas a smell. Clearest tell: a hand-rolled materialized-column lookup (e.g.get_materialized_column_for_property(...)with aJSONExtractfallback), which is the printer's job done by hand. - Many teams are exempt. Cross-team / global jobs (enrichment, billing rollups, "find every team where X" with no
team_idor ateam_id IN (...)) can't useexecute_hogql_query; keep them raw and optimize in place. A
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/investigation-playbook.md
- references/learnings.md
FAQ
Что делает скилл optimizing-clickhouse-and-hogql-queries?
Workflow for optimizing ClickHouse and HogQL queries. Use when a HogQL query, query runner, insight, or report is too slow; when a hand-written ClickHouse query (via `sync_execute` or in a migration) is too slow; when ClickHouse times out or hits memory limits; when investigating a slow `system.query_log` row; or when reviewing a proposed HogQL printer change for performance. Covers extracting the ClickHouse SQL, common smells (`FROM ... FINAL`, `JSONExtract` over properties, missing skip indexes, self-joins, CTE blow-up), measuring against a real cluster, and applying the fix at the right layer (printer, query runner, or migration). Does NOT cover Postgres / Django ORM / app-database queries; for those use `profiling-slow-api-endpoints`.
Как установить скилл optimizing-clickhouse-and-hogql-queries?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл optimizing-clickhouse-and-hogql-queries запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
AnthropicUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
xlsx
AnthropicUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
pptx
AnthropicUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…