Repository navigation
Хранение и алгоритмы сжатия данных - ПР 2 - Spark: ORC vs Parquet #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| ## SaDCA — Лабораторная 2. Spark DataSource V2 + Parquet/ORC | ||
|
|
||
| ### Цель | ||
| Реализовать кастомный Source (DataSource V2) для Apache Spark на Java, читающий документы из PeaceDatabase по REST, построить простой ETL (read → transform → write) и сравнить эффективность хранения/чтения в Parquet и ORC. | ||
|
|
||
| Справочные материалы: | ||
| - Structured Streaming / Data Sources (Spark 3.5.x/4.x): [Structured Streaming Programming Guide](https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html) | ||
| - Hadoop winutils для Windows: [cdarlint/winutils](https://github.com/cdarlint/winutils) | ||
| - [How to Install Apache Spark on Windows](https://phoenixnap.com/kb/install-spark-on-windows-10) | ||
|
|
||
| ### Окружение | ||
| - ОС: Windows 11, JDK 11 | ||
| - Spark: 3.5.7 (Hadoop 3) | ||
| - PeaceDatabase Web API: `http://localhost:5000`, БД: `news` | ||
|
|
||
| ### Архитектура решения | ||
| - Кастомный коннектор (Java DataSource V2, batch read) → REST: | ||
| - Эндпоинт пагинации: `GET /v1/db/{db}/_all_docs?skip=&limit=&includeDeleted=` | ||
| - Схема набора: | ||
| - `id` (string), `rev` (string), `deleted` (boolean) | ||
| - `tags` (array<string>), `content` (string) | ||
| - `data_json` (string) — сырой JSON поля `data` (для совместимости) | ||
| - Планирование чтения: создаётся `InputPartition` на каждую страницу. При указании `maxRows` план основан на N (без доверия к `total` из API). Для случая без лимита выполняется «быстрый» пробег страниц до короткой/пустой. | ||
| - Джоб (Spark App) делает преобразование и запись в две колоночные цели: | ||
| - Парсит `data_json` в столбцы: `link, headline, category, short_description, authors, date` (типизированные колонки улучшают компрессию/пушдаун) | ||
| - Примерные признаки: `tags_count = size(tags)`, `content_len = length(content)` | ||
| - Пишет в `out/parquet_#N` и `out/orc_#N` | ||
| - Измеряет размер папок, время записи и чтения (`count()`) и сохраняет в CSV | ||
|
|
||
| ### Spark DataSource / Job | ||
| - Модуль в каталоге `spark/` (JDK 11, Spark 3.5.x) | ||
| - Источник Spark V2 планирует чтение по `/v1/db/{db}/_stats` (без «пробега» страниц) | ||
| - Поддерживаются таймауты и ретраи HTTP | ||
|
|
||
| Полезные эндпоинты: | ||
| - `GET /v1/db/{db}/_all_docs?skip=&limit=&includeDeleted=` — постраничный вывод документов | ||
| - `GET /v1/db/{db}/_seq` — текущая последовательность изменений | ||
| - `GET /v1/db/{db}/_stats` — статистика БД (docsTotal/docsAlive/docsDeleted) | ||
|
|
||
| Ключевые файлы: | ||
| - `spark/peacedb-datasource/src/main/java/io/peacedb/spark/PeacedbDataSource.java` | ||
| - `spark/peacedb-datasource/src/main/java/io/peacedb/spark/read/*` | ||
| - `spark/peacedb-job/src/main/java/io/peacedb/job/PeacedbToColumnar.java` | ||
| - `tools/plot_peacedb_columnar.py` | ||
|
|
||
| ### Опции коннектора | ||
| - `baseUrl` (по умолчанию `http://localhost:5000`) | ||
| - `db` (по умолчанию `news`) | ||
| - `outDir` - папка с результатами | ||
| - `pageSize` (по умолчанию `100`) | ||
| - `includeDeleted` (по умолчанию `false`) | ||
| - `maxRows` — ограничение количества возвращаемых строк на стороне источника (используется в бенчмарке) | ||
| - `connectTimeoutMs` / `readTimeoutMs` — таймауты HTTP | ||
| - `retries`, `retryBackoffMs` - перезапуски | ||
|
|
||
| ### Сборка и запуск | ||
| Установить Java, Spark, winutils | ||
|
|
||
| Задать переменные окружения JAVA_HOME, HADOOP_HOME, SPARK_HOME | ||
|
|
||
| ```bash | ||
| cd spark | ||
| mvn -q -DskipTests package | ||
|
|
||
| # Пример запуска (N=1/10/100/1000/10000/100000, warm‑up в одном прогоне) | ||
| spark-submit --class io.peacedb.job.PeacedbToColumnar --master local[*] peacedb-job/target/peacedb-job-*.jar --baseUrl http://localhost:5000 --db news --outDir ./out --pageSize 200 --connectTimeoutMs 10000 --readTimeoutMs 60000 --retries 3 --retryBackoffMs 500 | ||
|
|
||
| # Построение графиков | ||
| python tools/plot_peacedb_columnar.py spark/out/metrics.csv --out spark/out/plot.png | ||
| ``` | ||
|
|
||
| Примечание для Windows: при ошибке `NativeIO$Windows.access0` установить `winutils.exe` с dll для Hadoop 3.3.x и задать `HADOOP_HOME`/`PATH` (см. winutils выше). Для локальной ФС в коде/submit включены безопасные настройки (pure‑Java путь). | ||
|
|
||
|
|
||
| ### Методика измерений | ||
| - Для каждого N в `[1, 10, 100, 1000, 10000, 100000]` читаем `maxRows=N`, считаем признаки, парсим `data_json` в колонки и: | ||
| 1) Выполняем тёплый прогон (кэш + микро‑запись/чтение) для прогрева JIT/кодеков/коммит‑протокола | ||
| 2) Измеряем запись и считывание Parquet и ORC (миллисекунды) | ||
| - Результаты накапливаются в `out/metrics.csv` c колонками: `n,format,bytes,write_ms,read_ms,rows` | ||
|
|
||
| ### Результаты (пример, с тёплого прогона) | ||
|
|
||
|  | ||
|
|
||
| [Таблица (CSV)](tools/docs/SaDCA-lab2-spark-orc-parquet/metrics.csv) | ||
|
|
||
| Наблюдения: | ||
| - Размеры у Parquet и ORC близки (после парсинга `data_json` в колонки). ORC слегка компактнее на этих данных. | ||
| - Время записи: у Parquet и ORC соизмеримо на N до 10^4, на 10^5 ORC медленнее; начальные точки (1) могут отличаться из‑за недостаточного прогрева (cold start). | ||
| - Время чтения: ORC немного быстрее, Parquet догоняет. | ||
|
|
||
| Графики: `spark/out/plot.png` (лог‑ось X). | ||
|
|
||
| ### Решенные проблемы | ||
| - Не хранить вложенные поля как «сырой JSON» — парсить в типизированные колонки (даёт компрессию и pushdown/column pruning). | ||
| - Разогревать пайплайн перед замерами (JIT/кодеки/коммиттер), иначе первый пункт искажен. | ||
| - На Windows учесть нюансы Hadoop Native/`winutils`. | ||
|
|
||
| ### Ограничения и улучшения | ||
| - Сейчас данные можно загружать только "пакетами" (batch-only). В будущем можно добавить режим микробатчей или потоковой обработки (stream), используя поле `_seq` и watermark. | ||
| - На данный момент фильтрация поддерживается только на стороне Spark. Можно улучшить, чтобы фильтры Spark автоматически переводились в запросы к API (`/v1/db/{db}/_find/*`), чтобы уменьшить объем передаваемых данных. | ||
| - Структура данных (`data`) может меняться со временем. Чтобы не "ломать" обработку при изменении формата, стоит использовать функции вроде `from_json` с гибкой (нежесткой) схемой и автоматическим определением структуры (`schema_of_json` или автоинференс). | ||
|
|
||
| ### Выводы | ||
| - Колоночные форматы выигрывают при типизации полей. Для новостного датасета состоящего преимущественно из текста, а не чисел ORC незначительно компактнее, времена записи/чтения для Parquet и ORC близки. | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # JAVA | ||
|
|
||
| # Compiled class file | ||
| *.class | ||
|
|
||
| # Log file | ||
| *.log | ||
|
|
||
| # BlueJ files | ||
| *.ctxt | ||
|
|
||
| # Mobile Tools for Java (J2ME) | ||
| .mtj.tmp/ | ||
|
|
||
| # Package Files # | ||
| *.jar | ||
| *.war | ||
| *.nar | ||
| *.ear | ||
| *.zip | ||
| *.tar.gz | ||
| *.rar | ||
|
|
||
| # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml | ||
| hs_err_pid* | ||
| replay_pid* | ||
|
|
||
|
|
||
| # SPARK | ||
|
|
||
| #*# | ||
| *.#* | ||
| *.iml | ||
| *.ipr | ||
| *.iws | ||
| *.pyc | ||
| *.pyo | ||
| *.swp | ||
| *~ | ||
| .DS_Store | ||
| .bsp/ | ||
| .cache | ||
| .classpath | ||
| .ensime | ||
| .ensime_cache/ | ||
| .ensime_lucene | ||
| .generated-mima* | ||
| .idea/ | ||
| .idea_modules/ | ||
| .project | ||
| .pydevproject | ||
| .scala_dependencies | ||
| .settings | ||
| /lib/ | ||
| R-unit-tests.log | ||
| R/unit-tests.out | ||
| R/cran-check.out | ||
| R/pkg/vignettes/sparkr-vignettes.html | ||
| R/pkg/tests/fulltests/Rplots.pdf | ||
| build/*.jar | ||
| build/apache-maven* | ||
| build/scala* | ||
| build/zinc* | ||
| cache | ||
| checkpoint | ||
| conf/*.cmd | ||
| conf/*.conf | ||
| conf/*.properties | ||
| conf/*.sh | ||
| conf/*.xml | ||
| conf/java-opts | ||
| conf/slaves | ||
| dependency-reduced-pom.xml | ||
| derby.log | ||
| dev/create-release/*final | ||
| dev/create-release/*txt | ||
| dev/pr-deps/ | ||
| dist/ | ||
| docs/_site/ | ||
| docs/api | ||
| sql/docs | ||
| sql/site | ||
| lib_managed/ | ||
| lint-r-report.log | ||
| log/ | ||
| logs/ | ||
| out/ | ||
| project/boot/ | ||
| project/build/target/ | ||
| project/plugins/lib_managed/ | ||
| project/plugins/project/build.properties | ||
| project/plugins/src_managed/ | ||
| project/plugins/target/ | ||
| python/lib/pyspark.zip | ||
| python/.eggs/ | ||
| python/deps | ||
| python/docs/_site/ | ||
| python/docs/source/reference/api/ | ||
| python/test_coverage/coverage_data | ||
| python/test_coverage/htmlcov | ||
| python/pyspark/python | ||
| .mypy_cache/ | ||
| reports/ | ||
| scalastyle-on-compile.generated.xml | ||
| scalastyle-output.xml | ||
| scalastyle.txt | ||
| spark-*-bin-*.tgz | ||
| spark-tests.log | ||
| src_managed/ | ||
| streaming-tests.log | ||
| target/ | ||
| unit-tests.log | ||
| work/ | ||
| docs/.jekyll-metadata | ||
| docs/.jekyll-cache | ||
| # For Hive | ||
| TempStatsStore/ | ||
| metastore/ | ||
| metastore_db/ | ||
| sql/hive-thriftserver/test_warehouses | ||
| warehouse/ | ||
| spark-warehouse/ | ||
| # For R session data | ||
| .RData | ||
| .RHistory | ||
| .Rhistory | ||
| *.Rproj | ||
| *.Rproj.* | ||
| .Rproj.user | ||
| # For SBT | ||
| .jvmopts | ||
|
|
||
|
|
||
| out*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| ## PeaceDB Spark DataSource (Java) and Job | ||
|
|
||
| Build requires JDK 11+, Maven, Spark 3.5.1. PeaceDatabase Web API must run at `http://localhost:5000`. | ||
|
|
||
| Data source features: | ||
| - Plans partitions using fast `/v1/db/{db}/_stats` (no page probing for large datasets) | ||
| - Configurable timeouts and automatic HTTP retries | ||
|
|
||
| ### Build | ||
|
|
||
| ``` | ||
| mvn -q -DskipTests package | ||
| ``` | ||
|
|
||
| Artifacts: | ||
| - `peacedb-datasource/target/peacedb-datasource-*.jar` | ||
| - `peacedb-job/target/peacedb-job-*.jar` | ||
|
|
||
| ### Run job | ||
|
|
||
| ``` | ||
| spark-submit \ | ||
| --class io.peacedb.job.PeacedbToColumnar \ | ||
| --master local[*] \ | ||
| peacedb-job/target/peacedb-job-*.jar \ | ||
| --baseUrl http://localhost:5000 \ | ||
| --db news \ | ||
| --outDir ./out \ | ||
| --pageSize 200 \ | ||
| --connectTimeoutMs 10000 \ | ||
| --readTimeoutMs 60000 \ | ||
| --retries 3 \ | ||
| --retryBackoffMs 500 | ||
| ``` | ||
|
|
||
| Outputs: `out/parquet_*`, `out/orc_*`, and `out/metrics.csv` with size and timing. | ||
|
|
||
| Connector options (Spark.read.format("peacedb")): | ||
| - `baseUrl` (default `http://localhost:5000`) | ||
| - `db` (default `news`) | ||
| - `pageSize` (default `100`) | ||
| - `includeDeleted` (default `false`) | ||
| - `maxRows` (for benchmarking) | ||
| - `connectTimeoutMs` / `readTimeoutMs` | ||
| - `retries` / `retryBackoffMs` | ||
|
|
||
|
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.