SparkETLManager Class Documentation¶
Bases: ManagerClass
Puts together all Spark features provided by sparksnake library.
This class provides an easy and fast way for users to improve and enhance the development of their Apache Spark applications. This class can be considered a central point of contact for users who whant to use all features (attributes and methods) provided by sparksnake whenever the Spark application is running locally or in any supported AWS services such as AWS Glue.
To configure this class and start using all its features, users just need to set up an "operation mode" represented by the "mode" class attribute. The operation mode can be chosen based on where the Spark application will run. Currently there are two available options:
mode="default"
enables features do enhance the development of Spark applications anywheremode="glue"
enables features to enhance the development of Spark applications deployed as Glue jobs in AWS. In this case, a class inheritance process is applied in order to enable users to useawsglue
modules in a Glue environment.
"Setting up the operation mode within SparkETLManager
class"
# Importing the class
from sparksnake.manager import SparkETLManager
# Creating a spark manager object to develop Spark apps anywhere
spark_manager = SparkETLManager(
mode="default"
)
# Creating a spark manager object to develop Spark apps on AWS Glue
spark_manager = SparkETLManager(
mode="glue",
argv_list=[] # A list of Glue job arguments
data_dict={} # A dictionary with all data sources for the job
)
A special note about the sparksnake's operation mode takes place on
different behaviors the deployment environment demands in order to work
properly. In other words, when choosing "glue" as the operation mode while
creating a SparkETLManager
object, users need to check what additional
attributes must be passed to the class so the Glue custom features can
available to be applied in their Spark application.
A basic usage example of class SparkETLManager
with mode="glue"
# Importing packages
from sparksnake.manager import SparkETLManager
from datetime import datetime
# Defining job arguments
ARGV_LIST = ["JOB_NAME", "S3_OUTPUT_PATH"]
# Defining dictionary of data sources to be used on job
DATA_DICT = {
"orders": {
"database": "ra8",
"table_name": "orders",
"transformation_ctx": "dyf_orders"
},
"customers": {
"database": "ra8",
"table_name": "customers",
"transformation_ctx": "dyf_customers",
"push_down_predicate": "anomesdia=20221201",
"create_temp_view": True,
"additional_options": {
"compressionType": "lzo"
}
}
}
# Creating a class object on initializing a glue job
spark_manager = SparkETLManager(
mode="glue",
argv_list=ARGV_LIST,
data_dict=DATA_DICT
)
spark_manager.init_job()
# Getting all DataFrames Spark based on data_dict provided
dfs_dict = spark_manager.generate_dataframes_dict()
# Indexing a DataFrame from the dictionary
df_orders = dfs_dict["orders"]
# Dropping a partition on S3 (if exists)
spark_manager.drop_partition(
s3_partition_uri="s3://some-bucket-name/some-table-name/partition/"
)
# Adding a partition column into the DataFrame
df_orders_partitioned = spark_manager.add_partition_column(
partition_name="anomesdia",
partition_value=int(datetime.now().strftime("%Y%m%d"))
)
# Applying a repartition method for storage optimization
df_orders_repartitioned = spark_manager.repartition_dataframe(
df=df_orders_partitioned,
num_partitions=10
)
# Writing data on S3 and cataloging it on Data Catalog
spark_manager.write_and_catalog_data(df=df_orders_repartitioned)
# Job commit
spark_manager.job.commit()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode |
string
|
Operation mode for the class. It handles inheritance from other
classes based on this library so the |
required |
The "mode" attribute may not be the only one.
As stated before, the SparkETLManager
class provides a "mode"
attribute that can be used to set special class configuration
according to where users pretend to develop their Spark applications.
Technically, it happens by class inheritance.
In other words, when users set mode="glue"
in order to develop their
Spark applications as Glue jobs on AWS, all Glue features that is
needed to provide such environment is inherited by another class inside
the sparksnake library. This class is the GlueJobManager
and its
source code is available on the glue.py
library module.
By saying that the "mode" attribute may not be the only one, it is said
that those class inheritance processes may demands the input of some
other attributes. For example, to initialize an object from the
GlueJobManager
class, users need to pass two more attributes named
argv_list
and data_dict
, each one with their special purposes. So,
in this situation, anyone who needs to use sparksnake in the Glue ops
mode may pass those two mode class attributes in the SparkETLManager
class.
To be awared of which additional attributes is needed to start the
SparkETLManager
class in any available mode, you can always check the
source code of the class to be inherited. The table below provides
information about all operation modes and the inherited classes:
Operation Mode | Inherited Class |
---|---|
default | None |
glue | GlueJobManager |
Source code in sparksnake/manager.py
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 |
|
date_transform(df, date_col, date_col_type='date', date_format='yyyy-MM-dd', cast_string_to_date=True, **kwargs)
staticmethod
¶
Extracting date attributes from a Spark DataFrame date column.
This method makes it possible to extract multiple date attributes from a Spark DataFrame column that represents a date or timestamp value. The date attributes are extracted using all available Apache Spark date functions such as year(), month(), dayofmonth() and many others that can be found on the official pyspark documentation page.
So, the given date column (date_col argument) should has a DATE or a TIMESTAMP data type. If this can be achieved, the date column should then be a string that can be parseable to a date type object. This is the condition to extract date attributes using pyspark date functions.
The main idea behind this method is to provide users an easy way to enhance their data analysis by extracting multiple date attributes from a date column. This can be a huge improvement on analytics processes and DataFrames enrichment.
Examples:
# Extracting date attributes from a date column in a Spark df
df_date_prep = spark_manager.date_transform(
df=df_raw,
date_col="order_date",
date_col_type="timestamp",
year=True,
month=True,
dayofmonth=True
)
# In the above example, the method will return a new DataFrame
# with additional columns based on the order_date_content, such as:
# year_order_date, month_order_date and dayofmonth_order_date
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pyspark.sql.DataFrame
|
A target Spark DataFrame for applying the transformation. |
required |
date_col |
str
|
A date column name (or parseable string as date) to be used in the date extraction process. |
required |
date_col_type |
str
|
Reference for data type of |
'date'
|
date_format |
str
|
Date format applied in a optional string to date casting.
It's applicable only if |
'yyyy-MM-dd'
|
cast_string_to_date |
bool
|
Enables an automatic casting of the |
True
|
Other Parameters:
Name | Type | Description |
---|---|---|
year |
bool
|
Extracts the year of target date column |
quarter |
bool
|
Extracts the quarter of target date column |
month |
bool
|
Extracts the month of target date column |
dayofmonth |
bool
|
Extracts the dayofmonth of target date column |
dayofweek |
bool
|
Extracts the dayofweek of target date column |
weekofyear |
bool
|
Extracts the weekofyear of target date column |
Raises:
Type | Description |
---|---|
ValueError
|
Exception raised if the |
Returns:
Type | Description |
---|---|
DataFrame
|
Spark DataFrame with new date columns extracted. |
Source code in sparksnake/manager.py
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 |
|
agg_data(spark_session, df, agg_col, group_by, round_result=False, n_round=2, **kwargs)
staticmethod
¶
Extracting statistical attributes based on a group by operation.
This method makes it possible to run complex aggregations using a single method call. To use this feature, users can follow the steps below:
- Provide a aggregation column (agg_col argument)
- Provide a single column reference or a list of columns to be grouped by (group_by argument)
- Provide the aggregation functions on **kwargs
The aggregation functions mentioned on the third step are represented
by almost any avaiable pyspark function, such as sum()
, mean()
,
max()
, min()
and many others.
Examples:
# Creating a new special and aggregated DataFrame
df_stats = spark_manager.agg_data(
spark_session=spark,
df=df_orders,
agg_col="order_value",
group_by=["order_id", "order_year"],
sum=True,
mean=True,
max=True,
min=True
)
# In the example above, the method will return a new DataFrame with
# the following columns:
# order_id e order_year (group by)
# sum_order_value (sum of order_value column)
# mean_order_value (average of order_value column)
# max_order_value (max value of order_value column)
# min_order_value (min value of order_value column)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spark_session |
pyspark.sql.SparkSession
|
A SparkSession object to be used to run SparkSQL query for grouping data |
required |
df |
pyspark.sql.DataFrame
|
A target Spark DataFrame for applying the transformation |
required |
agg_col |
str
|
A column reference on the target DataFrame to be used as target of aggregation process |
required |
group_by |
str or list
|
A column name or a list of columns used as group categories on the aggregation process |
required |
round_result |
bool
|
Enables rounding aggregation results on each new column |
False
|
n_round |
int
|
Defines the round number on rounding. Applied only if
|
2
|
About keyword arguments
In order to provide a new feature that is capable to put together the extraction of multiple statistical attributes with a single line of code, a special list of pyspark functions were selected as acceptable functions to be called on the aggregation process.
It means that if users wants to apply an aggregation on the
target DataFrame and extract the sum, the mean, the minimum and
the maximum value of a given numeric column, they must pass
keyword arguments as following: sum=True
, mean=True
,
min=True
and max=True
.
All acceptable keyword arguments (pyspark functions) can be found right below:
Other Parameters:
Name | Type | Description |
---|---|---|
sum |
bool
|
Extracts the sum of a given numeric column |
mean |
bool
|
Extracts the mean of a given numeric column |
max |
bool
|
Extracts the max of a given numeric column |
min |
bool
|
Extracts the min of a given numeric column |
countDistinct |
bool
|
Extracts the count distinct value of a given numeric column |
variance |
bool
|
Extracts the variance of a given numeric column |
stddev |
bool
|
Extracts the standard deviation of a given numeric column |
kurtosis |
bool
|
Extracts the kurtosis of a given numeric column |
skewness |
bool
|
Extracts the skewness of a given numeric column |
Returns:
Type | Description |
---|---|
DataFrame
|
A new Spark DataFrame with new statistical columns based on the aggregation configured by user on method call. |
Raises:
Type | Description |
---|---|
Exception
|
Generic exception raised when failed to execute the SparkSQL query for extracting the stats from the DataFrame. |
Source code in sparksnake/manager.py
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 |
|
add_partition_column(df, partition_name, partition_value)
staticmethod
¶
Adding a "partition" column on a Spark DataFrame.
This method is responsible for adding a new column on a target Spark
DataFrame to be considered as a table partition. In essence, this
method uses the native pyspark .withColumn()
method for adding a
new column to the DataFrame using a name (partition_name) and a value
(partition_value).
The idea behind this method is to provide users a more clear way to add a partition column in their Spark DataFrames and make it very explicity to whoever is reading the code.
Examples
# Defining partition information
partition_name = "anomesdia"
partition_value = int(datetime.now().strftime('%Y%m%d'))
# Adding a partition column to the DataFrame
df_partitioned = spark_manager.add_partition_column(
df=df_orders,
partition_name=partition_name,
partition_value=partition_value
)
# The method returns a new DataFrame with a new column
# referenced by "anomesdia" and its value referenced by
# the datetime library
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pyspark.sql.DataFrame
|
A target Spark DataFrame. |
required |
partition_name |
str
|
Column name to be added on the DataFrame. |
required |
partition_value |
Any
|
Value for the new column to be added. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
A Spark DataFrame with the new column added. |
Raises:
Type | Description |
---|---|
Exception
|
A generic exception raised on failed to execute the method |
Source code in sparksnake/manager.py
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 |
|
repartition_dataframe(df, num_partitions)
staticmethod
¶
Repartitioning a Spark DataFrame in order to optimize storage.
This method applies the repartition process in a Spark DataFrame in order to optimize its storage on S3. The method has some important checks based on each pyspark method to use for repartitioning the DataFrame. Take a look at the below tip to learn more.
Additional details on method behavior
The method repartition_dataframe()
works as follows:
- The current number of partitions in the target DataFrame is checked
-
The desired number of partitions passed as a parameter is checked
-
If the desired number is LESS than the current number, then the method
coalesce()
is executed - If the desired number is GREATER than the current one, then the
method
repartition()
is executed
Examples:
# Repartitioning a Spark DataFrame
df_repartitioned = spark_manager.repartition_dataframe(
df=df_orders,
num_partitions=10
)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
pyspark.sql.DataFrame
|
A target Spark Dataframe. |
required |
num_partitions |
int
|
Desired number of partitions. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
A new Spark DataFrame gotten after the repartition process. |
Raises:
Type | Description |
---|---|
Exception
|
A generic exception is raised on a failed attempt to run the repartition method ( |
Source code in sparksnake/manager.py
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 |
|
run_spark_sql_pipeline(spark_session, spark_sql_pipeline)
staticmethod
¶
Providing a way to run multiple SparkSQL queries in sequence.
This method allows users to define a sequence of SparkSQL queries to
built transformation DAGs in order to transform DataFrames in a Spark
application using only SQL. The core idea behind this method is that
users can define a sequence of SparkSQL statements using a predefined
list of dictionaries (spark_sql_pipeline
argument) that will be
handled by the method as the main piece for sequentially running
the queries and providing the desired result as a Spark DataFrame.
As said before, everything around this method takes place
spark_sql_pipeline
argument definition. In essence, this argument
can be defined as a list with multiple dictionaries, where each
inner dictionary in this list can have elements that describe the
execution of a SparkSQL query (including the query itself).
Examples:
# Defining a list with all SparkSQL steps to be executed
spark_sql_pipeline = [
{
"step": 1,
"query": '''
SELECT
order_id,
order_status,
order_purchase_ts
FROM tbl_orders
'''
"create_temp_view": True,
"temp_view_name": "auto"
},
{
"step": 2,
"query": '''
SELECT
order_id,
sum(payment_value) AS sum_payment_value
FROM tbl_payments
GROUP BY order_id
'''
"create_temp_view": True,
"temp_view_name": "auto"
},
{
"step": 3,
"query": '''
SELECT
step_1.order_id,
step_1.order_status,
step_1.order_purchase_ts,
step_2.sum_payment_value
FROM step_1
LEFT JOIN step_2
ON step_1.order_id = step_2.order_id
'''
"create_temp_view": True,
"temp_view_name": "auto"
}
]
# Running the SparkSQL pipeline
df_prep = run_spark_sql_pipeline(
spark_session=spark_manager.spark,
spark_sql_pipeline=spark_sql_pipeline
)
About the spark_sql_pipeline definition
As stated before, the spark_sql_pipeline
method argument can be
defined as a Python list where each element is a Python dictionary
with all information needed to run SparkSQL statements in sequence.
First of all, it's important to say that the inner dictionaries must be defined with some acceptable keys:
-
"step"
(required): defines an integer number to inform the method in which order the query in the given dictionary should be executed. The value passed on the "step" inner dictionary key is used in a sorting proccess that defines the execution order of the SparkSQL statements. -
"query"
(required): well, this is the SparkSQL query itself that will be executed by the method. This could be defines as a Python string directly on the dictionary or even by reading some external JSON or SQL file in the project directory. -
"create_temp_view"
(optional, default=True): defines a boolean flag that handles the creation of a new temporary view for each executed step. By the default, it's set as True, meaning that after each execution, a new temporary view will be available for further SparkSQL statements. -
"temp_view_name"
(optional, default="auto"): defines the name of the temporary view created after executing the SparkSQL query in a given step. It's applicable only if "create_temp_view" is True for the step. By default, it's value is set as "auto", meaning that the name of the intermediate temporary view will be set as "step_N", where N is the integer that defines the step. For example, in the first inner dictionary of thespark_sql_pipeline
list (for instance, "step": 1), a query will be executed and, if there is no an explicit "create_temp_view": False in the dictionary, then a new temporary view with query result will be created and named as "step_1". So, any further SparkSQL statements that selects data from any "step_1" table will be pointing to the intermediate results of the first step of the pipeline. By the other hand, users can define a specific name for the step temporary view by filling this key with any desired string.
If users don't explicit define the keys "create_temp_view" and
"temp_view_name", the method will consider its default values. In
other words, if the a inner dictionary of the spark_sql_pipeline
list doesn't have any of the mentioned keys, it means that a
temporary view will be created after running the step's query and
it will be named as "step_N", where N is the integer that identify
the step.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spark_session |
pyspark.sql.SparkSession
|
A SparkSession object to be used to run SparkSQL query for grouping data |
required |
spark_sql_pipeline |
list
|
A list made by dictionaries that defines details of the steps to be executed using SparkSQL queries. Check the tip above for more details on how passing this argument |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
A Spark DataFrame that is the result of the execution of the last step (query) defined in the spark_sql_pipeline list. |
Raises:
Type | Description |
---|---|
ValueError
|
An exception raises in two different situations: first, if the user defines any dictionary in |
Source code in sparksnake/manager.py
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 |
|