-
Notifications
You must be signed in to change notification settings - Fork 700
/
_write_parquet.py
983 lines (917 loc) · 38.5 KB
/
_write_parquet.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
"""Amazon PARQUET S3 Parquet Write Module (PRIVATE)."""
from __future__ import annotations
import logging
import math
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal, cast
import boto3
import pandas as pd
import pyarrow as pa
import pyarrow.lib
import pyarrow.parquet
from awswrangler import _utils, catalog, exceptions, typing
from awswrangler._arrow import _df_to_table
from awswrangler._config import apply_configs
from awswrangler._distributed import engine
from awswrangler.catalog._create import _create_parquet_table
from awswrangler.s3._fs import open_s3_object
from awswrangler.s3._read_parquet import _read_parquet_metadata
from awswrangler.s3._write import (
_COMPRESSION_2_EXT,
_get_chunk_file_path,
_get_file_path,
_get_write_table_args,
_S3WriteStrategy,
_validate_args,
)
from awswrangler.s3._write_concurrent import _WriteProxy
from awswrangler.typing import (
ArrowEncryptionConfiguration,
AthenaPartitionProjectionSettings,
BucketingInfoTuple,
GlueTableSettings,
_S3WriteDataReturnValue,
)
if TYPE_CHECKING:
from mypy_boto3_s3 import S3Client
_logger: logging.Logger = logging.getLogger(__name__)
@contextmanager
def _new_writer(
file_path: str,
compression: str | None,
pyarrow_additional_kwargs: dict[str, Any] | None,
schema: pa.Schema,
s3_client: "S3Client",
s3_additional_kwargs: dict[str, str] | None,
use_threads: bool | int,
encryption_configuration: ArrowEncryptionConfiguration | None,
) -> Iterator[pyarrow.parquet.ParquetWriter]:
writer: pyarrow.parquet.ParquetWriter | None = None
if not pyarrow_additional_kwargs:
pyarrow_additional_kwargs = {}
if "coerce_timestamps" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["coerce_timestamps"] = "ms"
if "flavor" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["flavor"] = "spark"
if "version" not in pyarrow_additional_kwargs:
# By default, use version 1.0 logical type set to maximize compatibility
pyarrow_additional_kwargs["version"] = "1.0"
if "use_dictionary" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["use_dictionary"] = True
if "write_statistics" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["write_statistics"] = True
if "schema" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["schema"] = schema
# When client side encryption materials are given
# construct file encryption properties object and pass it to pyarrow writer
encryption_properties = (
encryption_configuration["crypto_factory"].file_encryption_properties(
encryption_configuration["kms_connection_config"], encryption_configuration["encryption_config"]
)
if encryption_configuration
else None
)
with open_s3_object(
path=file_path,
mode="wb",
use_threads=use_threads,
s3_additional_kwargs=s3_additional_kwargs,
s3_client=s3_client,
) as f:
try:
writer = pyarrow.parquet.ParquetWriter(
where=f,
compression="NONE" if compression is None else compression,
encryption_properties=encryption_properties,
**pyarrow_additional_kwargs,
)
yield writer
finally:
if writer is not None and writer.is_open is True:
writer.close()
def _write_chunk(
file_path: str,
s3_client: "S3Client",
s3_additional_kwargs: dict[str, str] | None,
compression: str | None,
pyarrow_additional_kwargs: dict[str, str],
table: pa.Table,
offset: int,
chunk_size: int,
use_threads: bool | int,
encryption_configuration: ArrowEncryptionConfiguration | None,
) -> list[str]:
write_table_args = _get_write_table_args(pyarrow_additional_kwargs)
with _new_writer(
file_path=file_path,
compression=compression,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
schema=table.schema,
s3_client=s3_client,
s3_additional_kwargs=s3_additional_kwargs,
use_threads=use_threads,
encryption_configuration=encryption_configuration,
) as writer:
writer.write_table(table.slice(offset, chunk_size), **write_table_args)
return [file_path]
def _to_parquet_chunked(
file_path: str,
s3_client: "S3Client",
s3_additional_kwargs: dict[str, str] | None,
compression: str | None,
pyarrow_additional_kwargs: dict[str, Any],
table: pa.Table,
max_rows_by_file: int,
num_of_rows: int,
cpus: int,
encryption_configuration: ArrowEncryptionConfiguration | None,
) -> list[str]:
chunks: int = math.ceil(num_of_rows / max_rows_by_file)
use_threads: bool | int = cpus > 1
proxy: _WriteProxy = _WriteProxy(use_threads=use_threads)
for chunk in range(chunks):
offset: int = chunk * max_rows_by_file
write_path: str = _get_chunk_file_path(chunk, file_path)
proxy.write(
func=_write_chunk,
file_path=write_path,
s3_client=s3_client,
s3_additional_kwargs=s3_additional_kwargs,
compression=compression,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
table=table,
offset=offset,
chunk_size=max_rows_by_file,
use_threads=use_threads,
encryption_configuration=encryption_configuration,
)
return proxy.close() # blocking
@engine.dispatch_on_engine
def _to_parquet(
df: pd.DataFrame,
schema: pa.Schema,
index: bool,
compression: str | None,
compression_ext: str,
pyarrow_additional_kwargs: dict[str, Any],
cpus: int,
dtype: dict[str, str],
s3_client: "S3Client" | None,
s3_additional_kwargs: dict[str, str] | None,
use_threads: bool | int,
path: str | None = None,
path_root: str | None = None,
filename_prefix: str | None = None,
max_rows_by_file: int | None = 0,
bucketing: bool = False,
encryption_configuration: ArrowEncryptionConfiguration | None = None,
) -> list[str]:
s3_client = s3_client if s3_client else _utils.client(service_name="s3")
file_path = _get_file_path(
path_root=path_root,
path=path,
filename_prefix=filename_prefix,
compression_ext=compression_ext,
extension=".parquet",
)
table: pa.Table = _df_to_table(df, schema, index, dtype)
if max_rows_by_file is not None and max_rows_by_file > 0:
paths: list[str] = _to_parquet_chunked(
file_path=file_path,
s3_client=s3_client,
s3_additional_kwargs=s3_additional_kwargs,
compression=compression,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
table=table,
max_rows_by_file=max_rows_by_file,
num_of_rows=df.shape[0],
cpus=cpus,
encryption_configuration=encryption_configuration,
)
else:
write_table_args = _get_write_table_args(pyarrow_additional_kwargs)
with _new_writer(
file_path=file_path,
compression=compression,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
schema=table.schema,
s3_client=s3_client,
s3_additional_kwargs=s3_additional_kwargs,
use_threads=use_threads,
encryption_configuration=encryption_configuration,
) as writer:
writer.write_table(table, **write_table_args)
paths = [file_path]
return paths
class _S3ParquetWriteStrategy(_S3WriteStrategy):
@property
def _write_to_s3_func(self) -> Callable[..., list[str]]:
return _to_parquet
def _write_to_s3(
self,
df: pd.DataFrame,
schema: pa.Schema,
index: bool,
compression: str | None,
compression_ext: str,
pyarrow_additional_kwargs: dict[str, Any],
cpus: int,
dtype: dict[str, str],
s3_client: "S3Client" | None,
s3_additional_kwargs: dict[str, str] | None,
use_threads: bool | int,
path: str | None = None,
path_root: str | None = None,
filename_prefix: str | None = None,
max_rows_by_file: int | None = 0,
bucketing: bool = False,
encryption_configuration: ArrowEncryptionConfiguration | None = None,
) -> list[str]:
return _to_parquet(
df=df,
schema=schema,
index=index,
compression=compression,
compression_ext=compression_ext,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
cpus=cpus,
dtype=dtype,
s3_client=s3_client,
s3_additional_kwargs=s3_additional_kwargs,
use_threads=use_threads,
path=path,
path_root=path_root,
filename_prefix=filename_prefix,
max_rows_by_file=max_rows_by_file,
bucketing=bucketing,
encryption_configuration=encryption_configuration,
)
def _create_glue_table(
self,
database: str,
table: str,
path: str,
columns_types: dict[str, str],
table_type: str | None = None,
partitions_types: dict[str, str] | None = None,
bucketing_info: BucketingInfoTuple | None = None,
catalog_id: str | None = None,
compression: str | None = None,
description: str | None = None,
parameters: dict[str, str] | None = None,
columns_comments: dict[str, str] | None = None,
columns_parameters: dict[str, dict[str, str]] | None = None,
mode: str = "overwrite",
catalog_versioning: bool = False,
athena_partition_projection_settings: AthenaPartitionProjectionSettings | None = None,
boto3_session: boto3.Session | None = None,
catalog_table_input: dict[str, Any] | None = None,
) -> None:
return _create_parquet_table(
database=database,
table=table,
path=path,
columns_types=columns_types,
table_type=table_type,
partitions_types=partitions_types,
bucketing_info=bucketing_info,
catalog_id=catalog_id,
compression=compression,
description=description,
parameters=parameters,
columns_comments=columns_comments,
columns_parameters=columns_parameters,
mode=mode,
catalog_versioning=catalog_versioning,
athena_partition_projection_settings=athena_partition_projection_settings,
boto3_session=boto3_session,
catalog_table_input=catalog_table_input,
)
def _add_glue_partitions(
self,
database: str,
table: str,
partitions_values: dict[str, list[str]],
bucketing_info: BucketingInfoTuple | None = None,
catalog_id: str | None = None,
compression: str | None = None,
boto3_session: boto3.Session | None = None,
columns_types: dict[str, str] | None = None,
partitions_parameters: dict[str, str] | None = None,
) -> None:
return catalog.add_parquet_partitions(
database=database,
table=table,
partitions_values=partitions_values,
bucketing_info=bucketing_info,
compression=compression,
boto3_session=boto3_session,
catalog_id=catalog_id,
columns_types=columns_types,
partitions_parameters=partitions_parameters,
)
@apply_configs
@_utils.validate_distributed_kwargs(
unsupported_kwargs=["boto3_session", "s3_additional_kwargs"],
)
def to_parquet(
df: pd.DataFrame,
path: str | None = None,
index: bool = False,
compression: str | None = "snappy",
pyarrow_additional_kwargs: dict[str, Any] | None = None,
max_rows_by_file: int | None = None,
use_threads: bool | int = True,
boto3_session: boto3.Session | None = None,
s3_additional_kwargs: dict[str, Any] | None = None,
sanitize_columns: bool = False,
dataset: bool = False,
filename_prefix: str | None = None,
partition_cols: list[str] | None = None,
bucketing_info: BucketingInfoTuple | None = None,
concurrent_partitioning: bool = False,
mode: Literal["append", "overwrite", "overwrite_partitions"] | None = None,
catalog_versioning: bool = False,
schema_evolution: bool = True,
database: str | None = None,
table: str | None = None,
glue_table_settings: GlueTableSettings | None = None,
dtype: dict[str, str] | None = None,
athena_partition_projection_settings: typing.AthenaPartitionProjectionSettings | None = None,
catalog_id: str | None = None,
encryption_configuration: ArrowEncryptionConfiguration | None = None,
) -> _S3WriteDataReturnValue:
"""Write Parquet file or dataset on Amazon S3.
The concept of Dataset goes beyond the simple idea of ordinary files and enable more
complex features like partitioning and catalog integration (Amazon Athena/AWS Glue Catalog).
Note
----
This operation may mutate the original pandas DataFrame in-place. To avoid this behaviour
please pass in a deep copy instead (i.e. `df.copy()`)
Note
----
If `database` and `table` arguments are passed, the table name and all column names
will be automatically sanitized using `wr.catalog.sanitize_table_name` and `wr.catalog.sanitize_column_name`.
Please, pass `sanitize_columns=True` to enforce this behaviour always.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
df
Pandas DataFrame https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
path
S3 path (for file e.g. ``s3://bucket/prefix/filename.parquet``) (for dataset e.g. ``s3://bucket/prefix``).
Required if dataset=False or when dataset=True and creating a new dataset
index
True to store the DataFrame index in file, otherwise False to ignore it.
Is not supported in conjunction with `max_rows_by_file` when running the library with Ray/Modin.
compression
Compression style (``None``, ``snappy``, ``gzip``, ``zstd``).
pyarrow_additional_kwargs
Additional parameters forwarded to pyarrow.
e.g. pyarrow_additional_kwargs={'coerce_timestamps': 'ns', 'use_deprecated_int96_timestamps': False,
'allow_truncated_timestamps'=False}
max_rows_by_file
Max number of rows in each file.
Default is None i.e. don't split the files.
(e.g. 33554432, 268435456)
Is not supported in conjunction with `index=True` when running the library with Ray/Modin.
use_threads
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
If integer is provided, specified number is used.
boto3_session
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
s3_additional_kwargs
Forwarded to botocore requests.
e.g. s3_additional_kwargs={'ServerSideEncryption': 'aws:kms', 'SSEKMSKeyId': 'YOUR_KMS_KEY_ARN'}
sanitize_columns
True to sanitize columns names (using `wr.catalog.sanitize_table_name` and `wr.catalog.sanitize_column_name`)
or False to keep it as is.
True value behaviour is enforced if `database` and `table` arguments are passed.
dataset
If True store a parquet dataset instead of a ordinary file(s)
If True, enable all follow arguments:
partition_cols, mode, database, table, description, parameters, columns_comments, concurrent_partitioning,
catalog_versioning, projection_params, catalog_id, schema_evolution.
filename_prefix
If dataset=True, add a filename prefix to the output files.
partition_cols
List of column names that will be used to create partitions. Only takes effect if dataset=True.
bucketing_info
Tuple consisting of the column names used for bucketing as the first element and the number of buckets as the
second element.
Only `str`, `int` and `bool` are supported as column data types for bucketing.
concurrent_partitioning
If True will increase the parallelism level during the partitions writing. It will decrease the
writing time and increase the memory usage.
https://aws-sdk-pandas.readthedocs.io/en/3.11.0/tutorials/022%20-%20Writing%20Partitions%20Concurrently.html
mode
``append`` (Default), ``overwrite``, ``overwrite_partitions``. Only takes effect if dataset=True.
For details check the related tutorial:
https://aws-sdk-pandas.readthedocs.io/en/3.11.0/tutorials/004%20-%20Parquet%20Datasets.html
catalog_versioning
If True and `mode="overwrite"`, creates an archived version of the table catalog before updating it.
schema_evolution
If True allows schema evolution (new or missing columns), otherwise a exception will be raised. True by default.
(Only considered if dataset=True and mode in ("append", "overwrite_partitions"))
Related tutorial:
https://aws-sdk-pandas.readthedocs.io/en/3.11.0/tutorials/014%20-%20Schema%20Evolution.html
database
Glue/Athena catalog: Database name.
table
Glue/Athena catalog: Table name.
glue_table_settings
Settings for writing to the Glue table.
dtype
Dictionary of columns names and Athena/Glue types to be casted.
Useful when you have columns with undetermined or mixed data types.
(e.g. {'col name': 'bigint', 'col2 name': 'int'})
athena_partition_projection_settings
Parameters of the Athena Partition Projection
(https://docs.aws.amazon.com/athena/latest/ug/partition-projection.html).
AthenaPartitionProjectionSettings is a `TypedDict`, meaning the passed parameter can be instantiated either as
an instance of AthenaPartitionProjectionSettings or as a regular Python dict.
Following projection parameters are supported:
.. list-table:: Projection Parameters
:header-rows: 1
* - Name
- Type
- Description
* - projection_types
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections types.
Valid types: "enum", "integer", "date", "injected"
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': 'enum', 'col2_name': 'integer'})
* - projection_ranges
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections ranges.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '0,10', 'col2_name': '-1,8675309'})
* - projection_values
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections values.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': 'A,B,Unknown', 'col2_name': 'foo,boo,bar'})
* - projection_intervals
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections intervals.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '1', 'col2_name': '5'})
* - projection_digits
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections digits.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '1', 'col2_name': '2'})
* - projection_formats
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections formats.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_date': 'yyyy-MM-dd', 'col2_timestamp': 'yyyy-MM-dd HH:mm:ss'})
* - projection_storage_location_template
- Optional[str]
- Value which is allows Athena to properly map partition values if the S3 file locations do not follow
a typical `.../column=value/...` pattern.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-setting-up.html
(e.g. s3://bucket/table_root/a=${a}/${b}/some_static_subdirectory/${c}/)
catalog_id
The ID of the Data Catalog from which to retrieve Databases.
If none is provided, the AWS account ID is used by default.
encryption_configuration
For Arrow client-side encryption provide materials as follows {'crypto_factory': pyarrow.parquet.encryption.CryptoFactory,
'kms_connection_config': pyarrow.parquet.encryption.KmsConnectionConfig,
'encryption_config': pyarrow.parquet.encryption.EncryptionConfiguration}
see: https://arrow.apache.org/docs/python/parquet.html#parquet-modular-encryption-columnar-encryption
Client Encryption is not supported in distributed mode.
Returns
-------
Dictionary with:
* 'paths': List of all stored files paths on S3.
* 'partitions_values': Dictionary of partitions added with keys as S3 path locations and values as a list of partitions values as str.
Examples
--------
Writing single file
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... path='s3://bucket/prefix/my_file.parquet',
... )
{
'paths': ['s3://bucket/prefix/my_file.parquet'],
'partitions_values': {}
}
Writing single file encrypted with a KMS key
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... path='s3://bucket/prefix/my_file.parquet',
... s3_additional_kwargs={
... 'ServerSideEncryption': 'aws:kms',
... 'SSEKMSKeyId': 'YOUR_KMS_KEY_ARN'
... }
... )
{
'paths': ['s3://bucket/prefix/my_file.parquet'],
'partitions_values': {}
}
Writing partitioned dataset
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({
... 'col': [1, 2, 3],
... 'col2': ['A', 'A', 'B']
... }),
... path='s3://bucket/prefix',
... dataset=True,
... partition_cols=['col2']
... )
{
'paths': ['s3://.../col2=A/x.parquet', 's3://.../col2=B/y.parquet'],
'partitions_values: {
's3://.../col2=A/': ['A'],
's3://.../col2=B/': ['B']
}
}
Writing partitioned dataset with partition projection
>>> import awswrangler as wr
>>> import pandas as pd
>>> from datetime import datetime
>>> dt = lambda x: datetime.strptime(x, "%Y-%m-%d").date()
>>> wr.s3.to_parquet(
... df=pd.DataFrame({
... "id": [1, 2, 3],
... "value": [1000, 1001, 1002],
... "category": ['A', 'B', 'C'],
... }),
... path='s3://bucket/prefix',
... dataset=True,
... partition_cols=['value', 'category'],
... athena_partition_projection_settings={
... "projection_types": {
... "value": "integer",
... "category": "enum",
... },
... "projection_ranges": {
... "value": "1000,2000",
... "category": "A,B,C",
... },
... },
... )
{
'paths': [
's3://.../value=1000/category=A/x.snappy.parquet', ...
],
'partitions_values': {
's3://.../value=1000/category=A/': [
'1000',
'A',
], ...
}
}
Writing bucketed dataset
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({
... 'col': [1, 2, 3],
... 'col2': ['A', 'A', 'B']
... }),
... path='s3://bucket/prefix',
... dataset=True,
... bucketing_info=(["col2"], 2)
... )
{
'paths': ['s3://.../x_bucket-00000.csv', 's3://.../col2=B/x_bucket-00001.csv'],
'partitions_values: {}
}
Writing dataset to S3 with metadata on Athena/Glue Catalog.
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({
... 'col': [1, 2, 3],
... 'col2': ['A', 'A', 'B']
... }),
... path='s3://bucket/prefix',
... dataset=True,
... partition_cols=['col2'],
... database='default', # Athena/Glue database
... table='my_table' # Athena/Glue table
... )
{
'paths': ['s3://.../col2=A/x.parquet', 's3://.../col2=B/y.parquet'],
'partitions_values: {
's3://.../col2=A/': ['A'],
's3://.../col2=B/': ['B']
}
}
Writing dataset casting empty column data type
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.s3.to_parquet(
... df=pd.DataFrame({
... 'col': [1, 2, 3],
... 'col2': ['A', 'A', 'B'],
... 'col3': [None, None, None]
... }),
... path='s3://bucket/prefix',
... dataset=True,
... database='default', # Athena/Glue database
... table='my_table' # Athena/Glue table
... dtype={'col3': 'date'}
... )
{
'paths': ['s3://.../x.parquet'],
'partitions_values: {}
}
"""
glue_table_settings = cast(
GlueTableSettings,
glue_table_settings if glue_table_settings else {},
)
table_type = glue_table_settings.get("table_type")
description = glue_table_settings.get("description")
parameters = glue_table_settings.get("parameters")
columns_comments = glue_table_settings.get("columns_comments")
columns_parameters = glue_table_settings.get("columns_parameters")
regular_partitions = glue_table_settings.get("regular_partitions", True)
_validate_args(
df=df,
table=table,
database=database,
dataset=dataset,
path=path,
partition_cols=partition_cols,
bucketing_info=bucketing_info,
mode=mode,
description=description,
parameters=parameters,
columns_comments=columns_comments,
columns_parameters=columns_parameters,
execution_engine=engine.get(),
)
# Evaluating compression
if _COMPRESSION_2_EXT.get(compression, None) is None:
raise exceptions.InvalidCompression(f"{compression} is invalid, please use None, 'snappy', 'gzip' or 'zstd'.")
compression_ext: str = _COMPRESSION_2_EXT[compression]
# Pyarrow defaults
if not pyarrow_additional_kwargs:
pyarrow_additional_kwargs = {}
if "coerce_timestamps" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["coerce_timestamps"] = "ms"
if "flavor" not in pyarrow_additional_kwargs:
pyarrow_additional_kwargs["flavor"] = "spark"
strategy = _S3ParquetWriteStrategy()
return strategy.write(
df=df,
path=path,
index=index,
compression=compression,
pyarrow_additional_kwargs=pyarrow_additional_kwargs,
max_rows_by_file=max_rows_by_file,
use_threads=use_threads,
boto3_session=boto3_session,
s3_additional_kwargs=s3_additional_kwargs,
sanitize_columns=sanitize_columns,
dataset=dataset,
filename_prefix=filename_prefix,
partition_cols=partition_cols,
bucketing_info=bucketing_info,
concurrent_partitioning=concurrent_partitioning,
mode=mode,
catalog_versioning=catalog_versioning,
schema_evolution=schema_evolution,
database=database,
table=table,
description=description,
parameters=parameters,
columns_comments=columns_comments,
columns_parameters=columns_parameters,
table_type=table_type,
regular_partitions=regular_partitions,
dtype=dtype,
athena_partition_projection_settings=athena_partition_projection_settings,
catalog_id=catalog_id,
compression_ext=compression_ext,
encryption_configuration=encryption_configuration,
)
@apply_configs
@_utils.validate_distributed_kwargs(
unsupported_kwargs=["boto3_session"],
)
def store_parquet_metadata(
path: str,
database: str,
table: str,
catalog_id: str | None = None,
path_suffix: str | None = None,
path_ignore_suffix: str | list[str] | None = None,
ignore_empty: bool = True,
ignore_null: bool = False,
dtype: dict[str, str] | None = None,
sampling: float = 1.0,
dataset: bool = False,
use_threads: bool | int = True,
description: str | None = None,
parameters: dict[str, str] | None = None,
columns_comments: dict[str, str] | None = None,
compression: str | None = None,
mode: Literal["append", "overwrite"] = "overwrite",
catalog_versioning: bool = False,
regular_partitions: bool = True,
athena_partition_projection_settings: typing.AthenaPartitionProjectionSettings | None = None,
s3_additional_kwargs: dict[str, Any] | None = None,
boto3_session: boto3.Session | None = None,
) -> tuple[dict[str, str], dict[str, str] | None, dict[str, list[str]] | None]:
"""Infer and store parquet metadata on AWS Glue Catalog.
Infer Apache Parquet file(s) metadata from a received S3 prefix
And then stores it on AWS Glue Catalog including all inferred partitions
(No need for 'MSCK REPAIR TABLE')
The concept of Dataset goes beyond the simple idea of files and enables more
complex features like partitioning and catalog integration (AWS Glue Catalog).
This function accepts Unix shell-style wildcards in the path argument.
* (matches everything), ? (matches any single character),
[seq] (matches any character in seq), [!seq] (matches any character not in seq).
If you want to use a path which includes Unix shell-style wildcard characters (`*, ?, []`),
you can use `glob.escape(path)` before passing the path to this function.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
path
S3 prefix (accepts Unix shell-style wildcards) (e.g. s3://bucket/prefix).
table
Glue/Athena catalog: Table name.
database
AWS Glue Catalog database name.
catalog_id
The ID of the Data Catalog from which to retrieve Databases.
If none is provided, the AWS account ID is used by default.
path_suffix
Suffix or List of suffixes for filtering S3 keys.
path_ignore_suffix
Suffix or List of suffixes for S3 keys to be ignored.
ignore_empty
Ignore files with 0 bytes.
ignore_null
Ignore columns with null type.
dtype
Dictionary of columns names and Athena/Glue types to be casted.
Useful when you have columns with undetermined data types as partitions columns.
(e.g. {'col name': 'bigint', 'col2 name': 'int'})
sampling
Random sample ratio of files that will have the metadata inspected.
Must be `0.0 < sampling <= 1.0`.
The higher, the more accurate.
The lower, the faster.
dataset
If True read a parquet dataset instead of simple file(s) loading all the related partitions as columns.
use_threads
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
If integer is provided, specified number is used.
description
Glue/Athena catalog: Table description
parameters
Glue/Athena catalog: Key/value pairs to tag the table.
columns_comments
Glue/Athena catalog:
Columns names and the related comments (e.g. {'col0': 'Column 0.', 'col1': 'Column 1.', 'col2': 'Partition.'}).
compression
Compression style (``None``, ``snappy``, ``gzip``, etc).
mode
'overwrite' to recreate any possible existing table or 'append' to keep any possible existing table.
catalog_versioning
If True and `mode="overwrite"`, creates an archived version of the table catalog before updating it.
regular_partitions
Create regular partitions (Non projected partitions) on Glue Catalog.
Disable when you will work only with Partition Projection.
Keep enabled even when working with projections is useful to keep
Redshift Spectrum working with the regular partitions.
athena_partition_projection_settings
Parameters of the Athena Partition Projection
(https://docs.aws.amazon.com/athena/latest/ug/partition-projection.html).
AthenaPartitionProjectionSettings is a `TypedDict`, meaning the passed parameter can be instantiated either as
an instance of AthenaPartitionProjectionSettings or as a regular Python dict.
Following projection parameters are supported:
.. list-table:: Projection Parameters
:header-rows: 1
* - Name
- Type
- Description
* - projection_types
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections types.
Valid types: "enum", "integer", "date", "injected"
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': 'enum', 'col2_name': 'integer'})
* - projection_ranges
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections ranges.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '0,10', 'col2_name': '-1,8675309'})
* - projection_values
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections values.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': 'A,B,Unknown', 'col2_name': 'foo,boo,bar'})
* - projection_intervals
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections intervals.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '1', 'col2_name': '5'})
* - projection_digits
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections digits.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_name': '1', 'col2_name': '2'})
* - projection_formats
- Optional[Dict[str, str]]
- Dictionary of partitions names and Athena projections formats.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-supported-types.html
(e.g. {'col_date': 'yyyy-MM-dd', 'col2_timestamp': 'yyyy-MM-dd HH:mm:ss'})
* - projection_storage_location_template
- Optional[str]
- Value which is allows Athena to properly map partition values if the S3 file locations do not follow
a typical `.../column=value/...` pattern.
https://docs.aws.amazon.com/athena/latest/ug/partition-projection-setting-up.html
(e.g. s3://bucket/table_root/a=${a}/${b}/some_static_subdirectory/${c}/)
s3_additional_kwargs
Forwarded to botocore requests.
e.g. s3_additional_kwargs={'ServerSideEncryption': 'aws:kms', 'SSEKMSKeyId': 'YOUR_KMS_KEY_ARN'}
boto3_session
The default boto3 session will be used if boto3_session receive None.
Returns
-------
The metadata used to create the Glue Table.
columns_types: Dictionary with keys as column names and values as
data types (e.g. {'col0': 'bigint', 'col1': 'double'}). /
partitions_types: Dictionary with keys as partition names
and values as data types (e.g. {'col2': 'date'}). /
partitions_values: Dictionary with keys as S3 path locations and values as a
list of partitions values as str (e.g. {'s3://bucket/prefix/y=2020/m=10/': ['2020', '10']}).
Examples
--------
Reading all Parquet files metadata under a prefix
>>> import awswrangler as wr
>>> columns_types, partitions_types, partitions_values = wr.s3.store_parquet_metadata(
... path='s3://bucket/prefix/',
... database='...',
... table='...',
... dataset=True
... )
"""
columns_types: dict[str, str]
partitions_types: dict[str, str] | None
partitions_values: dict[str, list[str]] | None
columns_types, partitions_types, partitions_values = _read_parquet_metadata(
path=path,
dtype=dtype,
sampling=sampling,
dataset=dataset,
path_suffix=path_suffix,
path_ignore_suffix=path_ignore_suffix,
ignore_empty=ignore_empty,
ignore_null=ignore_null,
use_threads=use_threads,
s3_additional_kwargs=s3_additional_kwargs,
boto3_session=boto3_session,
)
_logger.debug("Resolved columns_types: %s", columns_types)
_logger.debug("Resolved partitions_types: %s", partitions_types)
_logger.debug("Resolved partitions_values: %s", partitions_values)
catalog.create_parquet_table(
database=database,
table=table,
path=path,
columns_types=columns_types,
partitions_types=partitions_types,
description=description,
parameters=parameters,
columns_comments=columns_comments,
mode=mode,
compression=compression,
catalog_versioning=catalog_versioning,
athena_partition_projection_settings=athena_partition_projection_settings,
boto3_session=boto3_session,
catalog_id=catalog_id,
)
if (partitions_types is not None) and (partitions_values is not None) and (regular_partitions is True):
catalog.add_parquet_partitions(
database=database,
table=table,
partitions_values=partitions_values,
compression=compression,
boto3_session=boto3_session,
catalog_id=catalog_id,
columns_types=columns_types,
)
return columns_types, partitions_types, partitions_values