forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_parquet.pyx
More file actions
1791 lines (1490 loc) · 57.2 KB
/
Copy path_parquet.pyx
File metadata and controls
1791 lines (1490 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# cython: profile=False
# distutils: language = c++
import io
from textwrap import indent
import warnings
import numpy as np
from libcpp cimport nullptr
from cython.operator cimport dereference as deref
from pyarrow.includes.common cimport *
from pyarrow.includes.libarrow cimport *
from pyarrow.lib cimport (_Weakrefable, Buffer, Array, Schema,
check_status,
MemoryPool, maybe_unbox_memory_pool,
Table, NativeFile,
pyarrow_wrap_chunked_array,
pyarrow_wrap_schema,
pyarrow_wrap_table,
pyarrow_wrap_buffer,
pyarrow_wrap_batch,
pyarrow_wrap_scalar,
NativeFile, get_reader, get_writer,
string_to_timeunit)
from pyarrow.lib import (ArrowException, NativeFile, BufferOutputStream,
_stringify_path, _datetime_from_int,
tobytes, frombytes)
cimport cpython as cp
cdef class Statistics(_Weakrefable):
"""Statistics for a single column in a single row group."""
def __cinit__(self):
pass
def __repr__(self):
return """{}
has_min_max: {}
min: {}
max: {}
null_count: {}
distinct_count: {}
num_values: {}
physical_type: {}
logical_type: {}
converted_type (legacy): {}""".format(object.__repr__(self),
self.has_min_max,
self.min,
self.max,
self.null_count,
self.distinct_count,
self.num_values,
self.physical_type,
str(self.logical_type),
self.converted_type)
def to_dict(self):
"""
Get dictionary represenation of statistics.
Returns
-------
dict
Dictionary with a key for each attribute of this class.
"""
d = dict(
has_min_max=self.has_min_max,
min=self.min,
max=self.max,
null_count=self.null_count,
distinct_count=self.distinct_count,
num_values=self.num_values,
physical_type=self.physical_type
)
return d
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def equals(self, Statistics other):
"""
Return whether the two column statistics objects are equal.
Parameters
----------
other : Statistics
Statistics to compare against.
Returns
-------
are_equal : bool
"""
return self.statistics.get().Equals(deref(other.statistics.get()))
@property
def has_min_max(self):
"""Whether min and max are present (bool)."""
return self.statistics.get().HasMinMax()
@property
def has_null_count(self):
"""Whether null count is present (bool)."""
return self.statistics.get().HasNullCount()
@property
def has_distinct_count(self):
"""Whether distinct count is preset (bool)."""
return self.statistics.get().HasDistinctCount()
@property
def min_raw(self):
"""Min value as physical type (bool, int, float, or bytes)."""
if self.has_min_max:
return _cast_statistic_raw_min(self.statistics.get())
else:
return None
@property
def max_raw(self):
"""Max value as physical type (bool, int, float, or bytes)."""
if self.has_min_max:
return _cast_statistic_raw_max(self.statistics.get())
else:
return None
@property
def min(self):
"""
Min value as logical type.
Returned as the Python equivalent of logical type, such as datetime.date
for dates and decimal.Decimal for decimals.
"""
if self.has_min_max:
min_scalar, _ = _cast_statistics(self.statistics.get())
return min_scalar.as_py()
else:
return None
@property
def max(self):
"""
Max value as logical type.
Returned as the Python equivalent of logical type, such as datetime.date
for dates and decimal.Decimal for decimals.
"""
if self.has_min_max:
_, max_scalar = _cast_statistics(self.statistics.get())
return max_scalar.as_py()
else:
return None
@property
def null_count(self):
"""Number of null values in chunk (int)."""
return self.statistics.get().null_count()
@property
def distinct_count(self):
"""
Distinct number of values in chunk (int).
If this is not set, will return 0.
"""
# This seems to be zero if not set. See: ARROW-11793
return self.statistics.get().distinct_count()
@property
def num_values(self):
"""Number of non-null values (int)."""
return self.statistics.get().num_values()
@property
def physical_type(self):
"""Physical type of column (str)."""
raw_physical_type = self.statistics.get().physical_type()
return physical_type_name_from_enum(raw_physical_type)
@property
def logical_type(self):
"""Logical type of column (:class:`ParquetLogicalType`)."""
return wrap_logical_type(self.statistics.get().descr().logical_type())
@property
def converted_type(self):
"""Legacy converted type (str or None)."""
raw_converted_type = self.statistics.get().descr().converted_type()
return converted_type_name_from_enum(raw_converted_type)
cdef class ParquetLogicalType(_Weakrefable):
"""Logical type of parquet type."""
cdef:
shared_ptr[const CParquetLogicalType] type
def __cinit__(self):
pass
cdef init(self, const shared_ptr[const CParquetLogicalType]& type):
self.type = type
def __repr__(self):
return "{}\n {}".format(object.__repr__(self), str(self))
def __str__(self):
return frombytes(self.type.get().ToString(), safe=True)
def to_json(self):
"""
Get a JSON string containing type and type parameters.
Returns
-------
json : str
JSON representation of type, with at least a field called 'Type'
which contains the type name. If the type is parameterized, such
as a decimal with scale and precision, will contain those as fields
as well.
"""
return frombytes(self.type.get().ToJSON())
@property
def type(self):
"""Name of the logical type (str)."""
return logical_type_name_from_enum(self.type.get().type())
cdef wrap_logical_type(const shared_ptr[const CParquetLogicalType]& type):
cdef ParquetLogicalType out = ParquetLogicalType()
out.init(type)
return out
cdef _cast_statistic_raw_min(CStatistics* statistics):
cdef ParquetType physical_type = statistics.physical_type()
cdef uint32_t type_length = statistics.descr().type_length()
if physical_type == ParquetType_BOOLEAN:
return (<CBoolStatistics*> statistics).min()
elif physical_type == ParquetType_INT32:
return (<CInt32Statistics*> statistics).min()
elif physical_type == ParquetType_INT64:
return (<CInt64Statistics*> statistics).min()
elif physical_type == ParquetType_FLOAT:
return (<CFloatStatistics*> statistics).min()
elif physical_type == ParquetType_DOUBLE:
return (<CDoubleStatistics*> statistics).min()
elif physical_type == ParquetType_BYTE_ARRAY:
return _box_byte_array((<CByteArrayStatistics*> statistics).min())
elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY:
return _box_flba((<CFLBAStatistics*> statistics).min(), type_length)
cdef _cast_statistic_raw_max(CStatistics* statistics):
cdef ParquetType physical_type = statistics.physical_type()
cdef uint32_t type_length = statistics.descr().type_length()
if physical_type == ParquetType_BOOLEAN:
return (<CBoolStatistics*> statistics).max()
elif physical_type == ParquetType_INT32:
return (<CInt32Statistics*> statistics).max()
elif physical_type == ParquetType_INT64:
return (<CInt64Statistics*> statistics).max()
elif physical_type == ParquetType_FLOAT:
return (<CFloatStatistics*> statistics).max()
elif physical_type == ParquetType_DOUBLE:
return (<CDoubleStatistics*> statistics).max()
elif physical_type == ParquetType_BYTE_ARRAY:
return _box_byte_array((<CByteArrayStatistics*> statistics).max())
elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY:
return _box_flba((<CFLBAStatistics*> statistics).max(), type_length)
cdef _cast_statistics(CStatistics* statistics):
cdef:
shared_ptr[CScalar] c_min
shared_ptr[CScalar] c_max
check_status(StatisticsAsScalars(statistics[0], &c_min, &c_max))
return (pyarrow_wrap_scalar(c_min), pyarrow_wrap_scalar(c_max))
cdef _box_byte_array(ParquetByteArray val):
return cp.PyBytes_FromStringAndSize(<char*> val.ptr, <Py_ssize_t> val.len)
cdef _box_flba(ParquetFLBA val, uint32_t len):
return cp.PyBytes_FromStringAndSize(<char*> val.ptr, <Py_ssize_t> len)
cdef class ColumnChunkMetaData(_Weakrefable):
"""Column metadata for a single row group."""
def __cinit__(self):
pass
def __repr__(self):
statistics = indent(repr(self.statistics), 4 * ' ')
return """{0}
file_offset: {1}
file_path: {2}
physical_type: {3}
num_values: {4}
path_in_schema: {5}
is_stats_set: {6}
statistics:
{7}
compression: {8}
encodings: {9}
has_dictionary_page: {10}
dictionary_page_offset: {11}
data_page_offset: {12}
total_compressed_size: {13}
total_uncompressed_size: {14}""".format(object.__repr__(self),
self.file_offset,
self.file_path,
self.physical_type,
self.num_values,
self.path_in_schema,
self.is_stats_set,
statistics,
self.compression,
self.encodings,
self.has_dictionary_page,
self.dictionary_page_offset,
self.data_page_offset,
self.total_compressed_size,
self.total_uncompressed_size)
def to_dict(self):
"""
Get dictionary represenation of the column chunk metadata.
Returns
-------
dict
Dictionary with a key for each attribute of this class.
"""
statistics = self.statistics.to_dict() if self.is_stats_set else None
d = dict(
file_offset=self.file_offset,
file_path=self.file_path,
physical_type=self.physical_type,
num_values=self.num_values,
path_in_schema=self.path_in_schema,
is_stats_set=self.is_stats_set,
statistics=statistics,
compression=self.compression,
encodings=self.encodings,
has_dictionary_page=self.has_dictionary_page,
dictionary_page_offset=self.dictionary_page_offset,
data_page_offset=self.data_page_offset,
total_compressed_size=self.total_compressed_size,
total_uncompressed_size=self.total_uncompressed_size
)
return d
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def equals(self, ColumnChunkMetaData other):
"""
Return whether the two column chunk metadata objects are equal.
Parameters
----------
other : ColumnChunkMetaData
Metadata to compare against.
Returns
-------
are_equal : bool
"""
return self.metadata.Equals(deref(other.metadata))
@property
def file_offset(self):
"""Offset into file where column chunk is located (int)."""
return self.metadata.file_offset()
@property
def file_path(self):
"""Optional file path if set (str or None)."""
return frombytes(self.metadata.file_path())
@property
def physical_type(self):
"""Physical type of column (str)."""
return physical_type_name_from_enum(self.metadata.type())
@property
def num_values(self):
"""Total number of values (int)."""
return self.metadata.num_values()
@property
def path_in_schema(self):
"""Nested path to field, separated by periods (str)."""
path = self.metadata.path_in_schema().get().ToDotString()
return frombytes(path)
@property
def is_stats_set(self):
"""Whether or not statistics are present in metadata (bool)."""
return self.metadata.is_stats_set()
@property
def statistics(self):
"""Statistics for column chunk (:class:`Statistics`)."""
if not self.metadata.is_stats_set():
return None
statistics = Statistics()
statistics.init(self.metadata.statistics(), self)
return statistics
@property
def compression(self):
"""
Type of compression used for column (str).
One of 'UNCOMPRESSED', 'SNAPPY', 'GZIP', 'LZO', 'BROTLI', 'LZ4', 'ZSTD',
or 'UNKNOWN'.
"""
return compression_name_from_enum(self.metadata.compression())
@property
def encodings(self):
"""
Encodings used for column (tuple of str).
One of 'PLAIN', 'BIT_PACKED', 'RLE', 'BYTE_STREAM_SPLIT', 'DELTA_BINARY_PACKED',
'DELTA_BYTE_ARRAY'.
"""
return tuple(map(encoding_name_from_enum, self.metadata.encodings()))
@property
def has_dictionary_page(self):
"""Whether there is dictionary data present in the column chunk (bool)."""
return bool(self.metadata.has_dictionary_page())
@property
def dictionary_page_offset(self):
"""Offset of dictionary page reglative to column chunk offset (int)."""
if self.has_dictionary_page:
return self.metadata.dictionary_page_offset()
else:
return None
@property
def data_page_offset(self):
"""Offset of data page reglative to column chunk offset (int)."""
return self.metadata.data_page_offset()
@property
def has_index_page(self):
"""Not yet supported."""
raise NotImplementedError('not supported in parquet-cpp')
@property
def index_page_offset(self):
"""Not yet supported."""
raise NotImplementedError("parquet-cpp doesn't return valid values")
@property
def total_compressed_size(self):
"""Compresssed size in bytes (int)."""
return self.metadata.total_compressed_size()
@property
def total_uncompressed_size(self):
"""Uncompressed size in bytes (int)."""
return self.metadata.total_uncompressed_size()
cdef class RowGroupMetaData(_Weakrefable):
"""Metadata for a single row group."""
def __cinit__(self, FileMetaData parent, int index):
if index < 0 or index >= parent.num_row_groups:
raise IndexError('{0} out of bounds'.format(index))
self.up_metadata = parent._metadata.RowGroup(index)
self.metadata = self.up_metadata.get()
self.parent = parent
self.index = index
def __reduce__(self):
return RowGroupMetaData, (self.parent, self.index)
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def equals(self, RowGroupMetaData other):
"""
Return whether the two row group metadata objects are equal.
Parameters
----------
other : RowGroupMetaData
Metadata to compare against.
Returns
-------
are_equal : bool
"""
return self.metadata.Equals(deref(other.metadata))
def column(self, int i):
"""
Get column metadata at given index.
Parameters
----------
i : int
Index of column to get metadata for.
Returns
-------
ColumnChunkMetaData
Metadata for column within this chunk.
"""
if i < 0 or i >= self.num_columns:
raise IndexError('{0} out of bounds'.format(i))
chunk = ColumnChunkMetaData()
chunk.init(self, i)
return chunk
def __repr__(self):
return """{0}
num_columns: {1}
num_rows: {2}
total_byte_size: {3}""".format(object.__repr__(self),
self.num_columns,
self.num_rows,
self.total_byte_size)
def to_dict(self):
"""
Get dictionary represenation of the row group metadata.
Returns
-------
dict
Dictionary with a key for each attribute of this class.
"""
columns = []
d = dict(
num_columns=self.num_columns,
num_rows=self.num_rows,
total_byte_size=self.total_byte_size,
columns=columns,
)
for i in range(self.num_columns):
columns.append(self.column(i).to_dict())
return d
@property
def num_columns(self):
"""Number of columns in this row group (int)."""
return self.metadata.num_columns()
@property
def num_rows(self):
"""Number of rows in this row group (int)."""
return self.metadata.num_rows()
@property
def total_byte_size(self):
"""Total byte size of all the uncompressed column data in this row group (int)."""
return self.metadata.total_byte_size()
def _reconstruct_filemetadata(Buffer serialized):
cdef:
FileMetaData metadata = FileMetaData.__new__(FileMetaData)
CBuffer *buffer = serialized.buffer.get()
uint32_t metadata_len = <uint32_t>buffer.size()
metadata.init(CFileMetaData_Make(buffer.data(), &metadata_len))
return metadata
cdef class FileMetaData(_Weakrefable):
"""Parquet metadata for a single file."""
def __cinit__(self):
pass
def __reduce__(self):
cdef:
NativeFile sink = BufferOutputStream()
COutputStream* c_sink = sink.get_output_stream().get()
with nogil:
self._metadata.WriteTo(c_sink)
cdef Buffer buffer = sink.getvalue()
return _reconstruct_filemetadata, (buffer,)
def __repr__(self):
return """{0}
created_by: {1}
num_columns: {2}
num_rows: {3}
num_row_groups: {4}
format_version: {5}
serialized_size: {6}""".format(object.__repr__(self),
self.created_by, self.num_columns,
self.num_rows, self.num_row_groups,
self.format_version,
self.serialized_size)
def to_dict(self):
"""
Get dictionary represenation of the file metadata.
Returns
-------
dict
Dictionary with a key for each attribute of this class.
"""
row_groups = []
d = dict(
created_by=self.created_by,
num_columns=self.num_columns,
num_rows=self.num_rows,
num_row_groups=self.num_row_groups,
row_groups=row_groups,
format_version=self.format_version,
serialized_size=self.serialized_size
)
for i in range(self.num_row_groups):
row_groups.append(self.row_group(i).to_dict())
return d
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def equals(self, FileMetaData other not None):
"""
Return whether the two file metadata objects are equal.
Parameters
----------
other : FileMetaData
Metadata to compare against.
Returns
-------
are_equal : bool
"""
return self._metadata.Equals(deref(other._metadata))
@property
def schema(self):
"""Schema of the file (:class:`ParquetSchema`)."""
if self._schema is None:
self._schema = ParquetSchema(self)
return self._schema
@property
def serialized_size(self):
"""Size of the original thrift encoded metadata footer (int)."""
return self._metadata.size()
@property
def num_columns(self):
"""Number of columns in file (int)."""
return self._metadata.num_columns()
@property
def num_rows(self):
"""Total number of rows in file (int)."""
return self._metadata.num_rows()
@property
def num_row_groups(self):
"""Number of row groups in file (int)."""
return self._metadata.num_row_groups()
@property
def format_version(self):
"""
Parquet format version used in file (str, such as '1.0', '2.4').
If version is missing or unparsable, will default to assuming '2.4'.
"""
cdef ParquetVersion version = self._metadata.version()
if version == ParquetVersion_V1:
return '1.0'
elif version == ParquetVersion_V2_0:
return 'pseudo-2.0'
elif version == ParquetVersion_V2_4:
return '2.4'
elif version == ParquetVersion_V2_6:
return '2.6'
else:
warnings.warn('Unrecognized file version, assuming 2.4: {}'
.format(version))
return '2.4'
@property
def created_by(self):
"""
String describing source of the parquet file (str).
This typically includes library name and version number. For example, Arrow 7.0's
writer returns 'parquet-cpp-arrow version 7.0.0'.
"""
return frombytes(self._metadata.created_by())
@property
def metadata(self):
"""Additional metadata as key value pairs (dict[bytes, bytes])."""
cdef:
unordered_map[c_string, c_string] metadata
const CKeyValueMetadata* underlying_metadata
underlying_metadata = self._metadata.key_value_metadata().get()
if underlying_metadata != NULL:
underlying_metadata.ToUnorderedMap(&metadata)
return metadata
else:
return None
def row_group(self, int i):
"""
Get metadata for row group at index i.
Parameters
----------
i : int
Row group index to get.
Returns
-------
row_group_metadata : RowGroupMetaData
"""
return RowGroupMetaData(self, i)
def set_file_path(self, path):
"""
Set ColumnChunk file paths to the given value.
This method modifies the ``file_path`` field of each ColumnChunk
in the FileMetaData to be a particular value.
Parameters
----------
path : str
The file path to set on all ColumnChunks.
"""
cdef:
c_string c_path = tobytes(path)
self._metadata.set_file_path(c_path)
def append_row_groups(self, FileMetaData other):
"""
Append row groups from other FileMetaData object.
Parameters
----------
other : FileMetaData
Other metadata to append row groups from.
"""
cdef shared_ptr[CFileMetaData] c_metadata
c_metadata = other.sp_metadata
self._metadata.AppendRowGroups(deref(c_metadata))
def write_metadata_file(self, where):
"""
Write the metadata to a metadata-only Parquet file.
Parameters
----------
where : path or file-like object
Where to write the metadata. Should be a writable path on
the local filesystem, or a writable file-like object.
"""
cdef:
shared_ptr[COutputStream] sink
c_string c_where
try:
where = _stringify_path(where)
except TypeError:
get_writer(where, &sink)
else:
c_where = tobytes(where)
with nogil:
sink = GetResultValue(FileOutputStream.Open(c_where))
with nogil:
check_status(
WriteMetaDataFile(deref(self._metadata), sink.get()))
cdef class ParquetSchema(_Weakrefable):
"""A Parquet schema."""
def __cinit__(self, FileMetaData container):
self.parent = container
self.schema = container._metadata.schema()
def __repr__(self):
return "{0}\n{1}".format(
object.__repr__(self),
frombytes(self.schema.ToString(), safe=True))
def __reduce__(self):
return ParquetSchema, (self.parent,)
def __len__(self):
return self.schema.num_columns()
def __getitem__(self, i):
return self.column(i)
@property
def names(self):
"""Name of each field (list of str)."""
return [self[i].name for i in range(len(self))]
def to_arrow_schema(self):
"""
Convert Parquet schema to effective Arrow schema.
Returns
-------
schema : Schema
"""
cdef shared_ptr[CSchema] sp_arrow_schema
with nogil:
check_status(FromParquetSchema(
self.schema, default_arrow_reader_properties(),
self.parent._metadata.key_value_metadata(),
&sp_arrow_schema))
return pyarrow_wrap_schema(sp_arrow_schema)
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def equals(self, ParquetSchema other):
"""
Return whether the two schemas are equal.
Parameters
----------
other : ParquetSchema
Schema to compare against.
Returns
-------
are_equal : bool
"""
return self.schema.Equals(deref(other.schema))
def column(self, i):
"""
Return the schema for a single column.
Parameters
----------
i : int
Index of column in schema.
Returns
-------
column_schema : ColumnSchema
"""
if i < 0 or i >= len(self):
raise IndexError('{0} out of bounds'.format(i))
return ColumnSchema(self, i)
cdef class ColumnSchema(_Weakrefable):
"""Schema for a single column."""
cdef:
int index
ParquetSchema parent
const ColumnDescriptor* descr
def __cinit__(self, ParquetSchema schema, int index):
self.parent = schema
self.index = index # for pickling support
self.descr = schema.schema.Column(index)
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return NotImplemented
def __reduce__(self):
return ColumnSchema, (self.parent, self.index)
def equals(self, ColumnSchema other):
"""
Return whether the two column schemas are equal.
Parameters
----------
other : ColumnSchema
Schema to compare against.
Returns
-------
are_equal : bool
"""
return self.descr.Equals(deref(other.descr))
def __repr__(self):
physical_type = self.physical_type
converted_type = self.converted_type
if converted_type == 'DECIMAL':
converted_type = 'DECIMAL({0}, {1})'.format(self.precision,
self.scale)
elif physical_type == 'FIXED_LEN_BYTE_ARRAY':
converted_type = ('FIXED_LEN_BYTE_ARRAY(length={0})'
.format(self.length))
return """<ParquetColumnSchema>
name: {0}
path: {1}
max_definition_level: {2}
max_repetition_level: {3}
physical_type: {4}
logical_type: {5}
converted_type (legacy): {6}""".format(self.name, self.path,
self.max_definition_level,
self.max_repetition_level,
physical_type,
str(self.logical_type),
converted_type)
@property
def name(self):
"""Name of field (str)."""
return frombytes(self.descr.name())
@property
def path(self):
"""Nested path to field, separated by periods (str)."""
return frombytes(self.descr.path().get().ToDotString())
@property
def max_definition_level(self):
"""Maximum definition level (int)."""
return self.descr.max_definition_level()
@property
def max_repetition_level(self):
"""Maximum repetition level (int)."""
return self.descr.max_repetition_level()
@property
def physical_type(self):
"""Name of physical type (str)."""
return physical_type_name_from_enum(self.descr.physical_type())
@property
def logical_type(self):
"""Logical type of column (:class:`ParquetLogicalType`)."""