/
_dataset.pyx
2859 lines (2361 loc) · 98.8 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 cython.operator cimport dereference as deref
import codecs
import collections
import os
import warnings
from libcpp cimport bool
import pyarrow as pa
from pyarrow.lib cimport *
from pyarrow.lib import ArrowTypeError, frombytes, tobytes, _pc
from pyarrow.includes.libarrow_dataset cimport *
from pyarrow._compute cimport Expression, _bind
from pyarrow._fs cimport FileSystem, FileInfo, FileSelector
from pyarrow._csv cimport (
ConvertOptions, ParseOptions, ReadOptions, WriteOptions)
from pyarrow.util import _is_iterable, _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)
_orc_fileformat = None
_orc_imported = False
def _get_orc_fileformat():
"""
Import OrcFileFormat on first usage (to avoid circular import issue
when `pyarrow._dataset_orc` would be imported first)
"""
global _orc_fileformat
global _orc_imported
if not _orc_imported:
try:
from pyarrow._dataset_orc import OrcFileFormat
_orc_fileformat = OrcFileFormat
except ImportError as e:
_orc_fileformat = None
finally:
_orc_imported = True
return _orc_fileformat
_dataset_pq = False
def _get_parquet_classes():
"""
Import Parquet class files on first usage (to avoid circular import issue
when `pyarrow._dataset_parquet` would be imported first)
"""
global _dataset_pq
if _dataset_pq is False:
try:
import pyarrow._dataset_parquet as _dataset_pq
except ImportError:
_dataset_pq = None
def _get_parquet_symbol(name):
"""
Get a symbol from pyarrow.parquet if the latter is importable, otherwise
return None.
"""
_get_parquet_classes()
return _dataset_pq and getattr(_dataset_pq, name)
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 CSegmentEncoding _get_segment_encoding(str segment_encoding):
if segment_encoding == "none":
return CSegmentEncodingNone
elif segment_encoding == "uri":
return CSegmentEncodingUri
raise ValueError(f"Unknown segment encoding: {segment_encoding}")
cdef Expression _true = Expression._scalar(True)
cdef class Dataset(_Weakrefable):
"""
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).
"""
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,
'in-memory': InMemoryDataset,
}
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.
"""
return Expression.wrap(self.dataset.partition_expression())
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.
Parameters
----------
schema : Schema
The new dataset schema.
"""
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:
CExpression c_filter
CFragmentIterator c_iterator
if filter is None:
c_fragments = move(GetResultValue(self.dataset.GetFragments()))
else:
c_filter = _bind(filter, self.schema)
c_fragments = move(GetResultValue(
self.dataset.GetFragments(c_filter)))
for maybe_fragment in c_fragments:
yield Fragment.wrap(GetResultValue(move(maybe_fragment)))
def scanner(self, **kwargs):
"""
Build a scan operation against the dataset.
Data is not loaded immediately. Instead, this produces a Scanner,
which exposes further operations (e.g. loading all data as a
table, counting rows).
See the `Scanner.from_dataset` method for further information.
Parameters
----------
**kwargs : dict, optional
Arguments for `Scanner.from_dataset`.
Returns
-------
scanner : Scanner
Examples
--------
>>> import pyarrow as pa
>>> table = pa.table({'year': [2020, 2022, 2021, 2022, 2019, 2021],
... 'n_legs': [2, 2, 4, 4, 5, 100],
... 'animal': ["Flamingo", "Parrot", "Dog", "Horse",
... "Brittle stars", "Centipede"]})
>>>
>>> import pyarrow.parquet as pq
>>> pq.write_table(table, "dataset_scanner.parquet")
>>> import pyarrow.dataset as ds
>>> dataset = ds.dataset("dataset_scanner.parquet")
Selecting a subset of the columns:
>>> dataset.scanner(columns=["year", "n_legs"]).to_table()
pyarrow.Table
year: int64
n_legs: int64
----
year: [[2020,2022,2021,2022,2019,2021]]
n_legs: [[2,2,4,4,5,100]]
Projecting selected columns using an expression:
>>> dataset.scanner(columns={
... "n_legs_uint": ds.field("n_legs").cast("uint8"),
... }).to_table()
pyarrow.Table
n_legs_uint: uint8
----
n_legs_uint: [[2,2,4,4,5,100]]
Filtering rows while scanning:
>>> dataset.scanner(filter=ds.field("year") > 2020).to_table()
pyarrow.Table
year: int64
n_legs: int64
animal: string
----
year: [[2022,2021,2022,2021]]
n_legs: [[2,4,4,100]]
animal: [["Parrot","Dog","Horse","Centipede"]]
"""
return Scanner.from_dataset(self, **kwargs)
def to_batches(self, **kwargs):
"""
Read the dataset as materialized record batches.
Parameters
----------
**kwargs : dict, optional
Arguments for `Scanner.from_dataset`.
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.
Parameters
----------
**kwargs : dict, optional
Arguments for `Scanner.from_dataset`.
Returns
-------
table : Table
"""
return self.scanner(**kwargs).to_table()
def take(self, object indices, **kwargs):
"""
Select rows of data by index.
Parameters
----------
indices : Array or array-like
indices of rows to select in the dataset.
**kwargs : dict, optional
See scanner() method for full parameter description.
Returns
-------
table : Table
"""
return self.scanner(**kwargs).take(indices)
def head(self, int num_rows, **kwargs):
"""
Load the first N rows of the dataset.
Parameters
----------
num_rows : int
The number of rows to load.
**kwargs : dict, optional
See scanner() method for full parameter description.
Returns
-------
table : Table
"""
return self.scanner(**kwargs).head(num_rows)
def count_rows(self, **kwargs):
"""
Count rows matching the scanner filter.
Parameters
----------
**kwargs : dict, optional
See scanner() method for full parameter description.
Returns
-------
count : int
"""
return self.scanner(**kwargs).count_rows()
@property
def schema(self):
"""The common schema of the full Dataset"""
return pyarrow_wrap_schema(self.dataset.schema())
def join(self, right_dataset, keys, right_keys=None, join_type="left outer",
left_suffix=None, right_suffix=None, coalesce_keys=True,
use_threads=True):
"""
Perform a join between this dataset and another one.
Result of the join will be a new dataset, where further
operations can be applied.
Parameters
----------
right_dataset : dataset
The dataset to join to the current one, acting as the right dataset
in the join operation.
keys : str or list[str]
The columns from current dataset that should be used as keys
of the join operation left side.
right_keys : str or list[str], default None
The columns from the right_dataset that should be used as keys
on the join operation right side.
When ``None`` use the same key names as the left dataset.
join_type : str, default "left outer"
The kind of join that should be performed, one of
("left semi", "right semi", "left anti", "right anti",
"inner", "left outer", "right outer", "full outer")
left_suffix : str, default None
Which suffix to add to right column names. This prevents confusion
when the columns in left and right datasets have colliding names.
right_suffix : str, default None
Which suffic to add to the left column names. This prevents confusion
when the columns in left and right datasets have colliding names.
coalesce_keys : bool, default True
If the duplicated keys should be omitted from one of the sides
in the join result.
use_threads : bool, default True
Whenever to use multithreading or not.
Returns
-------
InMemoryDataset
"""
if right_keys is None:
right_keys = keys
return _pc()._exec_plan._perform_join(join_type, self, keys, right_dataset, right_keys,
left_suffix=left_suffix, right_suffix=right_suffix,
use_threads=use_threads, coalesce_keys=coalesce_keys,
output_type=InMemoryDataset)
cdef class InMemoryDataset(Dataset):
"""
A Dataset wrapping in-memory data.
Parameters
----------
source : The data for this dataset.
Can be a RecordBatch, Table, list of
RecordBatch/Table, iterable of RecordBatch, or a RecordBatchReader.
If an iterable is provided, the schema must also be provided.
schema : Schema, optional
Only required if passing an iterable as the source.
"""
cdef:
CInMemoryDataset* in_memory_dataset
def __init__(self, source, Schema schema=None):
cdef:
RecordBatchReader reader
shared_ptr[CInMemoryDataset] in_memory_dataset
if isinstance(source, (pa.RecordBatch, pa.Table)):
source = [source]
if isinstance(source, (list, tuple)):
batches = []
for item in source:
if isinstance(item, pa.RecordBatch):
batches.append(item)
elif isinstance(item, pa.Table):
batches.extend(item.to_batches())
else:
raise TypeError(
'Expected a list of tables or batches. The given list '
'contains a ' + type(item).__name__)
if schema is None:
schema = item.schema
elif not schema.equals(item.schema):
raise ArrowTypeError(
f'Item has schema\n{item.schema}\nwhich does not '
f'match expected schema\n{schema}')
if not batches and schema is None:
raise ValueError('Must provide schema to construct in-memory '
'dataset from an empty list')
table = pa.Table.from_batches(batches, schema=schema)
in_memory_dataset = make_shared[CInMemoryDataset](
pyarrow_unwrap_table(table))
else:
raise TypeError(
'Expected a table, batch, or list of tables/batches '
'instead of the given type: ' +
type(source).__name__
)
self.init(<shared_ptr[CDataset]> in_memory_dataset)
cdef void init(self, const shared_ptr[CDataset]& sp):
Dataset.init(self, sp)
self.in_memory_dataset = <CInMemoryDataset*> sp.get()
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.
filesystem : FileSystem
FileSystem of the fragments.
root_partition : Expression, optional
The top-level partition of the DataDataset.
"""
cdef:
CFileSystemDataset* filesystem_dataset
def __init__(self, fragments, Schema schema, FileFormat format,
FileSystem filesystem=None, root_partition=None):
cdef:
FileFragment fragment=None
vector[shared_ptr[CFileFragment]] c_fragments
CResult[shared_ptr[CDataset]] result
shared_ptr[CFileSystem] c_filesystem
if root_partition is None:
root_partition = _true
elif 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()))
if filesystem is None:
filesystem = fragment.filesystem
if filesystem is not None:
c_filesystem = filesystem.unwrap()
result = CFileSystemDataset.Make(
pyarrow_unwrap_schema(schema),
(<Expression> root_partition).unwrap(),
format.unwrap(),
c_filesystem,
c_fragments
)
self.init(GetResultValue(result))
@property
def filesystem(self):
return FileSystem.wrap(self.filesystem_dataset.filesystem())
@property
def partitioning(self):
"""
The partitioning of the Dataset source, if discovered.
If the FileSystemDataset is created using the ``dataset()`` factory
function with a partitioning specified, this will return the
finalized Partitioning object from the dataset discovery. In all
other cases, this returns None.
"""
c_partitioning = self.filesystem_dataset.partitioning()
if c_partitioning.get() == nullptr:
return None
try:
return Partitioning.wrap(c_partitioning)
except TypeError:
# e.g. type_name "default"
return None
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.filesystem,
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
if root_partition is None:
root_partition = _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,
filesystem, 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 class FileWriteOptions(_Weakrefable):
def __init__(self):
_forbid_instantiation(self.__class__)
cdef void init(self, const shared_ptr[CFileWriteOptions]& sp):
self.wrapped = sp
self.c_options = sp.get()
@staticmethod
cdef wrap(const shared_ptr[CFileWriteOptions]& sp):
type_name = frombytes(sp.get().type_name())
classes = {
'csv': CsvFileWriteOptions,
'ipc': IpcFileWriteOptions,
'parquet': _get_parquet_symbol('ParquetFileWriteOptions'),
}
class_ = classes.get(type_name, None)
if class_ is None:
raise TypeError(type_name)
cdef FileWriteOptions self = class_.__new__(class_)
self.init(sp)
return self
@property
def format(self):
return FileFormat.wrap(self.c_options.format())
cdef inline shared_ptr[CFileWriteOptions] unwrap(self):
return self.wrapped
cdef class FileFormat(_Weakrefable):
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': _get_parquet_symbol('ParquetFileFormat'),
'orc': _get_orc_fileformat(),
}
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 WrittenFile _finish_write(self, path, base_dir,
CFileWriter* file_writer):
parquet_metadata = None
size = GetResultValue(file_writer.GetBytesWritten())
return WrittenFile(path, parquet_metadata, size)
cdef inline shared_ptr[CFileFormat] unwrap(self):
return self.wrapped
def inspect(self, file, filesystem=None):
"""
Infer the schema of a file.
Parameters
----------
file : file-like object, path-like or str
The file or file path to infer a schema from.
filesystem : Filesystem, optional
If `filesystem` is given, `file` must be a string and specifies
the path of the file to read from the filesystem.
Returns
-------
schema : Schema
The schema inferred from the file
"""
cdef:
CFileSource c_source = _make_file_source(file, filesystem)
CResult[shared_ptr[CSchema]] c_result
with nogil:
c_result = self.format.Inspect(c_source)
c_schema = GetResultValue(c_result)
return pyarrow_wrap_schema(move(c_schema))
def make_fragment(self, file, filesystem=None,
Expression partition_expression=None):
"""
Make a FileFragment from a given file.
Parameters
----------
file : file-like object, path-like or str
The file or file path to make a fragment from.
filesystem : Filesystem, optional
If `filesystem` is given, `file` must be a string and specifies
the path of the file to read from the filesystem.
partition_expression : Expression
The filter expression.
"""
if partition_expression is None:
partition_expression = _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 make_write_options(self):
return FileWriteOptions.wrap(self.format.DefaultWriteOptions())
@property
def default_extname(self):
return frombytes(self.format.type_name())
@property
def default_fragment_scan_options(self):
dfso = FragmentScanOptions.wrap(
self.wrapped.get().default_fragment_scan_options)
# CsvFileFormat stores a Python-specific encoding field that needs
# to be restored because it does not exist in the C++ struct
if isinstance(self, CsvFileFormat):
if self._read_options_py is not None:
dfso.read_options = self._read_options_py
return dfso
@default_fragment_scan_options.setter
def default_fragment_scan_options(self, FragmentScanOptions options):
if options is None:
self.wrapped.get().default_fragment_scan_options =\
<shared_ptr[CFragmentScanOptions]>nullptr
else:
self._set_default_fragment_scan_options(options)
cdef _set_default_fragment_scan_options(self, FragmentScanOptions options):
raise ValueError(f"Cannot set fragment scan options for "
f"'{options.type_name}' on {self.__class__.__name__}")
def __eq__(self, other):
try:
return self.equals(other)
except TypeError:
return False
cdef class Fragment(_Weakrefable):
"""Fragment of data from a Dataset."""
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, CsvFileFormat and OrcFileFormat do not have
# corresponding subclasses of FileFragment
'ipc': FileFragment,
'csv': FileFragment,
'orc': FileFragment,
'parquet': _get_parquet_symbol('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:
CResult[shared_ptr[CSchema]] maybe_schema
with nogil:
maybe_schema = self.fragment.ReadPhysicalSchema()
return pyarrow_wrap_schema(GetResultValue(maybe_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, Schema schema=None, **kwargs):
"""
Build a scan operation against the fragment.
Data is not loaded immediately. Instead, this produces a Scanner,
which exposes further operations (e.g. loading all data as a
table, counting rows).
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.
**kwargs : dict, optional
Arguments for `Scanner.from_fragment`.
Returns
-------
scanner : Scanner
"""
return Scanner.from_fragment(self, schema=schema, **kwargs)
def to_batches(self, Schema schema=None, **kwargs):
"""
Read the fragment as materialized record batches.
Parameters
----------
schema : Schema, optional
Concrete schema to use for scanning.
**kwargs : dict, optional
Arguments for `Scanner.from_fragment`.
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.
Parameters
----------
schema : Schema, optional
Concrete schema to use for scanning.
**kwargs : dict, optional
Arguments for `Scanner.from_fragment`.
Returns
-------
table : Table
"""
return self.scanner(schema=schema, **kwargs).to_table()
def take(self, object indices, **kwargs):
"""
Select rows of data by index.
Parameters
----------
indices : Array or array-like
The indices of row to select in the dataset.
**kwargs : dict, optional
Arguments for `Scanner.from_fragment`.
Returns
-------
Table
"""
return self.scanner(**kwargs).take(indices)
def head(self, int num_rows, **kwargs):
"""
Load the first N rows of the fragment.
Parameters
----------
num_rows : int
The number of rows to load.
**kwargs : dict, optional
Arguments for `Scanner.from_fragment`.