diff --git a/docs/source/python/api/formats.rst b/docs/source/python/api/formats.rst index 57a5e824fab..0b9a34ad134 100644 --- a/docs/source/python/api/formats.rst +++ b/docs/source/python/api/formats.rst @@ -82,6 +82,8 @@ Parquet Files ParquetDataset ParquetFile ParquetWriter + WriterProperties + ArrowWriterProperties filters_to_expression read_table read_metadata diff --git a/python/pyarrow/_parquet.pxd b/python/pyarrow/_parquet.pxd index 9cdba15638e..01fdae23987 100644 --- a/python/pyarrow/_parquet.pxd +++ b/python/pyarrow/_parquet.pxd @@ -38,7 +38,7 @@ cdef class FileEncryptionProperties: cdef inline shared_ptr[CFileEncryptionProperties] unwrap(self): return self.properties -cdef shared_ptr[WriterProperties] _create_writer_properties( +cdef shared_ptr[CWriterProperties] _create_writer_properties( use_dictionary=*, compression=*, version=*, @@ -62,7 +62,7 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( ) except * -cdef shared_ptr[ArrowWriterProperties] _create_arrow_writer_properties( +cdef shared_ptr[CArrowWriterProperties] _create_arrow_writer_properties( use_deprecated_int96_timestamps=*, coerce_timestamps=*, allow_truncated_timestamps=*, diff --git a/python/pyarrow/_parquet.pyx b/python/pyarrow/_parquet.pyx index 2e56c608d91..9c39a5a228d 100644 --- a/python/pyarrow/_parquet.pyx +++ b/python/pyarrow/_parquet.pyx @@ -39,7 +39,7 @@ from pyarrow.lib cimport (_Weakrefable, Buffer, Schema, pyarrow_wrap_batch, pyarrow_wrap_scalar, NativeFile, get_reader, get_writer, - string_to_timeunit) + string_to_timeunit, timeunit_to_string) from pyarrow.lib import (ArrowException, NativeFile, BufferOutputStream, ListType, LargeListType, @@ -2004,7 +2004,7 @@ cdef vector[CSortingColumn] _convert_sorting_columns(sorting_columns) except *: return c_sorting_columns cdef void _set_bloom_opts_for_column( - WriterProperties.Builder* props, + CWriterProperties.Builder* props, column, column_bloom_opts) except *: """Set Bloom filter options for a single column""" @@ -2045,7 +2045,7 @@ cdef void _set_bloom_opts_for_column( cdef void _set_bloom_filter_opts( - WriterProperties.Builder* props, + CWriterProperties.Builder* props, bloom_filter_options) except *: """Set Bloom filter options for all columns""" if bloom_filter_options is not None: @@ -2058,7 +2058,7 @@ cdef void _set_bloom_filter_opts( raise TypeError("'bloom_filter_options' must be a dictionary") -cdef shared_ptr[WriterProperties] _create_writer_properties( +cdef shared_ptr[CWriterProperties] _create_writer_properties( use_dictionary=None, compression=None, version=None, @@ -2082,8 +2082,8 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( """General writer properties""" cdef: - shared_ptr[WriterProperties] properties - WriterProperties.Builder props + shared_ptr[CWriterProperties] properties + CWriterProperties.Builder props CdcOptions cdc_options double savings double default_min_savings = 0.01 @@ -2294,7 +2294,7 @@ cdef shared_ptr[WriterProperties] _create_writer_properties( return properties -cdef shared_ptr[ArrowWriterProperties] _create_arrow_writer_properties( +cdef shared_ptr[CArrowWriterProperties] _create_arrow_writer_properties( use_deprecated_int96_timestamps=False, coerce_timestamps=None, allow_truncated_timestamps=False, @@ -2304,8 +2304,8 @@ cdef shared_ptr[ArrowWriterProperties] _create_arrow_writer_properties( write_time_adjusted_to_utc=False) except *: """Arrow writer properties""" cdef: - shared_ptr[ArrowWriterProperties] arrow_properties - ArrowWriterProperties.Builder arrow_props + shared_ptr[CArrowWriterProperties] arrow_properties + CArrowWriterProperties.Builder arrow_props # Store the original Arrow schema so things like dictionary types can # be automatically reconstructed @@ -2360,8 +2360,8 @@ cdef _name_to_index_map(Schema arrow_schema): cdef: shared_ptr[CSchema] sp_arrow_schema shared_ptr[SchemaDescriptor] sp_parquet_schema - shared_ptr[WriterProperties] props = _create_writer_properties() - shared_ptr[ArrowWriterProperties] arrow_props = _create_arrow_writer_properties( + shared_ptr[CWriterProperties] props = _create_writer_properties() + shared_ptr[CArrowWriterProperties] arrow_props = _create_arrow_writer_properties( use_deprecated_int96_timestamps=False, coerce_timestamps=None, allow_truncated_timestamps=False, @@ -2385,11 +2385,173 @@ cdef _name_to_index_map(Schema arrow_schema): return out +cdef class WriterProperties(_Weakrefable): + """Parquet file and column settings for a ParquetWriter. + + Obtain this read-only object from a ParquetWriter. + """ + + cdef shared_ptr[CWriterProperties] _properties + + def __init__(self): + raise TypeError("WriterProperties must be obtained from a ParquetWriter") + + @property + def dictionary_pagesize_limit(self): + """Maximum dictionary page size in bytes.""" + return self._properties.get().dictionary_pagesize_limit() + + @property + def write_batch_size(self): + """Number of values written per batch.""" + return self._properties.get().write_batch_size() + + @property + def max_row_group_length(self): + """Maximum number of rows per row group.""" + return self._properties.get().max_row_group_length() + + @property + def data_pagesize(self): + """Target data page size in bytes.""" + return self._properties.get().data_pagesize() + + @property + def max_rows_per_page(self): + """Maximum number of rows per data page.""" + return self._properties.get().max_rows_per_page() + + @property + def min_compression_savings(self): + """Minimum fractional savings required for compression.""" + return self._properties.get().min_compression_savings() + + @property + def store_decimal_as_integer(self): + """Whether eligible decimals are stored as integers.""" + return self._properties.get().store_decimal_as_integer() + + @property + def page_checksum_enabled(self): + """Whether page checksums are enabled.""" + return self._properties.get().page_checksum_enabled() + + @property + def content_defined_chunking_enabled(self): + """Whether content-defined chunking is enabled.""" + return self._properties.get().content_defined_chunking_enabled() + + @property + def version(self): + """Parquet logical type version.""" + return { + ParquetVersion_V1: '1.0', + ParquetVersion_V2_4: '2.4', + ParquetVersion_V2_6: '2.6', + }[self._properties.get().version()] + + @property + def data_page_version(self): + """Parquet data page format version.""" + if self._properties.get().data_page_version() == ParquetDataPageVersion_V1: + return '1.0' + return '2.0' + + def compression(self, column_path): + """Compression codec for a dot-separated Parquet column path.""" + cdef shared_ptr[ColumnPath] path = ColumnPath.FromDotString( + tobytes(column_path)) + return compression_name_from_enum(self._properties.get().compression(path)) + + def compression_level(self, column_path): + """Compression level for a column path, or None for the codec default.""" + cdef shared_ptr[ColumnPath] path = ColumnPath.FromDotString( + tobytes(column_path)) + cdef int level = self._properties.get().compression_level(path) + if level == CCodec.UseDefaultCompressionLevel(): + return None + return level + + def dictionary_enabled(self, column_path): + """Whether dictionary encoding is enabled for a dot-separated Parquet column path.""" + cdef shared_ptr[ColumnPath] path = ColumnPath.FromDotString( + tobytes(column_path)) + return self._properties.get().dictionary_enabled(path) + + def statistics_enabled(self, column_path): + """Whether statistics are enabled for a dot-separated Parquet column path.""" + cdef shared_ptr[ColumnPath] path = ColumnPath.FromDotString( + tobytes(column_path)) + return self._properties.get().statistics_enabled(path) + + def page_index_enabled(self, column_path): + """Whether the page index is enabled for a dot-separated Parquet column path.""" + cdef shared_ptr[ColumnPath] path = ColumnPath.FromDotString( + tobytes(column_path)) + return self._properties.get().page_index_enabled(path) + + +cdef class ArrowWriterProperties(_Weakrefable): + """Arrow-to-Parquet conversion settings for a ParquetWriter. + + Obtain this read-only object from a ParquetWriter. + """ + + cdef shared_ptr[CArrowWriterProperties] _properties + + def __init__(self): + raise TypeError("ArrowWriterProperties must be obtained from a ParquetWriter") + + @property + def support_deprecated_int96_timestamps(self): + """Whether timestamps are written as INT96.""" + return self._properties.get().support_deprecated_int96_timestamps() + + @property + def truncated_timestamps_allowed(self): + """Whether timestamp truncation is allowed.""" + return self._properties.get().truncated_timestamps_allowed() + + @property + def store_schema(self): + """Whether the Arrow schema is stored in file metadata.""" + return self._properties.get().store_schema() + + @property + def compliant_nested_types(self): + """Whether compliant nested types are used.""" + return self._properties.get().compliant_nested_types() + + @property + def write_time_adjusted_to_utc(self): + """Whether TIME columns are marked as adjusted to UTC.""" + return self._properties.get().write_time_adjusted_to_utc() + + @property + def use_threads(self): + """Whether columns may be written in parallel.""" + return self._properties.get().use_threads() + + @property + def coerce_timestamps(self): + """Target timestamp unit, or None if coercion is disabled.""" + if self._properties.get().coerce_timestamps_enabled(): + return timeunit_to_string(self._properties.get().coerce_timestamps_unit()) + return None + + @property + def engine_version(self): + """Arrow writer engine version.""" + return {V1: 'V1', V2: 'V2'}[self._properties.get().engine_version()] + + cdef class ParquetWriter(_Weakrefable): cdef: unique_ptr[FileWriter] writer shared_ptr[COutputStream] sink bint own_sink + shared_ptr[CWriterProperties] _properties + shared_ptr[CArrowWriterProperties] _arrow_properties def __cinit__(self, where, Schema schema not None, use_dictionary=None, compression=None, version=None, @@ -2419,8 +2581,8 @@ cdef class ParquetWriter(_Weakrefable): bloom_filter_options=None, min_compression_savings=0.01): cdef: - shared_ptr[WriterProperties] properties - shared_ptr[ArrowWriterProperties] arrow_properties + shared_ptr[CWriterProperties] properties + shared_ptr[CArrowWriterProperties] arrow_properties c_string c_where CMemoryPool* pool @@ -2473,6 +2635,22 @@ cdef class ParquetWriter(_Weakrefable): FileWriter.Open(deref(schema.schema), pool, self.sink, properties, arrow_properties))) + self._properties = properties + self._arrow_properties = arrow_properties + + @property + def properties(self): + cdef WriterProperties result = WriterProperties.__new__(WriterProperties) + result._properties = self._properties + return result + + @property + def arrow_properties(self): + cdef ArrowWriterProperties result = ArrowWriterProperties.__new__( + ArrowWriterProperties) + result._properties = self._arrow_properties + return result + def close(self): with nogil: check_status(self.writer.get().Close()) diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 25a9aa8da6f..24c3b7e8728 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -3077,6 +3077,9 @@ cdef extern from "arrow/util/compression.h" namespace "arrow" nogil: CCompressionType_BZ2" arrow::Compression::BZ2" cdef cppclass CCodec" arrow::util::Codec": + @staticmethod + int UseDefaultCompressionLevel() + @staticmethod CResult[unique_ptr[CCodec]] Create(CCompressionType codec) diff --git a/python/pyarrow/includes/libarrow_dataset_parquet.pxd b/python/pyarrow/includes/libarrow_dataset_parquet.pxd index 8f4917f6c0c..2e3780913d2 100644 --- a/python/pyarrow/includes/libarrow_dataset_parquet.pxd +++ b/python/pyarrow/includes/libarrow_dataset_parquet.pxd @@ -43,8 +43,8 @@ cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil: cdef cppclass CParquetFileWriteOptions \ "arrow::dataset::ParquetFileWriteOptions"(CFileWriteOptions): - shared_ptr[WriterProperties] writer_properties - shared_ptr[ArrowWriterProperties] arrow_writer_properties + shared_ptr[CWriterProperties] writer_properties + shared_ptr[CArrowWriterProperties] arrow_writer_properties shared_ptr[CParquetEncryptionConfig] parquet_encryption_config cdef cppclass CParquetFileFragment "arrow::dataset::ParquetFileFragment"( diff --git a/python/pyarrow/includes/libparquet.pxd b/python/pyarrow/includes/libparquet.pxd index a7ad239feac..a5525e59b60 100644 --- a/python/pyarrow/includes/libparquet.pxd +++ b/python/pyarrow/includes/libparquet.pxd @@ -37,6 +37,8 @@ cdef extern from "parquet/api/schema.h" namespace "parquet::schema" nogil: pass cdef cppclass ColumnPath: + @staticmethod + shared_ptr[ColumnPath] FromDotString(const c_string& path) except + c_string ToDotString() vector[c_string] ToDotVector() @@ -482,7 +484,24 @@ cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: int64_t max_chunk_size int norm_level - cdef cppclass WriterProperties: + cdef cppclass CWriterProperties "parquet::WriterProperties": + int64_t dictionary_pagesize_limit() const + int64_t write_batch_size() const + int64_t max_row_group_length() const + int64_t data_pagesize() const + int64_t max_rows_per_page() const + double min_compression_savings() const + c_bool store_decimal_as_integer() const + c_bool page_checksum_enabled() const + c_bool content_defined_chunking_enabled() const + ParquetVersion version() const + ParquetDataPageVersion data_page_version() const + ParquetCompression compression(const shared_ptr[ColumnPath]& path) const + int compression_level(const shared_ptr[ColumnPath]& path) const + c_bool dictionary_enabled(const shared_ptr[ColumnPath]& path) const + c_bool statistics_enabled(const shared_ptr[ColumnPath]& path) const + c_bool page_index_enabled(const shared_ptr[ColumnPath]& path) const + cppclass Builder: Builder* data_page_version(ParquetDataPageVersion version) Builder* min_compression_savings(double min_compression_savings) except + @@ -523,9 +542,9 @@ cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: Builder* disable_bloom_filter(const c_string& path) Builder* enable_bloom_filter(const c_string& path, BloomFilterOptions bloom_filter_options) - shared_ptr[WriterProperties] build() + shared_ptr[CWriterProperties] build() - cdef cppclass ArrowWriterProperties: + cdef cppclass CArrowWriterProperties "parquet::ArrowWriterProperties": cppclass Builder: Builder() Builder* disable_deprecated_int96_timestamps() @@ -538,8 +557,17 @@ cdef extern from "parquet/api/writer.h" namespace "parquet" nogil: Builder* disable_compliant_nested_types() Builder* set_engine_version(ArrowWriterEngineVersion version) Builder* set_time_adjusted_to_utc(c_bool adjusted) - shared_ptr[ArrowWriterProperties] build() - c_bool support_deprecated_int96_timestamps() + shared_ptr[CArrowWriterProperties] build() + + c_bool support_deprecated_int96_timestamps() const + c_bool truncated_timestamps_allowed() const + c_bool store_schema() const + c_bool compliant_nested_types() const + c_bool write_time_adjusted_to_utc() const + c_bool use_threads() const + c_bool coerce_timestamps_enabled() const + TimeUnit coerce_timestamps_unit() const + ArrowWriterEngineVersion engine_version() const cdef extern from "parquet/arrow/reader.h" namespace "parquet::arrow" nogil: cdef cppclass FileReader: @@ -600,23 +628,19 @@ cdef extern from "parquet/arrow/schema.h" namespace "parquet::arrow" nogil: CStatus ToParquetSchema( const CSchema* arrow_schema, - const WriterProperties& properties, - const ArrowWriterProperties& arrow_properties, + const CWriterProperties& properties, + const CArrowWriterProperties& arrow_properties, shared_ptr[SchemaDescriptor]* out) cdef extern from "parquet/properties.h" namespace "parquet" nogil: - cdef enum ArrowWriterEngineVersion: + cdef enum ArrowWriterEngineVersion "parquet::ArrowWriterProperties::EngineVersion": V1 "parquet::ArrowWriterProperties::V1", V2 "parquet::ArrowWriterProperties::V2" - cdef cppclass ParquetDataPageVersion: - pass - - cdef ParquetDataPageVersion ParquetDataPageVersion_V1 \ - " parquet::ParquetDataPageVersion::V1" - cdef ParquetDataPageVersion ParquetDataPageVersion_V2 \ - " parquet::ParquetDataPageVersion::V2" + cdef enum ParquetDataPageVersion "parquet::ParquetDataPageVersion": + ParquetDataPageVersion_V1 "parquet::ParquetDataPageVersion::V1" + ParquetDataPageVersion_V2 "parquet::ParquetDataPageVersion::V2" cdef extern from "parquet/arrow/writer.h" namespace "parquet::arrow" nogil: cdef cppclass FileWriter: @@ -624,8 +648,8 @@ cdef extern from "parquet/arrow/writer.h" namespace "parquet::arrow" nogil: @staticmethod CResult[unique_ptr[FileWriter]] Open(const CSchema& schema, CMemoryPool* pool, const shared_ptr[COutputStream]& sink, - const shared_ptr[WriterProperties]& properties, - const shared_ptr[ArrowWriterProperties]& arrow_properties) + const shared_ptr[CWriterProperties]& properties, + const shared_ptr[CArrowWriterProperties]& arrow_properties) CStatus WriteTable(const CTable& table, int64_t chunk_size) CStatus NewRowGroup() diff --git a/python/pyarrow/parquet/core.py b/python/pyarrow/parquet/core.py index 6721eab9a06..1c4afea192a 100644 --- a/python/pyarrow/parquet/core.py +++ b/python/pyarrow/parquet/core.py @@ -43,7 +43,8 @@ ParquetLogicalType, FileEncryptionProperties, FileDecryptionProperties, - SortingColumn) + SortingColumn, WriterProperties, + ArrowWriterProperties) from pyarrow.fs import (LocalFileSystem, FileType, _resolve_filesystem_and_path, _ensure_filesystem) from pyarrow.util import guid, _is_path_like, _stringify_path, _deprecate_api @@ -1163,6 +1164,16 @@ def __init__(self, where, schema, filesystem=None, **options) self.is_open = True + @property + def properties(self): + """Read-only Parquet settings (:class:`WriterProperties`).""" + return self.writer.properties + + @property + def arrow_properties(self): + """Read-only Arrow settings (:class:`ArrowWriterProperties`).""" + return self.writer.arrow_properties + def __del__(self): if getattr(self, 'is_open', False): self.close() @@ -2532,6 +2543,7 @@ def read_schema(where, memory_map=False, decryption_properties=None, __all__ = ( + "ArrowWriterProperties", "ColumnChunkMetaData", "ColumnSchema", "FileDecryptionProperties", @@ -2546,6 +2558,7 @@ def read_schema(where, memory_map=False, decryption_properties=None, "RowGroupMetaData", "SortingColumn", "Statistics", + "WriterProperties", "read_metadata", "read_pandas", "read_schema", diff --git a/python/pyarrow/tests/parquet/test_parquet_writer.py b/python/pyarrow/tests/parquet/test_parquet_writer.py index 264392bae10..0e3ea58081b 100644 --- a/python/pyarrow/tests/parquet/test_parquet_writer.py +++ b/python/pyarrow/tests/parquet/test_parquet_writer.py @@ -41,6 +41,62 @@ pytestmark = pytest.mark.parquet +def test_parquet_writer_properties(): + table = pa.table({"a": [1, 2], "b": [3, 4]}) + sink = pa.BufferOutputStream() + with pq.ParquetWriter( + sink, table.schema, version="2.4", data_page_version="1.0", + compression={"a": "gzip"}, compression_level={"a": 3}, + use_dictionary=["a"], write_statistics=["b"], + write_batch_size=32, write_page_index=True, write_page_checksum=True, + coerce_timestamps="ms", allow_truncated_timestamps=True, + use_compliant_nested_type=False, store_schema=False, + ) as writer: + properties = writer.properties + arrow_properties = writer.arrow_properties + assert isinstance(properties, pq.WriterProperties) + assert isinstance(arrow_properties, pq.ArrowWriterProperties) + assert properties.version == "2.4" + assert properties.data_page_version == "1.0" + assert properties.write_batch_size == 32 + assert properties.compression("a") == "GZIP" + assert properties.compression("b") == "UNCOMPRESSED" + assert properties.compression_level("a") == 3 + assert properties.dictionary_enabled("a") is True + assert properties.dictionary_enabled("b") is False + assert properties.statistics_enabled("a") is False + assert properties.statistics_enabled("b") is True + assert properties.page_index_enabled("a") is True + assert properties.page_checksum_enabled is True + assert arrow_properties.coerce_timestamps == "ms" + assert arrow_properties.truncated_timestamps_allowed is True + assert arrow_properties.compliant_nested_types is False + assert arrow_properties.store_schema is False + with pytest.raises(AttributeError): + properties.write_batch_size = 64 + with pytest.raises(AttributeError): + arrow_properties.store_schema = True + writer.write_table(table) + + assert writer.properties.version == "2.4" + assert writer.arrow_properties.coerce_timestamps == "ms" + del writer + assert properties.write_batch_size == 32 + assert arrow_properties.store_schema is False + assert pq.read_table(sink.getvalue()).equals(table) + + +def test_parquet_writer_default_properties(): + with pq.ParquetWriter(pa.BufferOutputStream(), + pa.schema([("a", pa.int64())])) as writer: + assert writer.properties.version == "2.6" + assert writer.properties.compression("a") == "SNAPPY" + assert writer.properties.compression_level("a") is None + assert writer.arrow_properties.coerce_timestamps is None + assert writer.arrow_properties.engine_version == "V2" + assert writer.arrow_properties.store_schema is True + + @pytest.mark.parametrize("page_version, minimum", [ ("1.0", None), ("1.0", 0.0),