Apache Arrow record batches

Install the optional Arrow adapter when records need to flow into a columnar analytics pipeline. The core package does not depend on Apache Arrow.

To read a Columnar JSON document or a NetCDF CDL dataset directly into Arrow batches, install the extension for that input format.

dotnet add package PocketCsvReader.Arrow

Configure a stable PocketCsvReader schema, import the adapter namespace, and enumerate the batches:

using PocketCsvReader.Arrow;
using PocketCsvReader.Configuration;

var csv = new CsvReaderBuilder()
    .WithDialect(dialect => dialect
        .WithDelimiter(',')
        .WithHeader())
    .WithSchema(schema => schema.Named()
        .WithField<int>("customer_id")
        .WithField<string>("country")
        .WithNumberField<decimal>("revenue"))
    .Build();

foreach (var batch in csv.ToArrowBatches("sales.csv", batchSize: 32_768))
{
    using (batch)
    {
        // Send the RecordBatch to an Arrow-aware analytics engine.
    }
}

ToArrowBatchesAsync provides genuine asynchronous input reads and accepts a cancellation token:

await foreach (var batch in csv.ToArrowBatchesAsync(
    "sales.csv",
    batchSize: 32_768,
    cancellationToken: cancellationToken))
{
    using (batch)
    {
        await ConsumeAsync(batch, cancellationToken);
    }
}

The APIs are extensions on the shared flat-file reader abstraction, so the same calls work with CSV, JSON, NDJSON, fixed-width, key-value, and web-log readers. Each batch contains at most batchSize rows; the final partial batch is emitted, while empty input emits no batch. Memory use is bounded by one batch plus the parser buffers.

Each RecordBatch owns Arrow buffers and must be disposed by the consumer. Enumeration disposes the PocketCsvReader data reader. Stream overloads follow that reader’s ownership behavior and therefore dispose the supplied stream when enumeration ends, fails, or is cancelled.

Read the schema before requesting a batch

ToArrowStream and ToArrowStreamAsync accept a filename or an input stream and return an Apache Arrow IArrowArrayStream. The adapter can read the first data row during opening to determine the output schema and retains it for the first batch. A header-only CSV with a configured schema exposes its typed columns and returns no batches.

using var arrow = await csv.ToArrowStreamAsync(
    "sales.csv", batchSize: 32_768, cancellationToken: cancellationToken);

foreach (var field in arrow.Schema.FieldsList)
    Console.WriteLine(field.Name);

while (await arrow.ReadNextRecordBatchAsync(cancellationToken) is { } batch)
{
    using (batch)
        await ConsumeAsync(batch, cancellationToken);
}

Disposing the Arrow stream releases the data reader, including when you stop before the end of the input. The caller owns each returned batch.

Batches from multiple CSV inputs

Pass filenames, streams, or lazy stream factories to the multi-input ToArrowBatches or ToArrowBatchesAsync overloads. These overloads use the CSV reader’s batch configuration and yield CsvArrowBatch instances. Dispose each instance after consuming its Batch. Its Sources collection contains the source input and record number for every Arrow row, with parser positions when tracking is enabled.

var csv = new CsvReaderBuilder()
    .WithDialect(d => d.WithHeader())
    .WithSchema(schema => schema.Named()
        .WithField<int>("customer_id")
        .WithField<string>("country"))
    .WithProjection("customer_id", "country")
    .WithParallelFiles(4)
    .Build();

await foreach (var result in csv.ToArrowBatchesAsync(
    new[] { "part-1.csv", "part-2.csv" }, cancellationToken: cancellationToken))
{
    using var owned = result;
    Console.WriteLine($"Read {owned.Batch.Length} rows from {owned.Sources.Length} source records.");
}

When CSV workers build Arrow batches

The example builds Arrow batches on CSV workers with the default Arrow options. Worker conversion applies to the multi-input batch overloads when the reader has more than one file worker and a typed schema with a stable output layout. Ordered and unordered delivery both qualify.

  • When each file has its own header, select columns by name and use a named schema. This keeps the projected types stable even if the source column order changes.
  • For headerless inputs, select columns by ordinal. When all inputs share the first file’s header, the projection can select by name or ordinal.
  • To read all columns without a projection, configure a shared header with .WithHeaderRepeat(false). Worker conversion applies when the first row considered for delivery fills that header. If the header is unavailable or that row is short, conversion stays on the consumer.
  • For all-column reads with repeated headers or headerless files, the consumer builds the batches. An explicit projection can enable worker conversion for those inputs.
  • Generated row numbers, global skip or take, filters, computed fields, custom parsers and custom string-pooling callbacks use consumer conversion.

Call .WithoutBuildBatchesOnWorkers() on the CsvReaderBuilder to use consumer conversion for that reader. This takes precedence over ArrowOptions.BuildBatchesOnWorkers, even when the option is explicitly set to true. For a single conversion, pass new ArrowOptions { BuildBatchesOnWorkers = false }. Both opt-outs preserve the configured CSV file parallelism and input ordering.

Type mappings

PocketCsvReader runtime type Apache Arrow type
bool Boolean
signed and unsigned integer primitives matching-width signed or unsigned integer
float, double Float, Double
decimal Decimal128(38, 18)
string, char, Guid String
byte[] Binary
DateOnly Date32
DateTime, DateTimeOffset UTC Timestamp in microseconds
TimeOnly Time64 in nanoseconds

Null input values are appended to Arrow validity bitmaps. Unsupported and untyped object fields fail before the first batch is emitted with an error identifying the field. Configure those fields with a supported runtime type or a custom PocketCsvReader parser.


Buffering, allocations, and benchmarks
Chrononuensis temporal types

Related Docs