High-performance Go package to read and write Parquet files
High-performance Go package to read and write Parquet files
Parquet has been established as a powerful solution to represent columnar data on persistent storage mediums, achieving levels of compression and query performance that enable managing data sets at scales that reach the petabytes. In addition, having intensive data applications sharing a common format creates opportunities for interoperation in our tool kits, providing greater leverage and value to engineers maintaining and operating those systems.
The creation and evolution of large scale data management systems, combined with realtime expectations come with challenging maintenance and performance requirements, that existing solutions to use parquet with Go were not addressing.
The parquet-go/parquet-go package was designed and developed to respond to those
challenges, offering high level APIs to read and write parquet files, while
keeping a low compute and memory footprint in order to be used in environments
where data volumes and cost constraints require software to achieve high levels
of efficiency.
Columnar storage allows Parquet to store data more efficiently than, say, using JSON or Protobuf. For more information, refer to the Parquet Format Specification.
The package is distributed as a standard Go module that programs can take a dependency on and install with the following command:
go get github.com/parquet-go/parquet-goGo 1.22 or later is required to use the package.
The package is currently released as a pre-v1 version, which gives maintainers the freedom to break backward compatibility to help improve the APIs as we learn which initial design decisions would need to be revisited to better support the use cases that the library solves for. These occurrences are expected to be rare in frequency and documentation will be produce to guide users on how to adapt their programs to breaking changes.
The following sections describe how to use APIs exposed by the library, highlighting the use cases with code examples to demonstrate how they are used in practice.
When using Go structs to define the schema of parquet files, struct fields may
include a parquet tag to configure properties of the parquet column such as
its name, compression, encoding, and logical type. The first value in the tag
sets the column name, and additional comma-separated values set options.
type Record struct {
ID int64 `parquet:"id,delta"`
Name string `parquet:"name,dict,zstd"`
Timestamp int64 `parquet:"timestamp,timestamp(microsecond)"`
Score float64 `parquet:"score,split"`
Tags []string `parquet:"tags,list"`
Optional *string `parquet:"optional,optional"`
}Map keys and values can be configured with the parquet-key and parquet-value
tags, and list elements with the parquet-element tag.
For the full reference of supported tags, type constraints, and examples, see
the SchemaOf
documentation.
The library supports the Parquet VARIANT logical type for storing semi-structured data (JSON-like values) in a columnar format.
The simplest way to use variants is with the variant struct tag, which
automatically marshals and unmarshals Go values to/from the variant binary
format:
type Event struct {
ID int64 `parquet:"id"`
Data any `parquet:"data,variant"`
}
writer := parquet.NewGenericWriter[Event](output)
writer.Write([]Event{
{ID: 1, Data: "hello"},
{ID: 2, Data: int32(42)},
{ID: 3, Data: map[string]any{"key": "value"}},
})
writer.Close()For shredded variants (which store typed columns alongside the raw value for
faster queries), build a schema with parquet.ShreddedVariant():
shreddedType, err := parquet.ShreddedVariant(parquet.String())
schema := parquet.NewSchema("Record", parquet.Group{
"data": shreddedType,
})
writer := parquet.NewGenericWriter[Record](output, schema)For low-level access to raw variant bytes, use a struct with Metadata and
Value []byte fields:
type VariantData struct {
Metadata []byte `parquet:"metadata"`
Value []byte `parquet:"value"`
}For more examples, see the ExampleVariant and ExampleShreddedVariant
functions in example_variant_test.go.
A parquet file is a collection of rows sharing the same schema, arranged in columns to support faster scan operations on subsets of the data set.
For simple use cases, the parquet.WriteFile[T] function allows the creation
of parquet files on the file system from a slice of Go values representing the
rows to write to the file.
type RowType struct { FirstName, LastName string }
if err := parquet.WriteFile("file.parquet", []RowType{
{FirstName: "Bob"},
{FirstName: "Alice"},
}); err != nil {
...
}The parquet.GenericWriter[T] type denormalizes rows into columns, then encodes
the columns into a parquet file, generating row groups, column chunks, and pages
based on configurable heuristics.
type RowType struct { FirstName, LastName string }
writer := parquet.NewGenericWriter[RowType](output)
_, err := writer.Write([]RowType{
...
})
if err != nil {
...
}
// Closing the writer is necessary to flush buffers and write the file footer.
if err := writer.Close(); err != nil {
...
}Explicit declaration of the parquet schema on a writer is useful when the
application needs to ensure that data written to a file adheres to a predefined
schema, which may differ from the schema derived from the writer's type
parameter. The parquet.Schema type is a in-memory representation of the schema
of parquet rows, translated from the type of Go values, and can be used for this
purpose.
schema := parquet.SchemaOf(new(RowType))
writer := parquet.NewGenericWriter[any](output, schema)
...For simple use cases where the data set fits in memory and the program will
read most rows of the file, the parquet.ReadFile[T] function returns a slice
of Go values representing the rows read from the file.
type RowType struct { FirstName, LastName string }
rows, err := parquet.ReadFile[RowType]("file.parquet")
if err != nil {
...
}
for _, c := range rows {
fmt.Printf("%+v\n", c)
}The expected schema of rows can be explicitly declared when the reader is constructed, which is useful to ensure that the program receives rows matching an specific format; for example, when dealing with files from remote storage sources that applications cannot trust to have used an expected schema.
Configuring the schema of a reader is done by passing a parquet.Schema
instance as argument when constructing a reader. When the schema is declared,
conversion rules implemented by the package are applied to ensure that rows
read by the application match the desired format (see Evolving Parquet Schemas).
schema := parquet.SchemaOf(new(RowType))
reader := parquet.NewReader(file, schema)
...Sometimes, lower-level APIs can be useful to leverage the columnar layout of
parquet files. The parquet.File type is intended to provide such features to
Go applications, by exposing APIs to iterate over the various parts of a
parquet file.
f, err := parquet.OpenFile(file, size)
if err != nil {
...
}
for _, rowGroup := range f.RowGroups() {
for _, columnChunk := range rowGroup.ColumnChunks() {
...
}
}Parquet files embed all the metadata necessary to interpret their content, including a description of the schema of the tables represented by the rows and columns they contain.
Parquet files are also immutable; once written, there is not mechanism for updating a file. If their contents need to be changed, rows must be read, modified, and written to a new file.
Because applications evolve, the schema written to parquet files also tend to evolve over time. Those requirements creating challenges when applications need to operate on parquet files with heterogenous schemas: algorithms that expect new columns to exist may have issues dealing with rows that come from files with mismatching schema versions.
To help build applications that can handle evolving schemas, parquet-go/parquet-go
implements conversion rules that create views of row groups to translate between
schema versions.
The parquet.Convert function is the low-level routine constructing conversion
rules from a source to a target schema. The function is used to build converted
views of parquet.RowReader or parquet.RowGroup, for example:
type RowTypeV1 struct { ID int64; FirstName string }
type RowTypeV2 struct { ID int64; FirstName, LastName string }
source := parquet.SchemaOf(RowTypeV1{})
target := parquet.SchemaOf(RowTypeV2{})
conversion, err := parquet.Convert(target, source)
if err != nil {
...
}
targetRowGroup := parquet.ConvertRowGroup(sourceRowGroup, conversion)
...Conversion rules are automatically applied by the parquet.CopyRows function
when the reader and writers passed to the function also implement the
parquet.RowReaderWithSchema and parquet.RowWriterWithSchema interfaces.
The copy determines whether the reader and writer schemas can be converted from
one to the other, and automatically applies the conversion rules to facilitate
the translation between schemas.
At this time, conversion rules only supports adding or removing columns from the schemas, there are no type conversions performed, nor ways to rename columns, etc... More advanced conversion rules may be added in the future.
The parquet.GenericWriter[T] type is optimized for minimal memory usage,
keeping the order of rows unchanged and flushing pages as soon as they are filled.
Parquet supports expressing columns by which rows are sorted through the declaration of sorting columns on row groups. Sorting row groups requires buffering all rows before ordering and writing them to a parquet file.
To help with those use cases, the parquet-go/parquet-go package exposes the
parquet.GenericBuffer[T] type which acts as a buffer of rows and implements
sort.Interface to allow applications to sort rows prior to writing them
to a file.
The columns that rows are ordered by are configured when creating
parquet.GenericBuffer[T] instances using the parquet.SortingColumns function
to construct row group options configuring the buffer. The type of parquet
columns defines how values are compared, see Parquet Logical Types
for details.
When written to a file, the buffer is materialized into a single row group with
the declared sorting columns. After being written, buffers can be reused by
calling their Reset method.
The following example shows how to use a parquet.GenericBuffer[T] to order rows
written to a parquet file:
…Parquet files are often used as part of the underlying engine for data processing or storage layers, in which cases merging multiple row groups into one that contains more rows can be a useful operation to improve query performance; for example,
No open issues yet, or sync has not completed.