Skip to content
Search

Last updated

Read and write Parquet files in PHP

Let's say the data team asks us for the orders as a Parquet file. Until now they got a CSV file every night: a million orders, 62Mb.

We've never written a Parquet file in PHP, and fputcsv won't help us this time.

The file

First we need orders to work with, so let's generate the CSV file we already send. Set $rows to 1_000_000 to get the 62Mb version.

<?php

declare(strict_types=1);

$rows = 1_000;
$file = fopen(__DIR__ . '/orders.csv', 'w');

fputcsv($file, ['id', 'email', 'country', 'amount', 'created_at'], escape: '');

for ($id = 1; $id <= $rows; $id++) {
    fputcsv($file, [
        $id,
        "customer{$id}@example.com",
        ['PL', 'US', 'DE', 'FR', 'GB'][$id % 5],
        number_format(($id % 1000) / 10, 2, '.', ''),
        gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60),
    ], escape: '');
}

fclose($file);

echo "orders.csv: {$rows} rows\n";
orders.csv: 1000 rows

Write a Parquet file in PHP

PHP has no function that writes Parquet, so we need a library. flow-php/parquet is written in PHP, there is nothing to compile. It needs PHP 8.3 or newer.

composer require flow-php/parquet

A CSV file is text, and every value in it is a string. A Parquet file knows the type of every column, so the first thing we write is the schema.

<?php

declare(strict_types=1);

use Flow\Parquet\{Option, Options, Writer};
use Flow\Parquet\ParquetFile\{Compressions, Encodings, Schema};
use Flow\Parquet\ParquetFile\Schema\FlatColumn;

require __DIR__ . '/vendor/autoload.php';

$parquet = __DIR__ . '/orders.parquet';

if (file_exists($parquet)) {
    unlink($parquet);
}

$options = Options::default()
    ->set(Option::ROW_GROUP_MAXIMUM_ROWS_COUNT, 100_000)
    ->set(Option::COLUMNS_ENCODINGS, [
        'id' => Encodings::DELTA_BINARY_PACKED,
        'email' => Encodings::DELTA_BYTE_ARRAY,
        'created_at' => Encodings::DELTA_BINARY_PACKED,
    ]);

$writer = new Writer(Compressions::GZIP, $options);
$writer->open($parquet, Schema::with(
    FlatColumn::int64('id'),
    FlatColumn::string('email'),
    FlatColumn::string('country'),
    FlatColumn::double('amount'),
    FlatColumn::dateTime('created_at'),
));

$csv = fopen(__DIR__ . '/orders.csv', 'r');
$header = fgetcsv($csv, escape: '');
$batch = [];
$rows = 0;

while (($row = fgetcsv($csv, escape: '')) !== false) {
    $order = array_combine($header, $row);

    $batch[] = [
        'id' => (int) $order['id'],
        'email' => $order['email'],
        'country' => $order['country'],
        'amount' => (float) $order['amount'],
        'created_at' => new DateTimeImmutable($order['created_at'], new DateTimeZone('UTC')),
    ];
    $rows++;

    if (count($batch) === 10_000) {
        $writer->writeBatch($batch);
        $batch = [];
    }
}

if ($batch !== []) {
    $writer->writeBatch($batch);
}

$writer->close();
fclose($csv);

echo "orders.parquet: {$rows} rows\n";
orders.parquet: 1000 rows

The schema is strict. amount is a double, so we cast it to a float, and created_at is a DateTimeImmutable, not a string. A value of the wrong type ends with Column "amount" is not float, and nothing gets written.

We write ten thousand orders at a time, so the script never holds the whole file in memory.

Which encoding to use for a Parquet column

A Parquet file stores every column on its own, so every column can be stored in the way that fits its values. That's the encoding, and it matters more than the compression.

  • id and created_at grow from one order to the next. DELTA_BINARY_PACKED stores only the difference between two values.
  • email starts with the same letters in every order. DELTA_BYTE_ARRAY stores only the part that differs from the email before.
  • country and amount repeat. We leave them alone, because a column without an encoding gets a dictionary: every value is stored once.

A row group is a part of the file that the writer builds in memory and then puts on the disk. With ROW_GROUP_MAXIMUM_ROWS_COUNT we close it after a hundred thousand orders. The writer needs less memory, and a reader can skip whole groups.

Which compression to use for a Parquet file

Compression is a part of the Parquet format. The writer compresses every page of every column, and every Parquet reader knows how to read it back. It is the first argument of the Writer. We used gzip, because it works in every PHP.

PHP 8.3, a million orders:

File Size
CSV 62Mb
Parquet, no compression 15Mb
Parquet, Snappy 2.8Mb
Parquet, gzip 2.2Mb
Parquet, zstd 2.2Mb

The encodings alone make the file four times smaller than the CSV file, before any compression. With gzip it's 28 times smaller.

A CSV file has nothing like that. We can gzip it, but then it's an archive: nothing reads one column of it, and nothing finds a row without unpacking it from the start. The Parquet file stays a Parquet file. The next two scripts read the compressed file directly.

Our orders are kind to these encodings: the ids and the dates grow by the same step, and every email comes from an id. Real orders will give a bigger file. Check it on your own data before you promise a number to anybody.

Without a compression argument the Writer uses Snappy, the fastest one to read and write. zstd needs the zstd extension:

$writer = new Writer(Compressions::ZSTD, $options);

Read a Parquet file in PHP

The data team got their file. Now let's read it back and count the revenue per country.

<?php

declare(strict_types=1);

use Flow\Parquet\Reader;

use function Flow\Parquet\DSL\parquet_query;

require __DIR__ . '/vendor/autoload.php';

$file = (new Reader())->read(__DIR__ . '/orders.parquet');
$revenue = [];

foreach ($file->values(parquet_query()->select('country', 'amount')) as $order) {
    $revenue[$order['country']] = ($revenue[$order['country']] ?? 0.0) + $order['amount'];
}

arsort($revenue);

foreach ($revenue as $country => $total) {
    printf("%s %.2f\n", $country, $total);
}
GB 10030.00
FR 10010.00
DE 9990.00
US 9970.00
PL 9950.00

parquet_query with select reads two columns out of five. The ids, the emails and the dates stay on the disk. amount comes back as a float, there is nothing to cast.

Find rows in a Parquet file without reading all of it

Customer support asks for the last three orders. In a CSV file that means reading a million rows to print three.

<?php

declare(strict_types=1);

use Flow\Parquet\Reader;

use function Flow\Parquet\DSL\{parquet_column, parquet_query};

require __DIR__ . '/vendor/autoload.php';

$file = (new Reader())->read(__DIR__ . '/orders.parquet');

$query = parquet_query()
    ->select('id', 'email', 'amount', 'created_at')
    ->where(parquet_column('id')->greaterThan($file->metadata()->rowsNumber() - 3));

foreach ($file->values($query) as $order) {
    printf(
        "%d %s %.2f %s\n",
        $order['id'],
        $order['email'],
        $order['amount'],
        $order['created_at']->format('Y-m-d H:i'),
    );
}
998 customer998@example.com 99.80 2023-11-15 14:51
999 customer999@example.com 99.90 2023-11-15 14:52
1000 customer1000@example.com 0.00 2023-11-15 14:53

A Parquet file keeps the smallest and the biggest value of every column for each row group, and for each page inside it. The reader checks them first, and it skips every row group and every page that can't hold an id we asked for.

Our ids grow with the file, and that's the best case. When the values of a column are in random order, every page can hold a match. Then the reader has to look into all of them.

created_at comes back as a DateTimeImmutable, the same thing we wrote.

Check what is inside a Parquet file

Sooner or later somebody sends a Parquet file to us, and we can't open it in a text editor.

<?php

declare(strict_types=1);

use Flow\Parquet\Reader;

require __DIR__ . '/vendor/autoload.php';

$file = (new Reader())->read(__DIR__ . '/orders.parquet');

printf("rows: %d\n", $file->metadata()->rowsNumber());

foreach ($file->schema()->columnsFlat() as $column) {
    printf("%-10s %s\n", $column->name(), $column->logicalType()?->name() ?? $column->type()->name);
}
rows: 1000
id         INT64
email      STRING
country    STRING
amount     DOUBLE
created_at TIMESTAMP

The number of rows and the schema sit at the end of the file. This script takes the same time for a thousand orders and for a million.

The same thing with Flow

Flow needs PHP 8.3 or newer.

composer require flow-php/etl flow-php/etl-adapter-csv flow-php/etl-adapter-parquet
<?php

declare(strict_types=1);

use Flow\Parquet\{Option, Options};
use Flow\Parquet\ParquetFile\{Compressions, Encodings};

use function Flow\ETL\Adapter\CSV\from_csv;
use function Flow\ETL\Adapter\Parquet\{from_parquet, to_parquet};
use function Flow\ETL\DSL\{data_frame, overwrite, ref, sum, to_output};

require __DIR__ . '/vendor/autoload.php';

$options = Options::default()
    ->set(Option::ROW_GROUP_MAXIMUM_ROWS_COUNT, 100_000)
    ->set(Option::COLUMNS_ENCODINGS, [
        'id' => Encodings::DELTA_BINARY_PACKED,
        'email' => Encodings::DELTA_BYTE_ARRAY,
        'created_at' => Encodings::DELTA_BINARY_PACKED,
    ]);

data_frame()
    ->read(from_csv(__DIR__ . '/orders.csv'))
    ->write(to_parquet(__DIR__ . '/orders-flow.parquet', $options, Compressions::GZIP)->saveMode(overwrite()))
    ->run();

data_frame()
    ->read(from_parquet(__DIR__ . '/orders-flow.parquet'))
    ->groupBy([ref('country')])
    ->aggregate(sum(ref('amount')))
    ->sortBy(ref('amount_sum')->desc())
    ->write(to_output(truncate: false))
    ->run();
+---------+--------------+
| country |   amount_sum |
+---------+--------------+
|      GB | 10030.000000 |
|      FR | 10010.000000 |
|      DE |  9990.000000 |
|      US |  9970.000000 |
|      PL |  9950.000000 |
+---------+--------------+
5 rows

from_csv detects the type of every column, and to_parquet builds the Parquet schema from them, so we don't write one. The options are the same object the Writer took. The second pipeline is the revenue report from the beginning, this time with from_parquet.

How fast is Parquet in PHP

PHP 8.3, memory_limit=128M, a million orders, the 2.2Mb Parquet file from above:

Task Code Peak memory Time
Write the file flow-php/parquet 18Mb 9.5s
Write the file flow-php/parquet with the arrow extension 12Mb 2.3s
Revenue per country flow-php/parquet 6Mb 1.8s
Revenue per country flow-php/parquet with the arrow extension 6Mb 0.3s
Last three orders fgetcsv loop over the CSV file 2Mb 1.1s
Last three orders flow-php/parquet 6Mb 0.03s
Last three orders flow-php/parquet with the arrow extension 6Mb 0.02s

To find three orders, the fgetcsv loop reads a million rows. The Parquet reader skips almost all of them, and it's 36 times faster.

arrow is an optional PHP extension. The scripts stay the same, without a single change.

To check it on your machine, add this line at the end of any of the scripts above:

printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024);

Where to go from here

The row format that Parquet replaces is in read a large CSV file in PHP. Parquet files often live in a bucket: see read a large file from S3.

Found a typo or an outdated section? Edit this guide on GitHub

scroll back to top