-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathtest_dataset.py
5651 lines (4590 loc) · 202 KB
/
test_dataset.py
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.
import contextlib
import datetime
import os
import pathlib
import posixpath
import sys
import tempfile
import textwrap
import threading
import time
from shutil import copytree
from urllib.parse import quote
import numpy as np
import pytest
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.csv
import pyarrow.feather
import pyarrow.fs as fs
import pyarrow.json
from pyarrow.tests.util import (FSProtocolClass, ProxyHandler,
_configure_s3_limited_user, _filesystem_uri,
change_cwd)
try:
import pandas as pd
except ImportError:
pd = None
try:
import pyarrow.dataset as ds
except ImportError:
ds = None
try:
import pyarrow.parquet as pq
except ImportError:
pq = None
# Marks all of the tests in this module
# Ignore these with pytest ... -m 'not dataset'
pytestmark = pytest.mark.dataset
def _generate_data(n):
import datetime
import itertools
day = datetime.datetime(2000, 1, 1)
interval = datetime.timedelta(days=5)
colors = itertools.cycle(['green', 'blue', 'yellow', 'red', 'orange'])
data = []
for i in range(n):
data.append((day, i, float(i), next(colors)))
day += interval
return pd.DataFrame(data, columns=['date', 'index', 'value', 'color'])
def _table_from_pandas(df):
schema = pa.schema([
pa.field('date', pa.date32()),
pa.field('index', pa.int64()),
pa.field('value', pa.float64()),
pa.field('color', pa.string()),
])
table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)
return table.replace_schema_metadata()
def assert_dataset_fragment_convenience_methods(dataset):
# FileFragment convenience methods
for fragment in dataset.get_fragments():
with fragment.open() as nf:
assert isinstance(nf, pa.NativeFile)
assert not nf.closed
assert nf.seekable()
assert nf.readable()
assert not nf.writable()
@pytest.fixture
def mockfs():
mockfs = fs._MockFileSystem()
directories = [
'subdir/1/xxx',
'subdir/2/yyy',
]
for i, directory in enumerate(directories):
path = '{}/file{}.parquet'.format(directory, i)
mockfs.create_dir(directory)
with mockfs.open_output_stream(path) as out:
data = [
list(range(5)),
list(map(float, range(5))),
list(map(str, range(5))),
[i] * 5,
[{'a': j % 3, 'b': str(j % 3)} for j in range(5)],
]
schema = pa.schema([
('i64', pa.int64()),
('f64', pa.float64()),
('str', pa.string()),
('const', pa.int64()),
('struct', pa.struct({'a': pa.int64(), 'b': pa.string()})),
])
batch = pa.record_batch(data, schema=schema)
table = pa.Table.from_batches([batch])
pq.write_table(table, out)
return mockfs
@pytest.fixture
def open_logging_fs(monkeypatch):
from pyarrow.fs import LocalFileSystem, PyFileSystem
from .test_fs import ProxyHandler
localfs = LocalFileSystem()
def normalized(paths):
return {localfs.normalize_path(str(p)) for p in paths}
opened = set()
def open_input_file(self, path):
path = localfs.normalize_path(str(path))
opened.add(path)
return self._fs.open_input_file(path)
# patch proxyhandler to log calls to open_input_file
monkeypatch.setattr(ProxyHandler, "open_input_file", open_input_file)
fs = PyFileSystem(ProxyHandler(localfs))
@contextlib.contextmanager
def assert_opens(expected_opened):
opened.clear()
try:
yield
finally:
assert normalized(opened) == normalized(expected_opened)
return fs, assert_opens
@pytest.fixture(scope='module')
def multisourcefs(request):
request.config.pyarrow.requires('pandas')
request.config.pyarrow.requires('parquet')
df = _generate_data(1000)
mockfs = fs._MockFileSystem()
# simply split the dataframe into four chunks to construct a data source
# from each chunk into its own directory
n = len(df)
df_a, df_b, df_c, df_d = [df.iloc[i:i+n//4] for i in range(0, n, n//4)]
# create a directory containing a flat sequence of parquet files without
# any partitioning involved
mockfs.create_dir('plain')
n = len(df_a)
for i, chunk in enumerate([df_a.iloc[i:i+n//10] for i in range(0, n, n//10)]):
path = 'plain/chunk-{}.parquet'.format(i)
with mockfs.open_output_stream(path) as out:
pq.write_table(_table_from_pandas(chunk), out)
# create one with schema partitioning by weekday and color
mockfs.create_dir('schema')
for part, chunk in df_b.groupby([df_b.date.dt.dayofweek, df_b.color]):
folder = 'schema/{}/{}'.format(*part)
path = '{}/chunk.parquet'.format(folder)
mockfs.create_dir(folder)
with mockfs.open_output_stream(path) as out:
pq.write_table(_table_from_pandas(chunk), out)
# create one with hive partitioning by year and month
mockfs.create_dir('hive')
for part, chunk in df_c.groupby([df_c.date.dt.year, df_c.date.dt.month]):
folder = 'hive/year={}/month={}'.format(*part)
path = '{}/chunk.parquet'.format(folder)
mockfs.create_dir(folder)
with mockfs.open_output_stream(path) as out:
pq.write_table(_table_from_pandas(chunk), out)
# create one with hive partitioning by color
mockfs.create_dir('hive_color')
for part, chunk in df_d.groupby("color"):
folder = 'hive_color/color={}'.format(part)
path = '{}/chunk.parquet'.format(folder)
mockfs.create_dir(folder)
with mockfs.open_output_stream(path) as out:
pq.write_table(_table_from_pandas(chunk), out)
return mockfs
@pytest.fixture
def dataset(mockfs):
format = ds.ParquetFileFormat()
selector = fs.FileSelector('subdir', recursive=True)
options = ds.FileSystemFactoryOptions('subdir')
options.partitioning = ds.DirectoryPartitioning(
pa.schema([
pa.field('group', pa.int32()),
pa.field('key', pa.string())
])
)
factory = ds.FileSystemDatasetFactory(mockfs, selector, format, options)
return factory.finish()
@pytest.fixture(params=[
(True),
(False)
], ids=['threaded', 'serial'])
def dataset_reader(request):
'''
Fixture which allows dataset scanning operations to be
run with/without threads
'''
use_threads = request.param
class reader:
def __init__(self):
self.use_threads = use_threads
def _patch_kwargs(self, kwargs):
if 'use_threads' in kwargs:
raise Exception(
('Invalid use of dataset_reader, do not specify'
' use_threads'))
kwargs['use_threads'] = use_threads
def to_table(self, dataset, **kwargs):
self._patch_kwargs(kwargs)
return dataset.to_table(**kwargs)
def to_batches(self, dataset, **kwargs):
self._patch_kwargs(kwargs)
return dataset.to_batches(**kwargs)
def scanner(self, dataset, **kwargs):
self._patch_kwargs(kwargs)
return dataset.scanner(**kwargs)
def head(self, dataset, num_rows, **kwargs):
self._patch_kwargs(kwargs)
return dataset.head(num_rows, **kwargs)
def take(self, dataset, indices, **kwargs):
self._patch_kwargs(kwargs)
return dataset.take(indices, **kwargs)
def count_rows(self, dataset, **kwargs):
self._patch_kwargs(kwargs)
return dataset.count_rows(**kwargs)
return reader()
@pytest.mark.parquet
def test_filesystem_dataset(mockfs):
schema = pa.schema([
pa.field('const', pa.int64())
])
file_format = ds.ParquetFileFormat()
paths = ['subdir/1/xxx/file0.parquet', 'subdir/2/yyy/file1.parquet']
partitions = [ds.field('part') == x for x in range(1, 3)]
fragments = [file_format.make_fragment(path, mockfs, part)
for path, part in zip(paths, partitions)]
root_partition = ds.field('level') == ds.scalar(1337)
dataset_from_fragments = ds.FileSystemDataset(
fragments, schema=schema, format=file_format,
filesystem=mockfs, root_partition=root_partition,
)
dataset_from_paths = ds.FileSystemDataset.from_paths(
paths, schema=schema, format=file_format, filesystem=mockfs,
partitions=partitions, root_partition=root_partition,
)
for dataset in [dataset_from_fragments, dataset_from_paths]:
assert isinstance(dataset, ds.FileSystemDataset)
assert isinstance(dataset.format, ds.ParquetFileFormat)
assert dataset.partition_expression.equals(root_partition)
assert set(dataset.files) == set(paths)
fragments = list(dataset.get_fragments())
for fragment, partition, path in zip(fragments, partitions, paths):
assert fragment.partition_expression.equals(partition)
assert fragment.path == path
assert isinstance(fragment.format, ds.ParquetFileFormat)
assert isinstance(fragment, ds.ParquetFileFragment)
assert fragment.row_groups == [0]
assert fragment.num_row_groups == 1
row_group_fragments = list(fragment.split_by_row_group())
assert fragment.num_row_groups == len(row_group_fragments) == 1
assert isinstance(row_group_fragments[0], ds.ParquetFileFragment)
assert row_group_fragments[0].path == path
assert row_group_fragments[0].row_groups == [0]
assert row_group_fragments[0].num_row_groups == 1
fragments = list(dataset.get_fragments(filter=ds.field("const") == 0))
assert len(fragments) == 2
# the root_partition keyword has a default
dataset = ds.FileSystemDataset(
fragments, schema=schema, format=file_format, filesystem=mockfs
)
assert dataset.partition_expression.equals(ds.scalar(True))
# from_paths partitions have defaults
dataset = ds.FileSystemDataset.from_paths(
paths, schema=schema, format=file_format, filesystem=mockfs
)
assert dataset.partition_expression.equals(ds.scalar(True))
for fragment in dataset.get_fragments():
assert fragment.partition_expression.equals(ds.scalar(True))
# validation of required arguments
with pytest.raises(TypeError, match="incorrect type"):
ds.FileSystemDataset(fragments, file_format, schema)
# validation of root_partition
with pytest.raises(TypeError, match="incorrect type"):
ds.FileSystemDataset(fragments, schema=schema,
format=file_format, root_partition=1)
# missing required argument in from_paths
with pytest.raises(TypeError, match="incorrect type"):
ds.FileSystemDataset.from_paths(fragments, format=file_format)
def test_filesystem_dataset_no_filesystem_interaction(dataset_reader):
# ARROW-8283
schema = pa.schema([
pa.field('f1', pa.int64())
])
file_format = ds.IpcFileFormat()
paths = ['nonexistingfile.arrow']
# creating the dataset itself doesn't raise
dataset = ds.FileSystemDataset.from_paths(
paths, schema=schema, format=file_format,
filesystem=fs.LocalFileSystem(),
)
# getting fragments also doesn't raise
dataset.get_fragments()
# scanning does raise
with pytest.raises(FileNotFoundError):
dataset_reader.to_table(dataset)
@pytest.mark.parquet
def test_dataset(dataset, dataset_reader):
assert isinstance(dataset, ds.Dataset)
assert isinstance(dataset.schema, pa.Schema)
# TODO(kszucs): test non-boolean Exprs for filter do raise
expected_i64 = pa.array([0, 1, 2, 3, 4], type=pa.int64())
expected_f64 = pa.array([0, 1, 2, 3, 4], type=pa.float64())
for batch in dataset_reader.to_batches(dataset):
assert isinstance(batch, pa.RecordBatch)
assert batch.column(0).equals(expected_i64)
assert batch.column(1).equals(expected_f64)
for batch in dataset_reader.scanner(dataset).scan_batches():
assert isinstance(batch, ds.TaggedRecordBatch)
assert isinstance(batch.fragment, ds.Fragment)
table = dataset_reader.to_table(dataset)
assert isinstance(table, pa.Table)
assert len(table) == 10
condition = ds.field('i64') == 1
result = dataset.to_table(use_threads=True, filter=condition)
# Don't rely on the scanning order
result = result.sort_by('group').to_pydict()
assert result['i64'] == [1, 1]
assert result['f64'] == [1., 1.]
assert sorted(result['group']) == [1, 2]
assert sorted(result['key']) == ['xxx', 'yyy']
# Filtering on a nested field ref
condition = ds.field(('struct', 'b')) == '1'
result = dataset.to_table(use_threads=True, filter=condition)
result = result.sort_by('group').to_pydict()
assert result['i64'] == [1, 4, 1, 4]
assert result['f64'] == [1.0, 4.0, 1.0, 4.0]
assert result['group'] == [1, 1, 2, 2]
assert result['key'] == ['xxx', 'xxx', 'yyy', 'yyy']
# Projecting on a nested field ref expression
projection = {
'i64': ds.field('i64'),
'f64': ds.field('f64'),
'new': ds.field(('struct', 'b')) == '1',
}
result = dataset.to_table(use_threads=True, columns=projection)
result = result.sort_by('i64').to_pydict()
assert list(result) == ['i64', 'f64', 'new']
assert result['i64'] == [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
assert result['f64'] == [0.0, 0.0, 1.0, 1.0,
2.0, 2.0, 3.0, 3.0, 4.0, 4.0]
assert result['new'] == [False, False, True, True, False, False,
False, False, True, True]
assert_dataset_fragment_convenience_methods(dataset)
@pytest.mark.parquet
def test_scanner_options(dataset):
scanner = dataset.to_batches(fragment_readahead=16, batch_readahead=8)
batch = next(scanner)
assert batch.num_columns == 7
@pytest.mark.parquet
def test_scanner(dataset, dataset_reader):
scanner = dataset_reader.scanner(
dataset, memory_pool=pa.default_memory_pool())
assert isinstance(scanner, ds.Scanner)
with pytest.raises(pa.ArrowInvalid):
dataset_reader.scanner(dataset, columns=['unknown'])
scanner = dataset_reader.scanner(dataset, columns=['i64'],
memory_pool=pa.default_memory_pool())
assert scanner.dataset_schema == dataset.schema
assert scanner.projected_schema == pa.schema([("i64", pa.int64())])
assert isinstance(scanner, ds.Scanner)
table = scanner.to_table()
for batch in scanner.to_batches():
assert batch.schema == scanner.projected_schema
assert batch.num_columns == 1
assert table == scanner.to_reader().read_all()
assert table.schema == scanner.projected_schema
for i in range(table.num_rows):
indices = pa.array([i])
assert table.take(indices) == scanner.take(indices)
with pytest.raises(pa.ArrowIndexError):
scanner.take(pa.array([table.num_rows]))
assert table.num_rows == scanner.count_rows()
scanner = dataset_reader.scanner(dataset, columns=['__filename',
'__fragment_index',
'__batch_index',
'__last_in_fragment'],
memory_pool=pa.default_memory_pool())
table = scanner.to_table()
expected_names = ['__filename', '__fragment_index',
'__batch_index', '__last_in_fragment']
assert table.column_names == expected_names
sorted_table = table.sort_by('__fragment_index')
assert sorted_table['__filename'].to_pylist() == (
['subdir/1/xxx/file0.parquet'] * 5 +
['subdir/2/yyy/file1.parquet'] * 5)
assert sorted_table['__fragment_index'].to_pylist() == ([0] * 5 + [1] * 5)
assert sorted_table['__batch_index'].to_pylist() == [0] * 10
assert sorted_table['__last_in_fragment'].to_pylist() == [True] * 10
@pytest.mark.parquet
def test_scanner_memory_pool(dataset):
# honor default pool - https://issues.apache.org/jira/browse/ARROW-18164
old_pool = pa.default_memory_pool()
# TODO(ARROW-18293) we should be able to use the proxy memory pool for
# for testing, but this crashes
# pool = pa.proxy_memory_pool(old_pool)
pool = pa.system_memory_pool()
pa.set_memory_pool(pool)
try:
allocated_before = pool.bytes_allocated()
scanner = ds.Scanner.from_dataset(dataset)
_ = scanner.to_table()
assert pool.bytes_allocated() > allocated_before
finally:
pa.set_memory_pool(old_pool)
@pytest.mark.parquet
def test_head(dataset, dataset_reader):
result = dataset_reader.head(dataset, 0)
assert result == pa.Table.from_batches([], schema=dataset.schema)
result = dataset_reader.head(dataset, 1, columns=['i64']).to_pydict()
assert result == {'i64': [0]}
result = dataset_reader.head(dataset, 2, columns=['i64'],
filter=ds.field('i64') > 1).to_pydict()
assert result == {'i64': [2, 3]}
result = dataset_reader.head(dataset, 1024, columns=['i64']).to_pydict()
assert result == {'i64': list(range(5)) * 2}
fragment = next(dataset.get_fragments())
result = fragment.head(1, columns=['i64']).to_pydict()
assert result == {'i64': [0]}
result = fragment.head(1024, columns=['i64']).to_pydict()
assert result == {'i64': list(range(5))}
@pytest.mark.parquet
def test_take(dataset, dataset_reader):
fragment = next(dataset.get_fragments())
for indices in [[1, 3], pa.array([1, 3])]:
expected = dataset_reader.to_table(fragment).take(indices)
assert dataset_reader.take(fragment, indices) == expected
with pytest.raises(IndexError):
dataset_reader.take(fragment, pa.array([5]))
for indices in [[1, 7], pa.array([1, 7])]:
assert dataset_reader.take(
dataset, indices) == dataset_reader.to_table(dataset).take(indices)
with pytest.raises(IndexError):
dataset_reader.take(dataset, pa.array([10]))
@pytest.mark.parquet
def test_count_rows(dataset, dataset_reader):
fragment = next(dataset.get_fragments())
assert dataset_reader.count_rows(fragment) == 5
assert dataset_reader.count_rows(
fragment, filter=ds.field("i64") == 4) == 1
assert dataset_reader.count_rows(dataset) == 10
# Filter on partition key
assert dataset_reader.count_rows(
dataset, filter=ds.field("group") == 1) == 5
# Filter on data
assert dataset_reader.count_rows(dataset, filter=ds.field("i64") >= 3) == 4
assert dataset_reader.count_rows(dataset, filter=ds.field("i64") < 0) == 0
def test_abstract_classes():
classes = [
ds.FileFormat,
ds.Scanner,
ds.Partitioning,
]
for klass in classes:
with pytest.raises(TypeError):
klass()
def test_partitioning():
schema = pa.schema([
pa.field('i64', pa.int64()),
pa.field('f64', pa.float64())
])
for klass in [ds.DirectoryPartitioning, ds.HivePartitioning,
ds.FilenamePartitioning]:
partitioning = klass(schema)
assert isinstance(partitioning, ds.Partitioning)
assert partitioning == klass(schema)
assert partitioning != "other object"
schema = pa.schema([
pa.field('group', pa.int64()),
pa.field('key', pa.float64())
])
partitioning = ds.DirectoryPartitioning(schema)
assert len(partitioning.dictionaries) == 2
assert all(x is None for x in partitioning.dictionaries)
expr = partitioning.parse('/3/3.14/')
assert isinstance(expr, ds.Expression)
expected = (ds.field('group') == 3) & (ds.field('key') == 3.14)
assert expr.equals(expected)
with pytest.raises(pa.ArrowInvalid):
partitioning.parse('/prefix/3/aaa')
expr = partitioning.parse('/3/')
expected = ds.field('group') == 3
assert expr.equals(expected)
assert partitioning != ds.DirectoryPartitioning(schema, segment_encoding="none")
schema = pa.schema([
pa.field('alpha', pa.int64()),
pa.field('beta', pa.int64())
])
partitioning = ds.HivePartitioning(schema, null_fallback='xyz')
assert len(partitioning.dictionaries) == 2
assert all(x is None for x in partitioning.dictionaries)
expr = partitioning.parse('/alpha=0/beta=3/')
expected = (
(ds.field('alpha') == ds.scalar(0)) &
(ds.field('beta') == ds.scalar(3))
)
assert expr.equals(expected)
expr = partitioning.parse('/alpha=xyz/beta=3/')
expected = (
(ds.field('alpha').is_null() & (ds.field('beta') == ds.scalar(3)))
)
assert expr.equals(expected)
for shouldfail in ['/alpha=one/beta=2/', '/alpha=one/', '/beta=two/']:
with pytest.raises(pa.ArrowInvalid):
partitioning.parse(shouldfail)
assert partitioning != ds.HivePartitioning(schema, null_fallback='other')
schema = pa.schema([
pa.field('group', pa.int64()),
pa.field('key', pa.float64())
])
partitioning = ds.FilenamePartitioning(schema)
assert len(partitioning.dictionaries) == 2
assert all(x is None for x in partitioning.dictionaries)
expr = partitioning.parse('3_3.14_')
assert isinstance(expr, ds.Expression)
expected = (ds.field('group') == 3) & (ds.field('key') == 3.14)
assert expr.equals(expected)
with pytest.raises(pa.ArrowInvalid):
partitioning.parse('prefix_3_aaa_')
assert partitioning != ds.FilenamePartitioning(schema, segment_encoding="none")
schema = pa.schema([
pa.field('group', pa.int64()),
pa.field('key', pa.dictionary(pa.int8(), pa.string()))
])
partitioning = ds.DirectoryPartitioning(
schema, dictionaries={"key": pa.array(["first", "second", "third"])}
)
assert partitioning.dictionaries[0] is None
assert partitioning.dictionaries[1].to_pylist() == [
"first", "second", "third"]
assert partitioning != ds.DirectoryPartitioning(schema, dictionaries=None)
partitioning = ds.FilenamePartitioning(
pa.schema([
pa.field('group', pa.int64()),
pa.field('key', pa.dictionary(pa.int8(), pa.string()))
]),
dictionaries={
"key": pa.array(["first", "second", "third"]),
})
assert partitioning.dictionaries[0] is None
assert partitioning.dictionaries[1].to_pylist() == [
"first", "second", "third"]
# test partitioning roundtrip
table = pa.table([
pa.array(range(20)), pa.array(np.random.randn(20)),
pa.array(np.repeat(['a', 'b'], 10))],
names=["f1", "f2", "part"]
)
partitioning_schema = pa.schema([("part", pa.string())])
for klass in [ds.DirectoryPartitioning, ds.HivePartitioning,
ds.FilenamePartitioning]:
with tempfile.TemporaryDirectory() as tempdir:
partitioning = klass(partitioning_schema)
ds.write_dataset(table, tempdir,
format='ipc', partitioning=partitioning)
load_back = ds.dataset(tempdir, format='ipc',
partitioning=partitioning)
load_back_table = load_back.to_table()
assert load_back_table.equals(table)
# test invalid partitioning input
with tempfile.TemporaryDirectory() as tempdir:
partitioning = ds.DirectoryPartitioning(partitioning_schema)
ds.write_dataset(table, tempdir,
format='ipc', partitioning=partitioning)
load_back = None
with pytest.raises(ValueError,
match="Expected Partitioning or PartitioningFactory"):
load_back = ds.dataset(tempdir, format='ipc', partitioning=int(0))
assert load_back is None
def test_partitioning_pickling(pickle_module):
schema = pa.schema([
pa.field('i64', pa.int64()),
pa.field('f64', pa.float64())
])
parts = [
ds.DirectoryPartitioning(schema),
ds.HivePartitioning(schema),
ds.FilenamePartitioning(schema),
ds.DirectoryPartitioning(schema, segment_encoding="none"),
ds.FilenamePartitioning(schema, segment_encoding="none"),
ds.HivePartitioning(schema, segment_encoding="none", null_fallback="xyz"),
]
for part in parts:
assert pickle_module.loads(pickle_module.dumps(part)) == part
def test_expression_arithmetic_operators():
dataset = ds.dataset(pa.table({'a': [1, 2, 3], 'b': [2, 2, 2]}))
a = ds.field("a")
b = ds.field("b")
result = dataset.to_table(columns={
"a+1": a + 1,
"b-a": b - a,
"a*2": a * 2,
"a/b": a.cast("float64") / b,
})
expected = pa.table({
"a+1": [2, 3, 4], "b-a": [1, 0, -1],
"a*2": [2, 4, 6], "a/b": [0.5, 1.0, 1.5],
})
assert result.equals(expected)
def test_partition_keys():
a, b, c = [ds.field(f) == f for f in 'abc']
assert ds.get_partition_keys(a) == {'a': 'a'}
assert ds.get_partition_keys(a) == ds._get_partition_keys(a)
assert ds.get_partition_keys(a & b & c) == {f: f for f in 'abc'}
nope = ds.field('d') >= 3
assert ds.get_partition_keys(nope) == {}
assert ds.get_partition_keys(a & nope) == {'a': 'a'}
null = ds.field('a').is_null()
assert ds.get_partition_keys(null) == {'a': None}
@pytest.mark.parquet
def test_parquet_read_options():
opts1 = ds.ParquetReadOptions()
opts2 = ds.ParquetReadOptions(dictionary_columns=['a', 'b'])
opts3 = ds.ParquetReadOptions(coerce_int96_timestamp_unit="ms")
assert opts1.dictionary_columns == set()
assert opts2.dictionary_columns == {'a', 'b'}
assert opts1.coerce_int96_timestamp_unit == "ns"
assert opts3.coerce_int96_timestamp_unit == "ms"
assert opts1 == opts1
assert opts1 != opts2
assert opts1 != opts3
@pytest.mark.parquet
def test_parquet_file_format_read_options():
pff1 = ds.ParquetFileFormat()
pff2 = ds.ParquetFileFormat(dictionary_columns={'a'})
pff3 = ds.ParquetFileFormat(coerce_int96_timestamp_unit="s")
assert pff1.read_options == ds.ParquetReadOptions()
assert pff2.read_options == ds.ParquetReadOptions(dictionary_columns=['a'])
assert pff3.read_options == ds.ParquetReadOptions(
coerce_int96_timestamp_unit="s")
@pytest.mark.parquet
def test_parquet_scan_options():
opts1 = ds.ParquetFragmentScanOptions()
opts2 = ds.ParquetFragmentScanOptions(buffer_size=4096)
opts3 = ds.ParquetFragmentScanOptions(
buffer_size=2**13, use_buffered_stream=True)
opts4 = ds.ParquetFragmentScanOptions(buffer_size=2**13, pre_buffer=False)
opts5 = ds.ParquetFragmentScanOptions(
thrift_string_size_limit=123456,
thrift_container_size_limit=987654,)
opts6 = ds.ParquetFragmentScanOptions(
page_checksum_verification=True)
cache_opts = pa.CacheOptions(
hole_size_limit=2**10, range_size_limit=8*2**10, lazy=True)
opts7 = ds.ParquetFragmentScanOptions(pre_buffer=True, cache_options=cache_opts)
assert opts1.use_buffered_stream is False
assert opts1.buffer_size == 2**13
assert opts1.pre_buffer is True
assert opts1.thrift_string_size_limit == 100_000_000 # default in C++
assert opts1.thrift_container_size_limit == 1_000_000 # default in C++
assert opts1.page_checksum_verification is False
assert opts2.use_buffered_stream is False
assert opts2.buffer_size == 2**12
assert opts2.pre_buffer is True
assert opts3.use_buffered_stream is True
assert opts3.buffer_size == 2**13
assert opts3.pre_buffer is True
assert opts4.use_buffered_stream is False
assert opts4.buffer_size == 2**13
assert opts4.pre_buffer is False
assert opts5.thrift_string_size_limit == 123456
assert opts5.thrift_container_size_limit == 987654
assert opts6.page_checksum_verification is True
assert opts7.pre_buffer is True
assert opts7.cache_options == cache_opts
assert opts7.cache_options != opts1.cache_options
assert opts1 == opts1
assert opts1 != opts2
assert opts2 != opts3
assert opts3 != opts4
assert opts5 != opts1
assert opts6 != opts1
assert opts7 != opts1
def test_file_format_pickling(pickle_module):
formats = [
ds.IpcFileFormat(),
ds.CsvFileFormat(),
ds.CsvFileFormat(pa.csv.ParseOptions(delimiter='\t',
ignore_empty_lines=True)),
ds.CsvFileFormat(read_options=pa.csv.ReadOptions(
skip_rows=3, column_names=['foo'])),
ds.CsvFileFormat(read_options=pa.csv.ReadOptions(
skip_rows=3, block_size=2**20)),
ds.JsonFileFormat(),
ds.JsonFileFormat(
parse_options=pa.json.ParseOptions(newlines_in_values=True,
unexpected_field_behavior="ignore")),
ds.JsonFileFormat(read_options=pa.json.ReadOptions(
use_threads=False, block_size=14)),
]
try:
formats.append(ds.OrcFileFormat())
except ImportError:
pass
if pq is not None:
formats.extend([
ds.ParquetFileFormat(),
ds.ParquetFileFormat(dictionary_columns={'a'}),
ds.ParquetFileFormat(use_buffered_stream=True),
ds.ParquetFileFormat(
use_buffered_stream=True,
buffer_size=4096,
thrift_string_size_limit=123,
thrift_container_size_limit=456,
),
])
for file_format in formats:
assert pickle_module.loads(pickle_module.dumps(file_format)) == file_format
def test_fragment_scan_options_pickling(pickle_module):
options = [
ds.CsvFragmentScanOptions(),
ds.CsvFragmentScanOptions(
convert_options=pa.csv.ConvertOptions(strings_can_be_null=True)),
ds.CsvFragmentScanOptions(
read_options=pa.csv.ReadOptions(block_size=2**16)),
ds.JsonFragmentScanOptions(),
ds.JsonFragmentScanOptions(
pa.json.ParseOptions(newlines_in_values=False,
unexpected_field_behavior="error")),
ds.JsonFragmentScanOptions(
read_options=pa.json.ReadOptions(use_threads=True, block_size=512)),
]
if pq is not None:
options.extend([
ds.ParquetFragmentScanOptions(buffer_size=4096),
ds.ParquetFragmentScanOptions(pre_buffer=True),
])
for option in options:
assert pickle_module.loads(pickle_module.dumps(option)) == option
@pytest.mark.parametrize('paths_or_selector', [
fs.FileSelector('subdir', recursive=True),
[
'subdir/1/xxx/file0.parquet',
'subdir/2/yyy/file1.parquet',
]
])
@pytest.mark.parametrize('pre_buffer', [False, True])
@pytest.mark.parquet
def test_filesystem_factory(mockfs, paths_or_selector, pre_buffer):
format = ds.ParquetFileFormat(
read_options=ds.ParquetReadOptions(dictionary_columns={"str"}),
pre_buffer=pre_buffer
)
options = ds.FileSystemFactoryOptions('subdir')
options.partitioning = ds.DirectoryPartitioning(
pa.schema([
pa.field('group', pa.int32()),
pa.field('key', pa.string())
])
)
assert options.partition_base_dir == 'subdir'
assert options.selector_ignore_prefixes == ['.', '_']
assert options.exclude_invalid_files is False
factory = ds.FileSystemDatasetFactory(
mockfs, paths_or_selector, format, options
)
inspected_schema = factory.inspect()
assert factory.inspect().equals(pa.schema([
pa.field('i64', pa.int64()),
pa.field('f64', pa.float64()),
pa.field('str', pa.dictionary(pa.int32(), pa.string())),
pa.field('const', pa.int64()),
pa.field('struct', pa.struct({'a': pa.int64(),
'b': pa.string()})),
pa.field('group', pa.int32()),
pa.field('key', pa.string()),
]), check_metadata=False)
assert isinstance(factory.inspect_schemas(), list)
assert isinstance(factory.finish(inspected_schema),
ds.FileSystemDataset)
assert factory.root_partition.equals(ds.scalar(True))
dataset = factory.finish()
assert isinstance(dataset, ds.FileSystemDataset)
scanner = dataset.scanner()
expected_i64 = pa.array([0, 1, 2, 3, 4], type=pa.int64())
expected_f64 = pa.array([0, 1, 2, 3, 4], type=pa.float64())
expected_str = pa.DictionaryArray.from_arrays(
pa.array([0, 1, 2, 3, 4], type=pa.int32()),
pa.array("0 1 2 3 4".split(), type=pa.string())
)
expected_struct = pa.array([{'a': i % 3, 'b': str(i % 3)}
for i in range(5)])
iterator = scanner.scan_batches()
for (batch, fragment), group, key in zip(iterator, [1, 2], ['xxx', 'yyy']):
expected_group = pa.array([group] * 5, type=pa.int32())
expected_key = pa.array([key] * 5, type=pa.string())
expected_const = pa.array([group - 1] * 5, type=pa.int64())
# Can't compare or really introspect expressions from Python
assert fragment.partition_expression is not None
assert batch.num_columns == 7
assert batch[0].equals(expected_i64)
assert batch[1].equals(expected_f64)
assert batch[2].equals(expected_str)
assert batch[3].equals(expected_const)
assert batch[4].equals(expected_struct)
assert batch[5].equals(expected_group)
assert batch[6].equals(expected_key)
table = dataset.to_table()
assert isinstance(table, pa.Table)
assert len(table) == 10
assert table.num_columns == 7
@pytest.mark.parquet
def test_make_fragment(multisourcefs):
parquet_format = ds.ParquetFileFormat()
dataset = ds.dataset('/plain', filesystem=multisourcefs,
format=parquet_format)
for path in dataset.files:
fragment = parquet_format.make_fragment(path, multisourcefs)
assert fragment.row_groups == [0]