-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
_dataset.pyx
2020 lines (1607 loc) · 66.3 KB
/
_dataset.pyx
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: language_level = 3
"""Dataset is currently unstable. APIs subject to change without notice."""
from cpython.object cimport Py_LT, Py_EQ, Py_GT, Py_LE, Py_NE, Py_GE
from cython.operator cimport dereference as deref
import pyarrow as pa
from pyarrow.lib cimport *
from pyarrow.lib import frombytes, tobytes
from pyarrow.includes.libarrow_dataset cimport *
from pyarrow._fs cimport FileSystem, FileInfo, FileSelector
from pyarrow._csv cimport ParseOptions
from pyarrow._compute cimport CastOptions
from pyarrow.util import _is_path_like, _stringify_path
def _forbid_instantiation(klass, subclasses_instead=True):
msg = '{} is an abstract class thus cannot be initialized.'.format(
klass.__name__
)
if subclasses_instead:
subclasses = [cls.__name__ for cls in klass.__subclasses__]
msg += ' Use one of the subclasses instead: {}'.format(
', '.join(subclasses)
)
raise TypeError(msg)
cdef CFileSource _make_file_source(object file, FileSystem filesystem=None):
cdef:
CFileSource c_source
shared_ptr[CFileSystem] c_filesystem
c_string c_path
shared_ptr[CRandomAccessFile] c_file
shared_ptr[CBuffer] c_buffer
if isinstance(file, Buffer):
c_buffer = pyarrow_unwrap_buffer(file)
c_source = CFileSource(move(c_buffer))
elif _is_path_like(file):
if filesystem is None:
raise ValueError("cannot construct a FileSource from "
"a path without a FileSystem")
c_filesystem = filesystem.unwrap()
c_path = tobytes(_stringify_path(file))
c_source = CFileSource(move(c_path), move(c_filesystem))
elif hasattr(file, 'read'):
# Optimistically hope this is file-like
c_file = get_native_file(file, False).get_random_access_file()
c_source = CFileSource(move(c_file))
else:
raise TypeError("cannot construct a FileSource "
"from " + str(file))
return c_source
cdef class Expression:
cdef:
shared_ptr[CExpression] wrapped
CExpression* expr
def __init__(self):
_forbid_instantiation(self.__class__)
cdef void init(self, const shared_ptr[CExpression]& sp):
self.wrapped = sp
self.expr = sp.get()
@staticmethod
cdef wrap(const shared_ptr[CExpression]& sp):
cdef Expression self = Expression.__new__(Expression)
self.init(sp)
return self
cdef inline shared_ptr[CExpression] unwrap(self):
return self.wrapped
def equals(self, Expression other):
return self.expr.Equals(other.unwrap())
def __str__(self):
return frombytes(self.expr.ToString())
def __repr__(self):
return "<pyarrow.dataset.{0} {1}>".format(
self.__class__.__name__, str(self)
)
@staticmethod
def _deserialize(Buffer buffer not None):
c_buffer = pyarrow_unwrap_buffer(buffer)
c_expr = GetResultValue(CExpression.Deserialize(deref(c_buffer)))
return Expression.wrap(move(c_expr))
def __reduce__(self):
buffer = pyarrow_wrap_buffer(GetResultValue(self.expr.Serialize()))
return Expression._deserialize, (buffer,)
def validate(self, Schema schema not None):
"""Validate this expression for execution against a schema.
This will check that all reference fields are present (fields not in
the schema will be replaced with null) and all subexpressions are
executable. Returns the type to which this expression will evaluate.
Parameters
----------
schema : Schema
Schema to execute the expression on.
Returns
-------
type : DataType
"""
cdef:
shared_ptr[CSchema] sp_schema
CResult[shared_ptr[CDataType]] result
sp_schema = pyarrow_unwrap_schema(schema)
result = self.expr.Validate(deref(sp_schema))
return pyarrow_wrap_data_type(GetResultValue(result))
def assume(self, Expression given):
"""Simplify to an equivalent Expression given assumed constraints."""
return Expression.wrap(self.expr.Assume(given.unwrap()))
def __invert__(self):
return Expression.wrap(CMakeNotExpression(self.unwrap()))
@staticmethod
cdef shared_ptr[CExpression] _expr_or_scalar(object expr) except *:
if isinstance(expr, Expression):
return (<Expression> expr).unwrap()
return (<Expression> Expression._scalar(expr)).unwrap()
def __richcmp__(self, other, int op):
cdef:
shared_ptr[CExpression] c_expr
shared_ptr[CExpression] c_left
shared_ptr[CExpression] c_right
c_left = self.unwrap()
c_right = Expression._expr_or_scalar(other)
if op == Py_EQ:
c_expr = CMakeEqualExpression(move(c_left), move(c_right))
elif op == Py_NE:
c_expr = CMakeNotEqualExpression(move(c_left), move(c_right))
elif op == Py_GT:
c_expr = CMakeGreaterExpression(move(c_left), move(c_right))
elif op == Py_GE:
c_expr = CMakeGreaterEqualExpression(move(c_left), move(c_right))
elif op == Py_LT:
c_expr = CMakeLessExpression(move(c_left), move(c_right))
elif op == Py_LE:
c_expr = CMakeLessEqualExpression(move(c_left), move(c_right))
return Expression.wrap(c_expr)
def __and__(Expression self, other):
c_other = Expression._expr_or_scalar(other)
return Expression.wrap(CMakeAndExpression(self.wrapped,
move(c_other)))
def __or__(Expression self, other):
c_other = Expression._expr_or_scalar(other)
return Expression.wrap(CMakeOrExpression(self.wrapped,
move(c_other)))
def is_valid(self):
"""Checks whether the expression is not-null (valid)"""
return Expression.wrap(self.expr.IsValid().Copy())
def cast(self, type, bint safe=True):
"""Explicitly change the expression's data type"""
cdef CastOptions options
options = CastOptions.safe() if safe else CastOptions.unsafe()
c_type = pyarrow_unwrap_data_type(ensure_type(type))
return Expression.wrap(self.expr.CastTo(c_type,
options.unwrap()).Copy())
def isin(self, values):
"""Checks whether the expression is contained in values"""
if not isinstance(values, pa.Array):
values = pa.array(values)
c_values = pyarrow_unwrap_array(values)
return Expression.wrap(self.expr.In(c_values).Copy())
@staticmethod
def _field(str name not None):
return Expression.wrap(CMakeFieldExpression(tobytes(name)))
@staticmethod
def _scalar(value):
cdef:
Scalar scalar
if isinstance(value, Scalar):
scalar = value
else:
scalar = pa.scalar(value)
return Expression.wrap(
shared_ptr[CExpression](
new CScalarExpression(move(scalar.unwrap()))
)
)
_deserialize = Expression._deserialize
cdef Expression _true = Expression._scalar(True)
cdef class Dataset:
"""
Collection of data fragments and potentially child datasets.
Arrow Datasets allow you to query against data that has been split across
multiple files. This sharding of data may indicate partitioning, which
can accelerate queries that only touch some partitions (files).
"""
cdef:
shared_ptr[CDataset] wrapped
CDataset* dataset
def __init__(self):
_forbid_instantiation(self.__class__)
cdef void init(self, const shared_ptr[CDataset]& sp):
self.wrapped = sp
self.dataset = sp.get()
@staticmethod
cdef wrap(const shared_ptr[CDataset]& sp):
type_name = frombytes(sp.get().type_name())
classes = {
'union': UnionDataset,
'filesystem': FileSystemDataset,
}
class_ = classes.get(type_name, None)
if class_ is None:
raise TypeError(type_name)
cdef Dataset self = class_.__new__(class_)
self.init(sp)
return self
cdef shared_ptr[CDataset] unwrap(self) nogil:
return self.wrapped
@property
def partition_expression(self):
"""
An Expression which evaluates to true for all data viewed by this
Dataset.
"""
cdef shared_ptr[CExpression] expr
expr = self.dataset.partition_expression()
if expr.get() == nullptr:
return None
else:
return Expression.wrap(expr)
def replace_schema(self, Schema schema not None):
"""
Return a copy of this Dataset with a different schema.
The copy will view the same Fragments. If the new schema is not
compatible with the original dataset's schema then an error will
be raised.
"""
cdef shared_ptr[CDataset] copy = GetResultValue(
self.dataset.ReplaceSchema(pyarrow_unwrap_schema(schema)))
return Dataset.wrap(move(copy))
def get_fragments(self, Expression filter=None):
"""Returns an iterator over the fragments in this dataset.
Parameters
----------
filter : Expression, default None
Return fragments matching the optional filter, either using the
partition_expression or internal information like Parquet's
statistics.
Returns
-------
fragments : iterator of Fragment
"""
cdef:
shared_ptr[CExpression] c_filter
CFragmentIterator c_iterator
if filter is None:
c_fragments = self.dataset.GetFragments()
else:
c_filter = _insert_implicit_casts(filter, self.schema)
c_fragments = self.dataset.GetFragments(c_filter)
for maybe_fragment in c_fragments:
yield Fragment.wrap(GetResultValue(move(maybe_fragment)))
def _scanner(self, **kwargs):
return Scanner.from_dataset(self, **kwargs)
def scan(self, **kwargs):
"""Builds a scan operation against the dataset.
It produces a stream of ScanTasks which is meant to be a unit of work
to be dispatched. The tasks are not executed automatically, the user is
responsible to execute and dispatch the individual tasks, so custom
local task scheduling can be implemented.
Parameters
----------
columns : list of str, default None
List of columns to project. Order and duplicates will be preserved.
The columns will be passed down to Datasets and corresponding data
fragments to avoid loading, copying, and deserializing columns
that will not be required further down the compute chain.
By default all of the available columns are projected. Raises
an exception if any of the referenced column names does not exist
in the dataset's Schema.
filter : Expression, default None
Scan will return only the rows matching the filter.
If possible the predicate will be pushed down to exploit the
partition information or internal metadata found in the data
source, e.g. Parquet statistics. Otherwise filters the loaded
RecordBatches before yielding them.
batch_size : int, default 32K
The maximum row count for scanned record batches. If scanned
record batches are overflowing memory then this method can be
called to reduce their size.
use_threads : bool, default True
If enabled, then maximum parallelism will be used determined by
the number of available CPU cores.
memory_pool : MemoryPool, default None
For memory allocations, if required. If not specified, uses the
default pool.
Returns
-------
scan_tasks : iterator of ScanTask
"""
return self._scanner(**kwargs).scan()
def to_batches(self, **kwargs):
"""Read the dataset as materialized record batches.
Builds a scan operation against the dataset and sequentially executes
the ScanTasks as the returned generator gets consumed.
See scan method parameters documentation.
Returns
-------
record_batches : iterator of RecordBatch
"""
return self._scanner(**kwargs).to_batches()
def to_table(self, **kwargs):
"""Read the dataset to an arrow table.
Note that this method reads all the selected data from the dataset
into memory.
See scan method parameters documentation.
Returns
-------
table : Table instance
"""
return self._scanner(**kwargs).to_table()
@property
def schema(self):
"""The common schema of the full Dataset"""
return pyarrow_wrap_schema(self.dataset.schema())
cdef class UnionDataset(Dataset):
"""A Dataset wrapping child datasets.
Children's schemas must agree with the provided schema.
Parameters
----------
schema : Schema
A known schema to conform to.
children : list of Dataset
One or more input children
"""
cdef:
CUnionDataset* union_dataset
def __init__(self, Schema schema not None, children):
cdef:
Dataset child
CDatasetVector c_children
shared_ptr[CUnionDataset] union_dataset
for child in children:
c_children.push_back(child.wrapped)
union_dataset = GetResultValue(CUnionDataset.Make(
pyarrow_unwrap_schema(schema), move(c_children)))
self.init(<shared_ptr[CDataset]> union_dataset)
cdef void init(self, const shared_ptr[CDataset]& sp):
Dataset.init(self, sp)
self.union_dataset = <CUnionDataset*> sp.get()
def __reduce__(self):
return UnionDataset, (self.schema, self.children)
@property
def children(self):
cdef CDatasetVector children = self.union_dataset.children()
return [Dataset.wrap(children[i]) for i in range(children.size())]
cdef class FileSystemDataset(Dataset):
"""A Dataset of file fragments.
A FileSystemDataset is composed of one or more FileFragment.
Parameters
----------
fragments : list[Fragments]
List of fragments to consume.
schema : Schema
The top-level schema of the Dataset.
format : FileFormat
File format of the fragments, currently only ParquetFileFormat,
IpcFileFormat, and CsvFileFormat are supported.
root_partition : Expression, optional
The top-level partition of the DataDataset.
"""
cdef:
CFileSystemDataset* filesystem_dataset
def __init__(self, fragments, Schema schema, FileFormat format,
root_partition=None):
cdef:
FileFragment fragment
vector[shared_ptr[CFileFragment]] c_fragments
CResult[shared_ptr[CDataset]] result
root_partition = root_partition or _true
if not isinstance(root_partition, Expression):
raise TypeError(
"Argument 'root_partition' has incorrect type (expected "
"Epression, got {0})".format(type(root_partition))
)
for fragment in fragments:
c_fragments.push_back(
static_pointer_cast[CFileFragment, CFragment](
fragment.unwrap()))
result = CFileSystemDataset.Make(
pyarrow_unwrap_schema(schema),
(<Expression> root_partition).unwrap(),
(<FileFormat> format).unwrap(),
c_fragments
)
self.init(GetResultValue(result))
cdef void init(self, const shared_ptr[CDataset]& sp):
Dataset.init(self, sp)
self.filesystem_dataset = <CFileSystemDataset*> sp.get()
def __reduce__(self):
return FileSystemDataset, (
list(self.get_fragments()),
self.schema,
self.format,
self.partition_expression
)
@classmethod
def from_paths(cls, paths, schema=None, format=None,
filesystem=None, partitions=None, root_partition=None):
"""A Dataset created from a list of paths on a particular filesystem.
Parameters
----------
paths : list of str
List of file paths to create the fragments from.
schema : Schema
The top-level schema of the DataDataset.
format : FileFormat
File format to create fragments from, currently only
ParquetFileFormat, IpcFileFormat, and CsvFileFormat are supported.
filesystem : FileSystem
The filesystem which files are from.
partitions : List[Expression], optional
Attach additional partition information for the file paths.
root_partition : Expression, optional
The top-level partition of the DataDataset.
"""
cdef:
FileFragment fragment
root_partition = root_partition or _true
for arg, class_, name in [
(schema, Schema, 'schema'),
(format, FileFormat, 'format'),
(filesystem, FileSystem, 'filesystem'),
(root_partition, Expression, 'root_partition')
]:
if not isinstance(arg, class_):
raise TypeError(
"Argument '{0}' has incorrect type (expected {1}, "
"got {2})".format(name, class_.__name__, type(arg))
)
partitions = partitions or [_true] * len(paths)
if len(paths) != len(partitions):
raise ValueError(
'The number of files resulting from paths_or_selector '
'must be equal to the number of partitions.'
)
fragments = [
format.make_fragment(path, filesystem, partitions[i])
for i, path in enumerate(paths)
]
return FileSystemDataset(fragments, schema, format, root_partition)
@property
def files(self):
"""List of the files"""
cdef vector[c_string] files = self.filesystem_dataset.files()
return [frombytes(f) for f in files]
@property
def format(self):
"""The FileFormat of this source."""
return FileFormat.wrap(self.filesystem_dataset.format())
cdef shared_ptr[CExpression] _insert_implicit_casts(Expression filter,
Schema schema) except *:
assert schema is not None
if filter is None:
return _true.unwrap()
return GetResultValue(
CInsertImplicitCasts(
deref(filter.unwrap().get()),
deref(pyarrow_unwrap_schema(schema).get())
)
)
cdef class FileFormat:
cdef:
shared_ptr[CFileFormat] wrapped
CFileFormat* format
def __init__(self):
_forbid_instantiation(self.__class__)
cdef void init(self, const shared_ptr[CFileFormat]& sp):
self.wrapped = sp
self.format = sp.get()
@staticmethod
cdef wrap(const shared_ptr[CFileFormat]& sp):
type_name = frombytes(sp.get().type_name())
classes = {
'ipc': IpcFileFormat,
'csv': CsvFileFormat,
'parquet': ParquetFileFormat,
}
class_ = classes.get(type_name, None)
if class_ is None:
raise TypeError(type_name)
cdef FileFormat self = class_.__new__(class_)
self.init(sp)
return self
cdef inline shared_ptr[CFileFormat] unwrap(self):
return self.wrapped
def inspect(self, file, filesystem=None):
"""Infer the schema of a file."""
c_source = _make_file_source(file, filesystem)
c_schema = GetResultValue(self.format.Inspect(c_source))
return pyarrow_wrap_schema(move(c_schema))
def make_fragment(self, file, filesystem=None,
Expression partition_expression=None):
"""
Make a FileFragment of this FileFormat. The filter may not reference
fields absent from the provided schema. If no schema is provided then
one will be inferred.
"""
partition_expression = partition_expression or _true
c_source = _make_file_source(file, filesystem)
c_fragment = <shared_ptr[CFragment]> GetResultValue(
self.format.MakeFragment(move(c_source),
partition_expression.unwrap(),
<shared_ptr[CSchema]>nullptr))
return Fragment.wrap(move(c_fragment))
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return False
cdef class Fragment:
"""Fragment of data from a Dataset."""
cdef:
shared_ptr[CFragment] wrapped
CFragment* fragment
def __init__(self):
_forbid_instantiation(self.__class__)
cdef void init(self, const shared_ptr[CFragment]& sp):
self.wrapped = sp
self.fragment = sp.get()
@staticmethod
cdef wrap(const shared_ptr[CFragment]& sp):
type_name = frombytes(sp.get().type_name())
classes = {
# IpcFileFormat and CsvFileFormat do not have corresponding
# subclasses of FileFragment
'ipc': FileFragment,
'csv': FileFragment,
'parquet': ParquetFileFragment,
}
class_ = classes.get(type_name, None)
if class_ is None:
class_ = Fragment
cdef Fragment self = class_.__new__(class_)
self.init(sp)
return self
cdef inline shared_ptr[CFragment] unwrap(self):
return self.wrapped
@property
def physical_schema(self):
"""Return the physical schema of this Fragment. This schema can be
different from the dataset read schema."""
cdef:
shared_ptr[CSchema] c_schema
c_schema = GetResultValue(self.fragment.ReadPhysicalSchema())
return pyarrow_wrap_schema(c_schema)
@property
def partition_expression(self):
"""An Expression which evaluates to true for all data viewed by this
Fragment.
"""
return Expression.wrap(self.fragment.partition_expression())
def _scanner(self, **kwargs):
return Scanner.from_fragment(self, **kwargs)
def scan(self, Schema schema=None, **kwargs):
"""Builds a scan operation against the dataset.
It produces a stream of ScanTasks which is meant to be a unit of work
to be dispatched. The tasks are not executed automatically, the user is
responsible to execute and dispatch the individual tasks, so custom
local task scheduling can be implemented.
Parameters
----------
schema : Schema
Schema to use for scanning. This is used to unify a Fragment to
it's Dataset's schema. If not specified this will use the
Fragment's physical schema which might differ for each Fragment.
columns : list of str, default None
List of columns to project. Order and duplicates will be preserved.
The columns will be passed down to Datasets and corresponding data
fragments to avoid loading, copying, and deserializing columns
that will not be required further down the compute chain.
By default all of the available columns are projected. Raises
an exception if any of the referenced column names does not exist
in the dataset's Schema.
filter : Expression, default None
Scan will return only the rows matching the filter.
If possible the predicate will be pushed down to exploit the
partition information or internal metadata found in the data
source, e.g. Parquet statistics. Otherwise filters the loaded
RecordBatches before yielding them.
batch_size : int, default 32K
The maximum row count for scanned record batches. If scanned
record batches are overflowing memory then this method can be
called to reduce their size.
use_threads : bool, default True
If enabled, then maximum parallelism will be used determined by
the number of available CPU cores.
memory_pool : MemoryPool, default None
For memory allocations, if required. If not specified, uses the
default pool.
Returns
-------
scan_tasks : iterator of ScanTask
"""
return self._scanner(schema=schema, **kwargs).scan()
def to_batches(self, Schema schema=None, **kwargs):
"""Read the fragment as materialized record batches.
See scan method parameters documentation.
Returns
-------
record_batches : iterator of RecordBatch
"""
return self._scanner(schema=schema, **kwargs).to_batches()
def to_table(self, Schema schema=None, **kwargs):
"""Convert this Fragment into a Table.
Use this convenience utility with care. This will serially materialize
the Scan result in memory before creating the Table.
See scan method parameters documentation.
Returns
-------
table : Table
"""
return self._scanner(schema=schema, **kwargs).to_table()
cdef class FileFragment(Fragment):
"""A Fragment representing a data file."""
cdef:
CFileFragment* file_fragment
cdef void init(self, const shared_ptr[CFragment]& sp):
Fragment.init(self, sp)
self.file_fragment = <CFileFragment*> sp.get()
def __reduce__(self):
buffer = self.buffer
return self.format.make_fragment, (
self.path if buffer is None else buffer,
self.filesystem,
self.partition_expression
)
@property
def path(self):
"""
The path of the data file viewed by this fragment, if it views a
file. If instead it views a buffer, this will be "<Buffer>".
"""
return frombytes(self.file_fragment.source().path())
@property
def filesystem(self):
"""
The FileSystem containing the data file viewed by this fragment, if
it views a file. If instead it views a buffer, this will be None.
"""
cdef:
shared_ptr[CFileSystem] c_fs
c_fs = self.file_fragment.source().filesystem()
if c_fs.get() == nullptr:
return None
return FileSystem.wrap(c_fs)
@property
def buffer(self):
"""
The buffer viewed by this fragment, if it views a buffer. If
instead it views a file, this will be None.
"""
cdef:
shared_ptr[CBuffer] c_buffer
c_buffer = self.file_fragment.source().buffer()
if c_buffer.get() == nullptr:
return None
return pyarrow_wrap_buffer(c_buffer)
@property
def format(self):
"""
The format of the data file viewed by this fragment.
"""
return FileFormat.wrap(self.file_fragment.format())
cdef class RowGroupInfo:
"""A wrapper class for RowGroup information"""
cdef:
CRowGroupInfo info
def __init__(self, int id):
cdef CRowGroupInfo info = CRowGroupInfo(id)
self.init(info)
cdef void init(self, CRowGroupInfo info):
self.info = info
@staticmethod
cdef wrap(CRowGroupInfo info):
cdef RowGroupInfo self = RowGroupInfo.__new__(RowGroupInfo)
self.init(info)
return self
@property
def id(self):
return self.info.id()
@property
def num_rows(self):
return self.info.num_rows()
@property
def total_byte_size(self):
return self.info.total_byte_size()
@property
def statistics(self):
if not self.info.HasStatistics():
return None
cdef:
CStructScalar* c_statistics
CStructScalar* c_minmax
statistics = dict()
c_statistics = self.info.statistics().get()
for i in range(c_statistics.value.size()):
name = frombytes(c_statistics.type.get().field(i).get().name())
c_minmax = <CStructScalar*> c_statistics.value[i].get()
statistics[name] = {
'min': pyarrow_wrap_scalar(c_minmax.value[0]).as_py(),
'max': pyarrow_wrap_scalar(c_minmax.value[1]).as_py(),
}
return statistics
def __eq__(self, other):
if not isinstance(other, RowGroupInfo):
return False
cdef:
RowGroupInfo row_group = other
CRowGroupInfo c_info = row_group.info
return self.info.Equals(c_info)
cdef class ParquetFileFragment(FileFragment):
"""A Fragment representing a parquet file."""
cdef:
CParquetFileFragment* parquet_file_fragment
cdef void init(self, const shared_ptr[CFragment]& sp):
FileFragment.init(self, sp)
self.parquet_file_fragment = <CParquetFileFragment*> sp.get()
def __reduce__(self):
buffer = self.buffer
if self.row_groups is not None:
row_groups = [row_group.id for row_group in self.row_groups]
else:
row_groups = None
return self.format.make_fragment, (
self.path if buffer is None else buffer,
self.filesystem,
self.partition_expression,
row_groups
)
def ensure_complete_metadata(self):
"""
Ensure that all metadata (statistics, physical schema, ...) have
been read and cached in this fragment.
"""
check_status(self.parquet_file_fragment.EnsureCompleteMetadata())
@property
def row_groups(self):
cdef:
vector[CRowGroupInfo] c_row_groups
c_row_groups = self.parquet_file_fragment.row_groups()
if c_row_groups.empty():
return None
return [RowGroupInfo.wrap(row_group) for row_group in c_row_groups]
def split_by_row_group(self, Expression filter=None,
Schema schema=None):
"""
Split the fragment into multiple fragments.
Yield a Fragment wrapping each row group in this ParquetFileFragment.
Row groups will be excluded whose metadata contradicts the optional
filter.
Parameters
----------
filter : Expression, default None
Only include the row groups which satisfy this predicate (using
the Parquet RowGroup statistics).
schema : Schema, default None
Schema to use when filtering row groups. Defaults to the
Fragment's phsyical schema
Returns
-------
A list of Fragment.
"""
cdef:
vector[shared_ptr[CFragment]] c_fragments
shared_ptr[CExpression] c_filter
shared_ptr[CFragment] c_fragment
schema = schema or self.physical_schema
c_filter = _insert_implicit_casts(filter, schema)
with nogil:
c_fragments = move(GetResultValue(
self.parquet_file_fragment.SplitByRowGroup(move(c_filter))))
return [Fragment.wrap(c_fragment) for c_fragment in c_fragments]
cdef class ParquetReadOptions:
"""
Parquet format specific options for reading.
Parameters
----------
use_buffered_stream : bool, default False
Read files through buffered input streams rather than loading entire
row groups at once. This may be enabled to reduce memory overhead.
Disabled by default.
buffer_size : int, default 8192
Size of buffered stream, if enabled. Default is 8KB.
dictionary_columns : list of string, default None
Names of columns which should be dictionary encoded as
they are read.
"""
cdef public:
bint use_buffered_stream
uint32_t buffer_size
set dictionary_columns