К основному содержанию
скилл CX Codex

downloading-batch-export-files — скилл для Claude Code

Запускает разовый экспорт событий, сессий или запросов HogQL из PostHog и скачивает полученные файлы Parquet или JSONLines на диск.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add PostHog/skills --skill downloading-batch-export-files -a claude-code
Открыть на GitHub

Что делает downloading-batch-export-files

Скилл запускает разовые выгрузки сырых данных из PostHog. Агент формирует задачу на экспорт событий или выборок HogQL. Запуск выполняется через инструмент posthog:file-download-batch-exports-create, а проверка статуса — через posthog:file-download-batch-exports-retrieve. Если нужно, активный процесс можно прервать.

Для загрузки готовых файлов MCP намеренно не применяется. Эндпоинт PostHog использует HTTP-редирект, с которым у MCP пока нет явной совместимости. Поэтому скачивание идёт прямым запросом к REST API. По умолчанию размер части составляет 1024 МиБ. Для событий и сессий интервал ограничен одной неделей. Запросить больший отрезок за один раз API не позволит. Модель hogql работает в режиме закрытой беты.

Какие задачи решает

  • запустить разовый экспорт событий PostHog за выбранный интервал дат
  • выгрузить результаты произвольного HogQL-запроса в файл Parquet
  • отслеживать статус формирования архивов через MCP-опрос
  • скачать готовые части выгрузки через прямой вызов REST API

Примеры запросов агенту

  • Экспортируй события $pageview за вчерашний день в формате Parquet.
  • Выгрузи результат HogQL-запроса по событиям за последнюю неделю в JSONLines с компрессией gzip.
  • Проверь статус выгрузки 018f-export-run и скачай все готовые части.

Как установить downloading-batch-export-files

1Через Skills CLI (Vercel)

npx skills add PostHog/skills --skill downloading-batch-export-files -a claude-code

2Вручную: положить файлы

~/.claude/skills/downloading-batch-export-files/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/downloading-batch-export-files/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о downloading-batch-export-files

Как установить downloading-batch-export-files в Claude Code?

Выполните команду npx skills add PostHog/skills --skill downloading-batch-export-files -a claude-code. Навык сохранится в каталоге ~/.claude/skills/downloading-batch-export-files/SKILL.md.

Какие форматы и алгоритмы сжатия поддерживает экспорт?

Поддерживаются форматы Parquet и JSONLines. Для сжатия доступны zstd, gzip, brotli, lz4 и snappy, однако для JSONLines разрешены только gzip и brotli.

Почему скачивание выполняется через REST, а не через инструмент MCP?

Эндпоинт загрузки PostHog использует HTTP-редирект. Поскольку у MCP нет прямой поддержки перенаправлений, агент делает прямой запрос к GET /api/projects/{project_id}/file_download_batch_exports/{run_id}/download/{part}/.

Исходный текст

SKILL.md · MIT
---
name: downloading-batch-export-files
description: >
  Export PostHog events, persons, sessions, or the results of a HogQL query on demand and download the resulting
  files. Use when the user asks to download/export raw PostHog data, export HogQL query results, create a one-off
  file export, fetch a Parquet or JSONLines export, or use the file_download_batch_exports API.
  Covers starting the export with MCP, polling completion, and downloading via the existing REST redirect endpoint.
---

# Downloading batch export files

Use this skill when a user wants a one-off downloadable export of PostHog data.
The export is started and monitored through MCP, but the final file download uses the existing REST endpoint directly.

## Available MCP tools

| Tool                                           | Purpose                                                  |
| ---------------------------------------------- | -------------------------------------------------------- |
| `posthog:file-download-batch-exports-create`   | Start an on-demand export and return the run ID          |
| `posthog:file-download-batch-exports-retrieve` | Poll the run status and return file IDs after completion |

Do not rely on a generated MCP tool for the `/download/` endpoint.
That endpoint is a redirecting file download endpoint, so raw HTTP/download handling is the right interface until MCP has explicit redirect support.

## Workflow

### 1. Choose the export shape

Ask a short clarifying question if the user did not specify the required inputs:

- `model`: one of `events`, `persons`, `sessions`, or `hogql`
- `data_interval_start` and `data_interval_end`: ISO 8601 datetimes. Any supplied bound may not be in the future. When both bounds are supplied, they must be ordered and at most one week apart
  Required for `events`, `persons`, and `sessions`.
  For `hogql`, required only for the placeholders the query references. If only one placeholder is referenced, the other bound may be omitted and the one-week limit does not apply.
- `file.format`: `Parquet` or `JSONLines`; prefer `Parquet` for compact analytics exports and `JSONLines` for line-oriented text processing
- `file.compression`: optional, one of `zstd`, `gzip`, `brotli`, `lz4`, or `snappy`. If `JSONLines` was chosen as format, only `gzip` and `brotli` are supported.
- `file.max_size_mb`: part size in MiB, 1024 by default. A part can go a little over this size.
  Lower it when the user wants smaller parts, raise it for fewer and bigger ones, or set it to `null` to write a single file of any size.

For `events`, `include` and `exclude` are optional event-name filters.
Use them only when the user asks for specific events or wants to omit specific events.

For `hogql`, pass the query as `hogql_query` and leave out `include` and `exclude`.
You may prompt the user to export a slice of data by including a WHERE clause in the HogQL query, for example limiting results from the `events` table by bounding `timestamp`.
Always prefer limiting the data exported to the minimum necessary to solve the user's request.
Every column in the SELECT clause must be a field or have an alias.
This model is in closed beta and is enabled per team.

A `hogql` query can reference the `{data_interval_start}` and `{data_interval_end}` placeholders.
The export replaces them with the `data_interval_start` and `data_interval_end` values, so one query can export any interval.
Supply a bound for every placeholder the query references; a missing bound fails the request.
The bounds only replace placeholders and do not filter anything themselves, so a query without placeholders runs unchanged even when bounds are supplied.
Prefer placeholders over literal dates when the user wants a time range, or several consecutive ranges from the same query.
Compare with `>= {data_interval_start}` and `< {data_interval_end}`, so consecutive ranges do not export the same row twice.

### 2. Start the export

Call `posthog:file-download-batch-exports-create` with the selected shape.
The response contains an `id` for the export run.

Example request:

```json
{
  "model": "events",
  "file": {
    "format": "JSONLines",
    "compression": "gzip"
  },
  "include": ["$pageview"],
  "data_interval_start": "2026-05-25T00:00:00Z",
  "data_interval_end": "2026-05-26T00:00:00Z"
}
```

Example request for the `hogql` model:

```json
{
  "model": "hogql",
  "file": {
    "format": "Parquet"
  },
  "hogql_query": "SELECT event, timestamp, properties.$current_url AS url FROM events WHERE timestamp >= {data_interval_start} AND timestamp < {data_interval_end}",
  "data_interval_start": "2026-05-25T00:00:00Z",
  "data_interval_end": "2026-05-26T00:00:00Z"
}
```

### 3. Poll until completion

Call `posthog:file-download-batch-exports-retrieve` with the returned `id`.

Status handling:

| Status                                                                    | Action                                        |
| ------------------------------------------------------------------------- | --------------------------------------------- |
| `Starting` or `Running`                                                   | Wait briefly and poll again                   |
| `Completed`                                                               | Read the `files` array and download each file |
| `Cancelled`                                                               | Stop and report that the run was cancelled    |
| `Failed`, `FailedRetryable`, `FailedBilling`, `Terminated`, or `TimedOut` | Stop and report the `error` field             |

When `Completed`, the `files` array contains file UUIDs.
For single-file exports it usually contains one UUID.
For split exports, download every UUID unless the user asked for a specific part.

A `Completed` response also carries `records_completed`, the number of rows the run exported.
Report it to the user, because the count is otherwise only visible by opening every file.

### 4. Optionally, cancel a running export

If required by the user, a running export can be cancelled by calling `posthog:file-download-batch-exports-cancel-create` with the returned `id`.

An export that has already finished or has already failed may not be cancelled.

After cancelling an export, the `id` may not be used anymore and the export must start again from the beginning. However, you may still use the `id` to retrieve the export status (which will always be `Cancelled`).

### 5. Download files through REST

Use a direct authenticated HTTP request to the existing endpoint:

```text
GET /api/projects/{project_id}/file_download_batch_exports/{run_id}/download/{part}/
```

`part` can be either:

- a file UUID from the `files` array returned by `file-download-batch-exports-retrieve`
- a zero-based file index, ordered by key

If there is only one file, this also works without `part`:

```text
GET /api/projects/{project_id}/file_download_batch_exports/{run_id}/download/
```

Let the HTTP client follow the redirect, or inspect the `Location` header if you need the temporary signed URL.
Use the same PostHog authentication context as other API calls.

### 6. Save, do not print, file contents

Treat the result as a file download, not a chat response.
Parquet is binary and must be written as bytes.
JSONLines may still be large; save it to a file rather than pasting the contents unless the user explicitly asks for a tiny sample.

Use a filename that includes the model, run ID, and part identifier when possible, for example:

```text
posthog-events-<run_id>-<part>.jsonl.gz
posthog-persons-<run_id>-<part>.parquet
```

## Important notes

- The maximum export interval is one week. Split longer user requests into separate export runs or ask which week to export.
- The `hogql` model is in closed beta and is enabled per team. A permission error that says HogQL batch exports are not enabled means the team does not have the beta. Report that instead of retrying with a different query, and tell the user they can contact PostHog support to request access.
- The `hogql` model runs under stricter resource limits than the other models, because user queries are less predictable. If an export fails on memory, execution time, or bytes read, suggest narrowing the query with a WHERE clause instead of retrying it unchanged.
- The `hogql` model accepts an optional `hogql_modifiers` object. Each modifier in it overrides the project HogQL modifier with the same name for this export only, and the project modifiers apply to all others. Unless the project sets the `convertToProjectTimezone` modifier, `timestamp` columns come out in UTC, so pass `{"convertToProjectTimezone": true}` when the user wants them in the project timezone. Pass the same `hogql_modifiers` to `posthog:file-download-batch-exports-count-rows-create`, so that the count matches the export.
- A run can briefly report `Running` after completion while file records are being created. Poll again instead of failing immediately.
- Download URLs are temporary. If a URL expires, call the REST download endpoint again for a fresh redirect.
- Do not send the signed URL to unrelated services unless the user explicitly asks; it grants temporary access to the exported file.
- If the user wants all parts of a split export, iterate over every UUID in `files`; do not assume part `0` is enough.
- Large batch exports may take a few minutes or even longer to complete. Suggest to the user that they can speed-up their download by including only certain events or narrowing the date range.

© PostHog · MIT · PostHog/skills

Похожие скиллы

Все скиллы по теме «Данные и базы» →
batch-files официальный github Добавляет в GitHub Copilot знание синтаксиса cmd.exe для написания, отладки и поддержки файлов .bat и .cmd. Пригодится для автоматизации задач в Windows и скриптов планировщика. 206установок bulk-data-sharing-design Samuel Berthe Помогает спроектировать выгрузку данных клиентам: Parquet в бакете, нативные шеры Snowflake или Delta Sharing. Пригодится, когда SaaS отдаёт данные пачками, а не через API. CX Codex +1 7 800установок Anythink all-in-one backend: data, auth, files, workflows, payments, APIs anythink-cloud MCP-сервер Anythink даёт агенту доступ к бэкенду: сущности, данные, воркфлоу, пользователи, файлы и платежи — прямо из терминала. CX Codex +1 ★ 6звёзд репо wiki-export Ar9av Выгружает граф викилинков из Obsidian в JSON, GraphML, Cypher, SQL, HTML или OKF. Нужен, когда данные вики надо открыть в Gephi, Neo4j или своём скрипте. CX Codex +1 3 200установок marimo-batch marimo-team Скилл переводит блокноты marimo в режим пакетного запуска через CLI и планировщик. Он добавляет типизацию параметров на Pydantic и сохраняет работу в веб-интерфейсе. CX Codex +1 3 700установок posthog-analytics alinaqi Скилл для внедрения продуктовой аналитики PostHog: события, идентификация пользователей, фича-флаги и дашборды. Пригодится, когда нужно добавить трекинг в проект. CX Codex +1 809установок

Из того же набора48

formatting-insight-axes Подбирает правильную единицу оси Y при создании инсайта в PostHog: секунды, миллисекунды, проценты, валюта. Избавляет от формул ради пересчёта единиц. CX Codex +1 353установок managing-path-cleaning-rules Скилл обучает агента находить разрозненные URL в аналитике PostHog, составлять регулярные выражения re2 и объединять динамические сегменты адресов в читаемые шаблоны. CX Codex +1 353установок investigating-error-issue Разбирает одну ошибку PostHog по ID или URL: показывает затронутых пользователей, условия появления и возможную связь с релизом. CX Codex +1 337установок triaging-error-issues Собирает короткий список ошибок PostHog, на которые стоит смотреть: новые, всплески и те, что задели много пользователей. Пригодится на утреннем или дежурном разборе. CX Codex +1 329установок diagnosing-stacktrace-symbolication Разбирает, почему кадры стека в PostHog Error Tracking остаются минифицированными после загрузки символов, и ведёт по шагам до причины. CX Codex +1 327установок assessing-heatmaps Скилл разбирает тепловую карту страницы: где кликают, где злятся, докуда доскролливают, и что с этим делать. CX Codex +1 324установок signals-scout-general Скилл для PostHog: ищет корреляции между продуктами и заглядывает туда, куда не смотрят узкие скауты. Пишет отчёт в инбокс. CX Codex +1 314установок designing-email-templates Скилл создаёт и редактирует шаблоны писем для кампаний и рабочих процессов PostHog через MCP. Пригодится, когда письмо нужно собрать из редактируемых блоков и персонализировать с помощью Liquid. CX Codex +1 301установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой