-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
1596 lines (1392 loc) · 53.1 KB
/
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
import datetime as dt
import os
import re
import tempfile
import typing as t
import duckdb as _duckdb
import pandas as pd
import polars.selectors as cs
import psutil
import pyarrow as pa
import pyarrow.dataset as pds
import tqdm
from fsspec import AbstractFileSystem
from .filesystem import FileSystem, clear_cache
from .helpers.datetime import get_timestamp_column
from .helpers.misc import sql2pyarrow_filter
from .helpers.polars import pl as _pl
from .io import Writer
from .metadata import ParquetDatasetMetadata, PydalaDatasetMetadata
from .schema import replace_schema # from .optimize import Optimize
from .schema import shrink_large_string
from .table import PydalaTable
class BaseDataset:
def __init__(
self,
path: str,
name: str | None = None,
schema: pa.Schema | None = None,
filesystem: AbstractFileSystem | None = None,
bucket: str | None = None,
partitioning: str | list[str] | None = None,
format: str | None = "parquet",
cached: bool = False,
timestamp_column: str | None = None,
ddb_con: _duckdb.DuckDBPyConnection | None = None,
**fs_kwargs,
):
self._path = path
self._schema = schema
self._bucket = bucket
self._cached = cached
self._format = format
self._base_filesystem = filesystem
if cached:
cache_storage = fs_kwargs.pop(
"cache_storage", tempfile.mkdtemp(prefix="pydala2_")
)
# cache_storage = os.path.join(cache_storage, path)
else:
cache_storage = None
self._filesystem = FileSystem(
bucket=bucket,
fs=filesystem,
cached=cached,
cache_storage=cache_storage,
**fs_kwargs,
)
self.table = None
self._makedirs()
if name is None:
self.name = os.path.basename(path)
else:
self.name = name
if ddb_con is None:
ddb_con = _duckdb.connect()
self.ddb_con = ddb_con
# enable object caching for e.g. parquet metadata
self.ddb_con.execute(
f"""PRAGMA enable_object_cache;
SET THREADS={psutil.cpu_count() * 2};"""
)
self._timestamp_column = timestamp_column
# self.load_files()
# NOTE: Set partitioning manually, if not set, try to infer it
if partitioning is None:
# try to infer partitioning
try:
if any(["=" in obj for obj in self.fs.ls(self._path)]):
partitioning = "hive"
except FileNotFoundError as e:
_ = e
partitioning = None
else:
if partitioning == "ignore":
partitioning = None
self._partitioning = partitioning
# if self.has_files:
# if partitioning == "ignore":
# self._partitioning = None
# elif partitioning is None and "=" in self._files[0]:
# self._partitioning = "hive"
# else:
# self._partitioning = partitioning
# else:
# self._partitioning = partitioning
try:
self.load()
except Exception as e:
_ = e
pass
# @abstactmethod
def load_files(self) -> None:
"""
Loads the files from the specified path with the specified format.
This method populates the `_files` attribute with a list of file names
that match the specified format in the specified path.
Returns:
None
"""
self.clear_cache()
self._files = [
fn.replace(self._path, "").lstrip("/")
for fn in sorted(
self._filesystem.glob(os.path.join(self._path, f"**/*.{self._format}"))
)
]
def _makedirs(self):
if self._filesystem.exists(self._path):
return
try:
self._filesystem.mkdirs(self._path)
except Exception as e:
_ = e
self._filesystem.touch(os.path.join(self._path, "tmp.delete"))
self._filesystem.rm(os.path.join(self._path, "tmp.delete"))
@property
def files(self) -> list:
"""
Returns a list of files in the dataset.
If the files have not been loaded yet, this method will call the `load_files` method to load them.
Returns:
list: A list of files in the dataset.
"""
if not hasattr(self, "_files"):
self.load_files()
return self._files
@property
def path(self):
return self._path
@property
def has_files(self):
"""
Returns True if the dataset has files, False otherwise.
"""
return len(self.files) > 0
def load(self):
"""
Loads the dataset from the specified path and initializes the PydalaTable.
Returns:
None
"""
if self.has_files:
self._arrow_dataset = pds.dataset(
self._path,
schema=self._schema,
filesystem=self._filesystem,
format=self._format,
partitioning=self._partitioning,
)
self.table = PydalaTable(result=self._arrow_dataset, ddb_con=self.ddb_con)
# self.ddb_con.register("arrow__dataset", self._arrow_parquet_dataset)
if self._timestamp_column is None:
self._timestamp_columns = get_timestamp_column(self.table.pl.head(10))
if len(self._timestamp_columns) > 0:
self._timestamp_column = self._timestamp_columns[0]
if self._timestamp_column is not None:
tz = self.schema.field(self._timestamp_column).type.tz
self._tz = tz
if tz is not None:
self.ddb_con.execute(f"SET TimeZone='{tz}'")
else:
self._tz = None
self.ddb_con.register(f"{self.name}", self._arrow_dataset)
def clear_cache(self) -> None:
"""
Clears the cache for the dataset.
This method clears the cache for the dataset by calling the `clear_cache` function
for both the `_filesystem` and `_base_filesystem` attributes.
Returns:
None
"""
if hasattr(self._filesystem, "fs"):
clear_cache(self._filesystem.fs)
clear_cache(self._filesystem)
clear_cache(self._base_filesystem)
@property
def schema(self):
"""
Returns the schema of the dataset.
If the schema has not been cached, it retrieves the schema from the underlying Arrow dataset.
Returns:
pyarrow.Schema: The schema of the dataset.
"""
if self.is_loaded:
if not hasattr(self, "_schema") or self._schema is None:
self._schema = self._arrow_dataset.schema
return self._schema
@property
def is_loaded(self) -> bool:
"""
Returns True if the dataset has been loaded into memory, False otherwise.
"""
return hasattr(self, "_arrow_dataset")
@property
def columns(self) -> list:
"""
Returns a list of column names for the dataset, including both schema and partitioning columns.
Returns:
list: A list of column names.
"""
if self.is_loaded:
return self.schema.names
@property
def fs(self):
"""
Returns the filesystem associated with the dataset.
Returns:
The filesystem object associated with the dataset.
"""
return self._filesystem
@property
def t(self):
"""
Returns the table associated with the dataset.
Returns:
The table associated with the dataset.
"""
return self.table
def count_rows(self) -> int:
"""
Returns the number of rows in the dataset.
If the dataset is not loaded, it prints an error message and returns 0.
Returns:
int: The number of rows in the dataset.
"""
if self.is_loaded:
return self._arrow_dataset.count_rows()
else:
# print(f"No dataset loaded yet. Run {self}.load()")
return 0
@property
def num_rows(self) -> int:
"""
Returns the number of rows in the dataset.
If the dataset is not loaded, it prints an error message and returns 0.
Returns:
int: The number of rows in the dataset.
"""
return self.count_rows()
@property
def num_columns(self) -> int:
"""
Returns the number of columns in the dataset.
If the dataset is not loaded, it prints an error message and returns 0.
Returns:
int: The number of columns in the dataset.
"""
if self.is_loaded:
return len(self.schema.names)
else:
# print(f"No dataset loaded yet. Run {self}.load()")
return 0
def delete_files(self, files: str | list[str]):
"""
Deletes the specified files from the dataset.
Args:
files (str | list[str], optional): The file(s) to be deleted. If not provided, all files in the dataset
will be deleted. Defaults to None.
"""
if self._path not in files[0]:
files = [os.path.join(self._path, fn) for fn in files]
self._filesystem.rm(files, recursive=True)
# self.load(reload=True)
def vacuum(self):
"""
Deletes all files in the dataset.
"""
self.delete_files(self._files)
self.delete_metadata_files()
@property
def partitioning_schema(self) -> pa.Schema:
"""
Returns the partitioning schema of the dataset.
If the dataset has files and the partitioning schema has not been
computed yet, it will be computed and cached. If the dataset is not
loaded, an empty schema will be returned.
Returns:
pa.Schema: The partitioning schema of the dataset.
"""
if self.is_loaded:
if hasattr(self._arrow_dataset, "partitioning"):
if not hasattr(self, "_partitioning_schema"):
if self.is_loaded:
self._partitioning_schema = (
self._arrow_dataset.partitioning.schema
)
else:
return pa.schema([])
return self._partitioning_schema
@property
def partition_names(self) -> list:
"""
Returns a list of partitioning names.
Returns:
list: A list of partitioning names.
"""
if self.is_loaded:
if not hasattr(self, "_partition_names") and hasattr(
self._arrow_dataset, "partitioning"
):
self._partition_names = self._arrow_dataset.partitioning.schema.names
return self._partition_names
@property
def partition_values(self) -> dict:
"""
Returns a list of partitioning values.
Returns:
list: A list of partitioning values.
"""
if self.is_loaded:
if hasattr(self._arrow_dataset, "partitioning"):
self._partition_values = dict(
zip(
self._arrow_dataset.partitioning.schema.names,
[
pa_list.to_pylist()
for pa_list in self._arrow_dataset.partitioning.dictionaries
],
)
)
else:
# print(f"No dataset loaded yet. Run {self}.load()")
return []
return self._partition_values
@property
def partitions(self) -> pa.Table:
"""
Returns the partitions of the dataset as a pyarrow Table.
If the dataset has files and is partitioned, it retrieves the partitions
based on the partitioning schema. If the dataset is not loaded, an empty
pyarrow Table is returned.
Returns:
pa.Table: The partitions of the dataset as a pyarrow Table.
"""
if self.is_loaded:
if self._partitioning:
if not hasattr(self, "_partitions") and hasattr(
self._arrow_dataset, "partitioning"
):
self._partitions = sorted(
{
re.findall(
r"/".join(
[
f"{name}=([^/]+)"
for name in self._arrow_dataset.partitioning.schema.names
]
),
f,
)[0]
for f in self.files
}
)
self._partitions = (
_pl.DataFrame(
self._partitions,
schema=self._arrow_dataset.partitioning.schema.names,
orient="row",
)
.to_arrow()
.cast(self._arrow_dataset.partitioning.schema)
)
return self._partitions
def _filter_duckdb(self, filter_expr: str) -> _duckdb.DuckDBPyRelation:
"""
Filters the DuckDBPyRelation table based on the given filter expression.
Args:
filter_expr (str): The filter expression to apply.
Returns:
_duckdb.DuckDBPyRelation: The filtered DuckDBPyRelation table.
"""
return self.table.ddb.filter(filter_expr)
def _filter_arrow_dataset(
self, filter_expr: str | pds.Expression
) -> pds.FileSystemDataset:
"""
Filters a PyArrow Parquet dataset based on the provided filter expression.
Args:
filter_expr (str | pds.Expression): The filter expression to be applied to the dataset.
It can be either a string representation of a filter expression or a PyArrow
Expression object.
Returns:
pds.FileSystemDataset: The filtered PyArrow Parquet dataset.
"""
if self.is_loaded:
if isinstance(filter_expr, str):
filter_expr = sql2pyarrow_filter(filter_expr, self.schema)
return self._arrow_dataset.filter(filter_expr)
def filter(
self,
filter_expr: str | pds.Expression,
use: str = "auto",
) -> pds.FileSystemDataset | pds.Dataset | _duckdb.DuckDBPyRelation:
"""
Filters the dataset based on the given filter expression.
Args:
filter_expr (str | pds.Expression): The filter expression to apply.
use (str, optional): The method to use for filtering. Defaults to "auto".
Returns:
pds.FileSystemDataset | pds.Dataset | _duckdb.DuckDBPyRelation: The filtered dataset.
Raises:
Exception: If filtering with PyArrow fails and use is set to "auto".
Note:
If the filter expression contains any of the following: "%", "like", "similar to", or "*",
the method will automatically use DuckDB for filtering.
"""
if any([s in filter_expr for s in ["%", "like", "similar to", "*", "(", ")"]]):
use = "duckdb"
if use == "auto":
try:
res = self._filter_arrow_dataset(filter_expr)
except Exception as e:
e.add_note("Note: Filtering with PyArrow failed. Using DuckDB.")
print(e)
res = self._filter_duckdb(filter_expr)
elif use == "pyarrow":
res = self._filter_arrow_dataset(filter_expr)
elif use == "duckdb":
res = self._filter_duckdb(filter_expr)
return PydalaTable(result=res, ddb_con=self.ddb_con)
@property
def registered_tables(self) -> list[str]:
"""
Get a list of registered tables.
Returns:
list[str]: A list of table names.
"""
return self.ddb_con.sql("SHOW TABLES").arrow().column("name").to_pylist()
def interrupt_duckdb(self):
"""
Interrupts the DuckDB connection.
"""
self.ddb_con.interrupt()
def reset_duckdb(self):
"""
Resets the DuckDB connection and registers the necessary tables and datasets.
Returns:
None
"""
# self.ddb_con = _duckdb.connect()
self.interrupt_duckdb()
if f"{self.name}" not in self.registered_tables:
if hasattr(self, "_arrow_table"):
self.ddb_con.register(f"{self.name}", self._arrow_table)
elif hasattr(self, "_arrow_dataset"):
self.ddb_con.register(f"{self.name}", self._arrow_dataset)
def _get_delta_other_df(
self,
df: _pl.DataFrame | _pl.LazyFrame,
filter_columns: str | list[str] | None = None,
) -> _pl.DataFrame | _pl.LazyFrame:
"""
Returns a filtered DataFrame or LazyFrame based on the given input DataFrame and filter columns.
Args:
df (DataFrame or LazyFrame): The input DataFrame or LazyFrame to filter.
filter_columns (str or list[str] or None, optional): The columns to filter on. Defaults to None.
Returns:
DataFrame or LazyFrame: The filtered DataFrame or LazyFrame.
"""
collect = False
if len(self.files) == 0:
return _pl.DataFrame(schema=df.schema)
if isinstance(df, _pl.LazyFrame):
collect = True
columns = set(df.columns) & set(self.columns)
null_columns = df.select(cs.by_dtype(_pl.Null)).collect_schema().names()
columns = columns - set(null_columns)
if filter_columns is not None:
columns = set(columns) & set(filter_columns)
if len(columns) == 0:
return _pl.DataFrame(schema=df.schema)
filter_expr = []
for col in columns:
# if df.collect_schema().get(col).is_(_pl.Null):
# max_min = df.select(
# _pl.first(col).alias("max"), _pl.last(col).alias("min")
# )
# else:
max_min = df.select(_pl.max(col).alias("max"), _pl.min(col).alias("min"))
if collect:
max_min = max_min.collect()
f_max = max_min["max"][0]
f_min = max_min["min"][0]
if isinstance(f_max, str):
f_max = f_max.strip("'").replace(",", "")
if isinstance(f_min, str):
f_min = f_min.strip("'").replace(",", "")
filter_expr.append(
f"(({col}<='{f_max}' AND {col}>='{f_min}') OR {col} IS NULL)".replace(
"'None'", "NULL"
)
)
return self.filter(" AND ".join(filter_expr)).pl
def write_to_dataset(
self,
data: (
_pl.DataFrame
| _pl.LazyFrame
| pa.Table
| pa.RecordBatch
| pd.DataFrame
| _duckdb.DuckDBPyConnection
| list[
_pl.DataFrame
| _pl.LazyFrame
| pa.Table
| pa.RecordBatch
| pd.DataFrame
| _duckdb.DuckDBPyConnection
]
),
mode: str = "append", # "delta", "overwrite"
basename: str | None = None,
partition_by: str | list[str] | None = None,
max_rows_per_file: int | None = 2_500_000,
row_group_size: int | None = 250_000,
compression: str = "zstd",
sort_by: str | list[str] | list[tuple[str, str]] | None = None,
unique: bool | str | list[str] = False,
ts_unit: str = "us",
tz: str | None = None,
remove_tz: bool = False,
use_large_string: bool = False,
delta_subset: str | list[str] | None = None,
alter_schema: bool = False,
timestamp_column: str | None = None,
**kwargs,
):
"""
Writes the given data to the dataset.
Parameters:
- data: The data to be written to the dataset. It can be one of the following types:
- _pl.DataFrame
- _pl.LazyFrame
- pa.Table
- pa.RecordBatch
- pa.RecordBatchReader
- pd.DataFrame
- _duckdb.DuckDBPyConnection
- list of any of the above types
- mode: The write mode. Possible values are "append", "delta", or "overwrite". Defaults to "append".
- basename: The template for the basename of the output files. Defaults to None.
- partition_by: The columns to be used for partitioning the dataset. Can be a string, a list of strings,
or None. Defaults to None.
- max_rows_per_file: The maximum number of rows per file. Defaults to 2,500,000.
- row_group_size: The size of each row group. Defaults to 250,000.
- compression: The compression algorithm to be used. Defaults to "zstd".
- sort_by: The column(s) to sort the data by. Can be a string, a list of strings, or a list of tuples (column,
order). Defaults to None.
- unique: Whether to keep only unique rows. Can be a bool, a string, or a list of strings. Defaults to False.
- ts_unit: The unit of the timestamp column. Defaults to "us".
- tz: The timezone to be used for the timestamp column. Defaults to None.
- remove_tz: Whether to remove the timezone information from the timestamp column. Defaults to False.
- use_large_string: Whether to use large string type for string columns. Defaults to False.
- delta_subset: The subset of columns to consider for delta updates. Can be a string, a list of strings, or
None. Defaults to None.
- alter_schema: Whether to alter the schema of the dataset. Defaults to False.
- timestamp_column: The name of the timestamp column. Defaults to None.
- **kwargs: Additional keyword arguments to be passed to the writer.
Returns:
None
"""
if "partitioning_columns" in kwargs:
partition_by = kwargs.pop("partitioning_columns")
if not partition_by and self.partition_names:
partition_by = self.partition_names
if timestamp_column is not None:
self._timestamp_column = timestamp_column
if (
not isinstance(data, list)
and not isinstance(data, tuple)
and not isinstance(data, pa.RecordBatchReader)
):
data = [data]
for data_ in data:
writer = Writer(
data=data_,
path=self._path,
filesystem=self._filesystem,
schema=self.schema if not alter_schema else None,
)
if writer.shape[0] == 0:
continue
writer.sort_data(by=sort_by)
if unique:
writer.unique(columns=unique)
if partition_by:
writer.add_datepart_columns(
columns=partition_by,
timestamp_column=self._timestamp_column,
)
writer.cast_schema(
use_large_string=use_large_string,
ts_unit=ts_unit,
tz=tz,
remove_tz=remove_tz,
alter_schema=alter_schema,
)
if mode == "delta" and self.is_loaded:
writer._to_polars()
other_df = self._get_delta_other_df(
writer.data,
filter_columns=delta_subset,
)
if other_df is not None:
writer.delta(other=other_df, subset=delta_subset)
writer.write_to_dataset(
row_group_size=row_group_size,
compression=compression,
partitioning_columns=partition_by,
partitioning_flavor="hive",
max_rows_per_file=max_rows_per_file,
basename=basename,
**kwargs,
)
if mode == "overwrite":
del_files = [os.path.join(self._path, fn) for fn in self.files]
self.delete_files(del_files)
self.clear_cache()
# self.load_files()
class ParquetDataset(PydalaDatasetMetadata, BaseDataset):
def __init__(
self,
path: str,
name: str | None = None,
filesystem: AbstractFileSystem | None = None,
bucket: str | None = None,
partitioning: str | list[str] | None = None,
cached: bool = False,
timestamp_column: str | None = None,
ddb_con: _duckdb.DuckDBPyConnection | None = None,
**fs_kwargs,
):
"""
Initialize a Dataset object.
Args:
path (str): The path to the dataset.
filesystem (AbstractFileSystem, optional): The filesystem to use.
Defaults to None.
bucket (str, optional): The bucket to use. Defaults to None.
partitioning (str, list[str], optional): The partitioning scheme
to use. Defaults to None.
cached (bool, optional): Whether to use cached data. Defaults to
False.
**cached_options: Additional options for cached data.
Returns:
None
"""
PydalaDatasetMetadata.__init__(
self,
path=path,
filesystem=filesystem,
bucket=bucket,
cached=cached,
partitioning=partitioning,
ddb_con=ddb_con,
**fs_kwargs,
)
BaseDataset.__init__(
self,
path=path,
name=name,
filesystem=filesystem,
bucket=bucket,
partitioning=partitioning,
cached=cached,
timestamp_column=timestamp_column,
ddb_con=self.ddb_con,
**fs_kwargs,
)
# if self.has_metadata:
# self.pydala_dataset_metadata = PydalaDatasetMetadata(
# metadata=self.metadata, partitioning=partitioning, ddb_con=ddb_con
# )
# self.metadata_table.create_view(f"{self.name}_metadata")
# self.ddb_con.unregister("metadata_table")
# try:
# self.load()
# except Exception as e:
# _ = e
# pass
def load(
self,
update_metadata: bool = False,
reload_metadata: bool = False,
schema: pa.Schema | None = None,
ts_unit: str = "us",
tz: str | None = None,
use_large_string: bool = False,
sort_schema: bool = False,
format_version: str = "2.6",
**kwargs,
):
"""
Loads the data from the dataset.
Args:
update_metadata (bool, optional): Whether to update the metadata. Defaults to False.
reload_metadata (bool, optional): Whether to reload the metadata. Defaults to False.
schema (pa.Schema | None, optional): The schema of the data. Defaults to None.
ts_unit (str, optional): The unit of the timestamp. Defaults to "us".
tz (str | None, optional): The timezone. Defaults to None.
use_large_string (bool, optional): Whether to use large string. Defaults to False.
sort_schema (bool, optional): Whether to sort the schema. Defaults to False.
format_version (str, optional): The version of the data format. Defaults to "2.6".
**kwargs: Additional keyword arguments.
Returns:
None
"""
if kwargs.pop("update", None):
update_metadata = True
if kwargs.pop("reload", None):
reload_metadata = True
if self.has_files:
if update_metadata or reload_metadata or not self.has_metadata_file:
self.update(
reload=reload_metadata,
schema=schema,
ts_unit=ts_unit,
tz=tz,
use_large_string=use_large_string,
sort=sort_schema,
format_version=format_version,
**kwargs,
)
if not hasattr(self, "_schema"):
self._schema = self.metadata.schema.to_arrow_schema()
self.update_metadata_table()
self._arrow_dataset = pds.parquet_dataset(
self._metadata_file,
# schema=self._schema,
partitioning=self._partitioning,
filesystem=self._filesystem,
)
self.table = PydalaTable(result=self._arrow_dataset, ddb_con=self.ddb_con)
if self._timestamp_column is None:
self._timestamp_columns = get_timestamp_column(self.table.pl.head(10))
if len(self._timestamp_columns) > 0:
self._timestamp_column = self._timestamp_columns[0]
if self._timestamp_column is not None:
tz = self.schema.field(self._timestamp_column).type.tz
self._tz = tz
if tz is not None:
self.ddb_con.execute(f"SET TimeZone='{tz}'")
else:
self._tz = None
self.ddb_con.register(f"{self.name}", self._arrow_dataset)
# def gen_metadata_table(self):
# """
# Generate the metadata table for the dataset.
# This function calls the `gen_metadata_table` method of the `pydala_dataset_metadata` object
# to generate the metadata table for the dataset. It takes two parameters:
# - `metadata`: The metadata object containing information about the dataset.
# - `_partitioning`: The partitioning object containing information about the dataset partitioning.
# This function does not return anything.
# Example usage:
# ```
# self.gen_metadata_table()
# ```
# """
# self.pydala_dataset_metadata.gen_metadata_table(
# self.metadata, self._partitioning
# )
def scan(self, filter_expr: str | None = None) -> ParquetDatasetMetadata:
"""
Scans the Parquet dataset metadata.
Args:
filter_expr (str, optional): An optional filter expression to apply to the metadata.
Returns:
ParquetDatasetMetadata: The ParquetDatasetMetadata object.
"""
PydalaDatasetMetadata.scan(self, filter_expr=filter_expr)
if len(self.scan_files) == 0:
return PydalaTable(result=self.table.ddb.limit(0))
return PydalaTable(
result=pds.dataset(
[os.path.join(self.path, fn) for fn in self.scan_files],
filesystem=self._filesystem,
format=self._format,
partitioning=self._partitioning,
),
ddb_con=self.ddb_con,
)
def __repr__(self):
if self.table is not None:
return self.table.__repr__()
else:
return f"{self.path} is empty."
def write_to_dataset(
self,
data: (
_pl.DataFrame
| _pl.LazyFrame
| pa.Table
| pa.RecordBatch
| pa.RecordBatchReader
| pd.DataFrame
| _duckdb.DuckDBPyConnection
| list[
_pl.DataFrame
| _pl.LazyFrame
| pa.Table
| pa.RecordBatch
| pd.DataFrame
| _duckdb.DuckDBPyConnection
]
),
mode: str = "append", # "delta", "overwrite"
basename: str | None = None,
partition_by: str | list[str] | None = None,
max_rows_per_file: int | None = 2_500_000,
row_group_size: int | None = 250_000,
compression: str = "zstd",
sort_by: str | list[str] | list[tuple[str, str]] | None = None,
unique: bool | str | list[str] = False,
ts_unit: str = "us",
tz: str | None = None,
remove_tz: bool = False,
use_large_string: bool = False,
delta_subset: str | list[str] | None = None,
update_metadata: bool = False,
alter_schema: bool = False,
timestamp_column: str | None = None,
**kwargs,
):
"""
Writes the given data to the dataset.
Parameters:
- data: The data to be written to the dataset. It can be one of the following types:
- _pl.DataFrame
- _pl.LazyFrame
- pa.Table
- pa.RecordBatch
- pa.RecordBatchReader
- pd.DataFrame
- _duckdb.DuckDBPyConnection
- list of any of the above types
- mode: The write mode. Possible values are "append", "delta", or "overwrite". Defaults to "append".
- basename: The template for the basename of the output files. Defaults to None.
- partition_by: The columns to be used for partitioning the dataset. Can be a string, a list of strings,
or None. Defaults to None.
- max_rows_per_file: The maximum number of rows per file. Defaults to 2,500,000.
- row_group_size: The size of each row group. Defaults to 250,000.
- compression: The compression algorithm to be used. Defaults to "zstd".
- sort_by: The column(s) to sort the data by. Can be a string, a list of strings, or a list of tuples (column,
order). Defaults to None.
- unique: Whether to keep only unique rows. Can be a bool, a string, or a list of strings. Defaults to False.
- ts_unit: The unit of the timestamp column. Defaults to "us".
- tz: The timezone to be used for the timestamp column. Defaults to None.