<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Swapnil Bhoite on Medium]]></title>
        <description><![CDATA[Stories by Swapnil Bhoite on Medium]]></description>
        <link>https://medium.com/@swapnil-bhoite?source=rss-772637dfc6b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zZJkiORT7pPC6VWWJ3gDZQ.jpeg</url>
            <title>Stories by Swapnil Bhoite on Medium</title>
            <link>https://medium.com/@swapnil-bhoite?source=rss-772637dfc6b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:29:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swapnil-bhoite/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to Amazon S3 Tables and table buckets]]></title>
            <link>https://medium.com/doit-international/introduction-to-amazon-s3-tables-and-table-buckets-22b12d63fc60?source=rss-772637dfc6b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b12d63fc60</guid>
            <dc:creator><![CDATA[Swapnil Bhoite]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 16:09:23 GMT</pubDate>
            <atom:updated>2025-01-18T23:49:17.873Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction to Amazon S3 Tables and Table Buckets for seamless analytics</strong></h3><p>Recently in the AWS re:invent 2024, there was an <a href="https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-s3-tables-apache-iceberg-tables-analytics-workloads/">announcement</a> for Amazon S3 Tables that provide fully managed Apache Iceberg tables optimized for analytics workloads. These tables will have managed storage Iceberg format table which can be managed using <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3tables/index.html#cli-aws-s3tables">s3tables API</a> and for the data operations, this can be integrated with Apache Spark or <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-integrating-aws.html">AWS-based analytical services </a>— Amazon EMR, Amazon Athena, Amazon Redshift, Amazon EMR, Amazon QuickSight, Amazon Data Firehose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Syjfzbj7RyEm7m8-K8Yyqg.png" /><figcaption>Generated using Amazon Bedrock</figcaption></figure><h3>Getting started</h3><p>First of all, you will be required to <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-buckets-create.html">create a table bucket</a> either using the console or AWS CLI and here you have the option of enabling this table bucket integration with AWS analytics services mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdiXrfArDjuKYFJiQwlgyw.png" /><figcaption>S3 Table bucket console</figcaption></figure><p>Once you create the table bucket you will now need to create a <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-namespace.html">namespace</a> (Think of this as a logical database that will have multiple tables within it) inside which will have our tables.</p><pre>aws s3tables create-namespace \<br>    --table-bucket-arn arn:aws:s3tables:us-east-1:111122223333:bucket/my-s3-table-bucket \ <br>    --namespace my_first_namespace<br><br>aws s3tables create-table \<br>    --table-bucket-arn arn:aws:s3tables:us-east-1:111122223333:bucket/my-s3-table-bucket \<br>    --namespace my_first_namespace \<br>    --name my_first_table --format ICEBERG</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1OOIRvoNjDJRLiED6yMrw.png" /><figcaption>Tables created in table bucket console</figcaption></figure><p>The table format is based on the <a href="https://iceberg.apache.org/">Apache Iceberg</a> framework, the underlying storage has both the table data and its metadata. With S3 tables you do not have to worry about table maintenance, <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-maintenance-overview.html">Amazon S3 offers maintenance</a> to enhance the performance of your S3 tables or table buckets. These maintenance options are file compaction, snapshot management, and unreferenced file removal. These options are enabled by default. You can edit or disable these operations through maintenance configuration files. However, you can <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3tables/put-table-bucket-maintenance-configuration.html">configure the maintenance job parameters </a>to the parameter value that works well for you. You can review the job status using the s3tables API</p><pre>aws s3tables get-table-maintenance-job-status \<br>   --table-bucket-arn=&quot;arn:aws:s3tables:us-east-1:111122223333:bucket/my-s3-table-bucket&quot; \<br>   --namespace=&quot;mynamespace&quot; \<br>   --name=&quot;testtable&quot; </pre><p>Before we integrate S3 tables with analytical services, you will need to complete the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-integrating-aws.html#table-integration-prerequisites">prerequisite</a> steps.</p><p>Create a new catalog for S3 tables</p><pre>aws glue create-catalog --region us-east-1 --name s3tablescatalog --catalog-input &#39;{ &quot;CreateDatabaseDefaultPermissions&quot;:[], &quot;CreateTableDefaultPermissions&quot;:[], &quot;FederatedCatalog&quot;:{ &quot;Identifier&quot;:&quot;arn:aws:s3tables:us-east-1:111122223333:bucket/*&quot;, &quot;ConnectionName&quot;:&quot;aws:s3tables&quot;} }&#39;</pre><p>This catalog will be registered under the AWS LakeFormation and likewise, you should also be able to see the namespace and the table we created earlier LakeFormation console (You will need to use the dropdown option to select the S3 table catalog we created above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkOzpNBjYhy8wzbHaBoGgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foTzU3ZtUyCvpAXYJQtFhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FvuJ0rWWdEKfEMysktYqA.png" /></figure><h3>Integration with Amazon EMR</h3><p>Now coming to the fun part! Here we integrate these S3 tables with AWS services. Firstly I will start with Amazon EMR and <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-getting-started.html#s2-tables-tutorial-EMR-cluster">provision an Iceberg-enabled EMR cluster with Apache Spark. </a>And then login to the primary node of the cluster using <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-connect-master-node-ssh.html#emr-connect-linux">SSH</a>.</p><p>Start the spark-shell</p><pre>spark-shell \<br>--packages software.amazon.s3tables:s3-tables-catalog-for-iceberg-runtime:0.1.3 \<br>--conf spark.sql.catalog.s3tablesbucket=org.apache.iceberg.spark.SparkCatalog \<br>--conf spark.sql.catalog.s3tablesbucket.catalog-impl=software.amazon.s3tables.iceberg.S3TablesCatalog \<br>--conf spark.sql.catalog.s3tablesbucket.warehouse=arn:aws:s3tables:us-east-1:111122223333:bucket/my-s3-table-bucket \<br>--conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zar6B_9YVsb_KFHAN321mw.png" /><figcaption>Spark-shell in EMR primary node</figcaption></figure><p>Make sure you have correctly followed the <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables-getting-started.html#s2-tables-tutorial-EMR-cluster">pre-requisite</a> mentioned for the integration. For Amazon EMR, you will need to Attach the <a href="https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonS3TablesFullAccess.html">AmazonS3TablesFullAccess</a> policy to EMR_EC2_DefaultRoleand also provide appropriate catalog, namespace, and table-level LakeFormation permissions to the EMR_EC2_DefaultRole</p><pre>spark.sql(&quot;CREATE NAMESPACE IF NOT EXISTS s3tablesbucket.my_first_namespace&quot;)           <br><br>spark.sql( <br>&quot;&quot;&quot; CREATE TABLE IF NOT EXISTS s3tablesbucket.my_first_namespace.`example_table` ( <br>    id INT, <br>    name STRING, <br>    value INT <br>) <br>USING iceberg &quot;&quot;&quot;<br>)<br><br>spark.sql(<br>&quot;&quot;&quot;<br>    INSERT INTO s3tablesbucket.my_first_namespace.example_table <br>    VALUES <br>        (1, &#39;ABC&#39;, 100), <br>        (2, &#39;XYZ&#39;, 200)<br>&quot;&quot;&quot;)<br><br>spark.sql(&quot;&quot;&quot; SELECT * FROM s3tablesbucket.my_first_namespace.example_table &quot;&quot;&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*aNy04PB8Uny8HlaMXpX0MA.png" /><figcaption>Create a new namespace for table bucket</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JczbiwiLNhkIcJO3deGKg.png" /><figcaption>Create new table bucket based table inside the namespace</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*gvcmczOesaQxlsMx71zc4A.png" /><figcaption>Query the table</figcaption></figure><p>If you have a sample parquet data on S3 you can read it and create a S3 table for it and query it</p><pre>#Read the parequet file<br>val data_file = spark.read.parquet(&quot;s3://myBucket/prefix1/file.parquet&quot;)<br><br>#Create a new table <br>data_file.writeTo(&quot;s3tablesbucket.my_first_namespace.my_table&quot;).using(&quot;Iceberg&quot;).tableProperty (&quot;format-version&quot;, &quot;2&quot;).createOrReplace()<br><br>#Query the table we created <br>spark.sql(&quot;&quot;&quot; SELECT * FROM s3tablesbucket.my_first_namespace.my_table &quot;&quot;&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITpr9A_5kG2_SOcOu2-riA.png" /></figure><h3>Integration with Amazon Athena</h3><p>Let&#39;s integrate this table with <a href="https://docs.aws.amazon.com/athena/latest/ug/gdc-register-s3-table-bucket-cat.html">Amazon Athena</a> now! Since we have created a catalog for S3 tables, this can be viewed under the Data sources and catalogs in the Athena console and you can select the drop-down option in the editor to view the s3 tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N69KBq3qOf0YEr51U-Acng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7R_NfzKoazEVOlCiGn6iw.png" /></figure><p>Now you can readily query these tables just as native Glue catalog tables in Athena</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ODbAIhhlb-FE5YBeGd6dg.png" /></figure><p>Note that since the s3 tables are managed by S3 you do not have access to the underlying S3 data location and cannot query the manifest files as when compared to <a href="https://docs.aws.amazon.com/athena/latest/ug/querying-iceberg-table-data.html">querying Iceberg table metadata for Amazon Athena-based tables.</a></p><h3>Conclusion</h3><p>Amazon S3 tables allow you to create logical tables on top of your data in S3 which is stored in parquet format for optimized read performance and these tables are based on Iceberg format which not only supports ACID transactions but also gives you the ability to perform updates, deletes, insert alongside time-travel queries for your data. This is all managed by Amazon S3 for you with the added benefits of S3’s durability, scalability, and performance.</p><p>If you’d like to know more or are interested in our services, don’t hesitate to get in touch. You can contact us <a href="https://www.doit.com/contact/?utm_source=test&amp;utm_medium=topnavcontact&amp;utm_id=top_nav_contact_link">here</a>.</p><h3>References:</h3><p>[] <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-tables.html">Working with Amazon S3 Tables and table buckets</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b12d63fc60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/doit-international/introduction-to-amazon-s3-tables-and-table-buckets-22b12d63fc60">Introduction to Amazon S3 Tables and table buckets</a> was originally published in <a href="https://medium.com/doit-international">DoiT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Machine Learning Models with SparkML: An Analysis of Ireland Rental Data]]></title>
            <link>https://swapnil-bhoite.medium.com/scaling-machine-learning-models-with-sparkml-an-analysis-of-ireland-rental-data-fce131187e55?source=rss-772637dfc6b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce131187e55</guid>
            <dc:creator><![CDATA[Swapnil Bhoite]]></dc:creator>
            <pubDate>Tue, 09 May 2023 09:01:27 GMT</pubDate>
            <atom:updated>2023-05-09T11:13:05.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Machine Learning Models with SparkML: An Analysis of Ireland Rental Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlOGs0moNjxq_EYHzcNjcQ.png" /></figure><p>In today’s data-driven world, organizations of all sizes and industries seek ways to extract valuable insights from their vast amounts of data. Machine learning has emerged as a key tool for data analysis and decision-making, but building and deploying machine learning models at scale can be a daunting task. Fortunately, SparkML, the machine learning library of the popular big data processing framework Apache Spark, is making it easier to develop scalable and efficient machine learning models. By leveraging distributed computing capabilities and a wide range of built-in algorithms and tools, SparkML is revolutionizing how we approach machine learning and data analysis.</p><ul><li>Apache Spark was developed at UC Berkeley for large-scale machine learning</li><li>Spark’s team realized it could be a general data processing platform, leading to subprojects</li><li>SparkML is a machine-learning library in Apache Spark</li><li>It provides a distributed platform for building and deploying ML models</li><li>SparkML includes algorithms and tools for data preprocessing, feature engineering, model training, and evaluation</li><li>SparkML is a popular choice for big data machine learning projects.</li><li>Spark supports various options for data storage that can be used as the source and target for the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Js0IW3emZ-jw2TE_" /></figure><h4><strong>Apache Spark offering in AWS</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I8Y7RG2LIHsa9_GZUi5DQ.png" /></figure><h4><strong>Spark ML</strong></h4><ul><li>The project focused on analyzing rental data¹ for Ireland using machine learning.</li><li>The dataset included features such as location, property type, number of bedrooms, rental price, and other relevant information.</li><li>Two machine learning models were used: random forest and decision tree. These are both popular methods for classification and regression tasks in supervised learning.</li><li>The project involved preprocessing the data, such as handling missing values, encoding categorical variables, and scaling numerical features.</li><li>The notebook code and data used for this project can be accessed through this <a href="https://github.com/swap-lm10/SparkML">GitHub repository</a>. The repository contains all the necessary files and instructions to reproduce the results presented in this study</li></ul><p>Here is the snippet of the said notebook where I ran Apache Spark locally to perform pre-processing of data, and created ML models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec4eb3920f834a0ba2512dfaf47d74ca/href">https://medium.com/media/ec4eb3920f834a0ba2512dfaf47d74ca/href</a></iframe><p>In conclusion, SparkML is an incredibly powerful tool for building scalable and efficient machine-learning models. By leveraging distributed computing capabilities and a wide range of built-in algorithms and tools, we can analyze vast amounts of data and extract valuable insights that can inform business decisions. In this study, we demonstrated how SparkML can be used to analyze Ireland rental data and build predictive models. With its ease of use, flexibility, and robustness, SparkML is poised to become the go-to framework for machine learning and data analysis in the years to come.</p><p>I would like to take this opportunity to thank you for taking the time to read this article. I hope you found it informative and useful. If you have any thoughts, questions, or feedback on the subject, I would love to hear from you. Please feel free to share your thoughts in the comments section below. Also, if you found this article helpful, please share it with others who might benefit from it. Thank you again for reading, and I look forward to hearing from you.</p><p>[1] <a href="https://www.rtb.ie/research/about-the-rent-index"><em>Rental Index data from Ireland’s Central Statistic Office (2023, April)</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce131187e55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Glue DynamicFrame transformations with example code and output]]></title>
            <link>https://swapnil-bhoite.medium.com/aws-glue-dynamicframe-transformations-with-example-code-and-output-26e14d13145f?source=rss-772637dfc6b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/26e14d13145f</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[aws-glue-studio]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Swapnil Bhoite]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 13:54:41 GMT</pubDate>
            <atom:updated>2022-04-28T14:06:56.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iC1LLDnQBZPSw2fiMaTP6Q.jpeg" /></figure><h3>Let’s begin by importing the necessary libraries and creating a GlueContext.</h3><p>Some of the transformations will need an S3 temporary path to write data to, so please replace the path in the temp_dir variable with an available S3 path to where temporary data can be written — this is typically a path pointing to a bucket in your account, but it can be any bucket the IAM role associated can reach.</p><p>The Legislators database is created by AWS Glue crawler from the public data based in s3://awsglue-datasets/examples/us-legislators/all and the payment database tables are created from public data in s3://awsglue-datasets/examples/medicare/</p><pre>import sys<br>import boto3<br>from awsglue.transforms import *<br>from awsglue.utils import getResolvedOptions<br>from pyspark.context import SparkContext<br>from awsglue.context import GlueContext<br>from awsglue.job import Job</pre><pre>glueContext = GlueContext(SparkContext.getOrCreate())<br>temp_dir = &quot;s3://swbho-iad/tempDir/&quot;</pre><p>Starting Spark application…</p><h3>SelectFields</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-SelectFields.html">SelectFields operation</a> takes fields from a DynamicFrame to keep, just like a ‘SELECT’ query on SQL would do. The output is a DynamicFrame with only the selected fields. You provide the paths in the schema to the fields to keep. Let’s start by checking one of the tables’ schema:</p><pre>persons =<br>glueContext.create_dynamic_frame.from_catalog(database=&quot;legislators&quot;, table_name=&quot;persons_json&quot;)<br>print(&quot;Count: &quot;, persons.count())<br>persons.printSchema()</pre><pre>Count:  1961<br>root<br>|-- family_name: string<br>|-- name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- gender: string<br>|-- image: string<br>|-- identifiers: array<br>|    |-- element: struct<br>|    |    |-- scheme: string<br>|    |    |-- identifier: string<br>|-- other_names: array<br>|    |-- element: struct<br>|    |    |-- lang: string<br>|    |    |-- note: string<br>|    |    |-- name: string<br>|-- sort_name: string<br>|-- images: array<br>|    |-- element: struct<br>|    |    |-- url: string<br>|-- given_name: string<br>|-- birth_date: string<br>|-- id: string<br>|-- contact_details: array<br>|    |-- element: struct<br>|    |    |-- type: string<br>|    |    |-- value: string<br>|-- death_date: string</pre><p>Now we’ll use the SelectFields method to only pick one of the fields</p><pre>persons.select_fields([&#39;family_name&#39;]).toDF().show()</pre><pre>+-----------+<br>|family_name|<br>+-----------+<br>|    Collins|<br>|   Huizenga|<br>|    Clawson|<br>|    Solomon|<br>|     Rigell|<br>|      Crapo|<br>|      Hutto|<br>|      Ertel|<br>|     Minish|<br>|    Andrews|<br>|     Walden|<br>|      Kazen|<br>|     Turner|<br>|      Kolbe|<br>|  Lowenthal|<br>|    Capuano|<br>|   Schrader|<br>|     Nadler|<br>|     Graves|<br>|   McMillan|<br>+-----------+<br>only showing top 20 rows</pre><h3>Map transformation</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-map.html">Map transformation</a> applies a function to the records of a DynamicFrame and returns a transformed DynamicFrame. The supplied function is applied to each input record and transforms it to an output record. The map transform can add fields, delete fields, and perform lookups using an external API operation. If there is an exception, processing continues, and the record is marked as an error.</p><p>Let’s start by getting a dataset to apply the map to. This is also a good opportunity to showcase how to load a dataset directly from S3:</p><pre>dyF = glueContext.create_dynamic_frame.from_options(<br>        &#39;s3&#39;,<br>        {&#39;paths&#39;: [&#39;s3://awsglue-datasets/examples/medicare/Medicare_Hospital_Provider.csv&#39;]},<br>        &#39;csv&#39;,<br>        {&#39;withHeader&#39;: True})</pre><pre>dyF.printSchema()</pre><pre>root<br>|-- DRG Definition: string<br>|-- Provider Id: string<br>|-- Provider Name: string<br>|-- Provider Street Address: string<br>|-- Provider City: string<br>|-- Provider State: string<br>|-- Provider Zip Code: string<br>|-- Hospital Referral Region Description: string<br>|-- Total Discharges: string<br>|-- Average Covered Charges: string<br>|-- Average Total Payments: string<br>|-- Average Medicare Payments: string</pre><p>Now we will define a function that will be supplied to the transformation. Think of it as a function that gets applied to every record in the dataset. The function takes one record as the input and must return a new record with the desired changes.</p><p>In this case we’ll want to group some of the existing fields into a single one, creating a nested structure. We’ll be creating a new field called “Address” that will encapsulate the following fields:</p><ul><li>Provider Street Address</li><li>Provider City</li><li>Provider State</li><li>Provider Zip Code</li></ul><p>So for each record we’ll have to create the new field, add the new subfields to it by copying the information from the original fields, then get rid of the original ones:</p><pre>def MergeAddress(rec):<br>  rec[&quot;Address&quot;] = {}<br>  rec[&quot;Address&quot;][&quot;Street&quot;] = rec[&quot;Provider Street Address&quot;]<br>  rec[&quot;Address&quot;][&quot;City&quot;] = rec[&quot;Provider City&quot;]<br>  rec[&quot;Address&quot;][&quot;State&quot;] = rec[&quot;Provider State&quot;]<br>  rec[&quot;Address&quot;][&quot;Zip.Code&quot;] = rec[&quot;Provider Zip Code&quot;]<br>  rec[&quot;Address&quot;][&quot;Array&quot;] = [rec[&quot;Provider Street Address&quot;], rec[&quot;Provider City&quot;], rec[&quot;Provider State&quot;], rec[&quot;Provider Zip Code&quot;]]<br>  del rec[&quot;Provider Street Address&quot;]<br>  del rec[&quot;Provider City&quot;]<br>  del rec[&quot;Provider State&quot;]<br>  del rec[&quot;Provider Zip Code&quot;]<br>  return rec</pre><p>Now let’s apply the Map transform to the dataset by passing this function and see what we get:</p><pre>mapped_dyF =  Map.apply(frame = dyF, f = MergeAddress)<br>mapped_dyF.printSchema()<br>print(&quot;Total count:  &quot;, mapped_dyF.count())</pre><pre>root<br>|-- Average Total Payments: string<br>|-- Average Covered Charges: string<br>|-- DRG Definition: string<br>|-- Average Medicare Payments: string<br>|-- Hospital Referral Region Description: string<br>|-- Address: struct<br>|    |-- Zip.Code: string<br>|    |-- City: string<br>|    |-- Array: array<br>|    |    |-- element: string<br>|    |-- State: string<br>|    |-- Street: string<br>|-- Provider Id: string<br>|-- Total Discharges: string<br>|-- Provider Name: string</pre><pre>Total count:   163065</pre><h3>Filter</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-filter.html">Filter transform</a> returns a filetered selection of a DynamicFrame’s records. Just like in Map, you provide a function to the transform that will be executed on each record. The function takes the record as an input and outputs a boolean value: if true, the record will be present in the output of the transform, if not it won’t.</p><p>Let’s apply this transform to the previously-loaded DynamicFrame to filter results by State and City. Notice how the record count has gone down due to the filter:</p><pre>sac_or_mon_dyF = Filter.apply(frame = dyF,<br>                              f = lambda x: x[&quot;Provider State&quot;] in [&quot;CA&quot;, &quot;AL&quot;] and x[&quot;Provider City&quot;] in [&quot;SACRAMENTO&quot;, &quot;MONTGOMERY&quot;])<br>print(&quot;Filtered record count:  &quot;, sac_or_mon_dyF.count())</pre><pre>Filtered record count:   564</pre><h3>DropFields and RenameFields</h3><p>These transformations are pretty much self-descriptive:</p><ul><li><a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-DropFields.html">DropFields</a> removes a field from a DynamicFrame. You specify which fields to remove using the paths argument. The paths argument points to a field in the schema tree structure using dot notation — for example, to remove field B which is a child of field A in the tree, you would type ‘A.B’ for the path. Several fields can be dropped at a time.</li><li><a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-RenameField.html">RenameField</a> renames a field in a DynamicFrame. You provide the new name and the path in the schema to the field to be renamed. Only one field can be renamed at a time.</li></ul><p>Let’s start by creating a DynamicFrame from the organizations catalog table in the legislators database:</p><pre>orgs = glueContext.create_dynamic_frame.from_catalog(database=&quot;legislators&quot;, table_name=&quot;organizations_json&quot;)<br>print(&quot;Count: &quot;, orgs.count())<br>orgs.printSchema()</pre><pre>Count:  13<br>root<br>|-- identifiers: array<br>|    |-- element: struct<br>|    |    |-- scheme: string<br>|    |    |-- identifier: string<br>|-- other_names: array<br>|    |-- element: struct<br>|    |    |-- lang: string<br>|    |    |-- note: string<br>|    |    |-- name: string<br>|-- id: string<br>|-- classification: string<br>|-- name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- image: string<br>|-- seats: int<br>|-- type: string</pre><p>Now let’s delete and rename some fields:</p><pre>orgs = orgs.drop_fields([&#39;other_names&#39;,&#39;identifiers&#39;]).rename_field(&#39;id&#39;, &#39;org_id&#39;).rename_field(&#39;name&#39;, &#39;org_name&#39;)<br>orgs.printSchema()</pre><pre>root<br>|-- classification: string<br>|-- org_id: string<br>|-- org_name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- image: string<br>|-- seats: int<br>|-- type: string</pre><h3>Join</h3><p>The Join transform performs an <a href="https://www.w3resource.com/sql/joins/perform-an-equi-join.php">equi-join</a> of two DynamicFrames. The join operation is performed based on the provided column keys for both DynamicFrames, and the output DynamicFrame will contain the rows where the specified keys matched.</p><p>Let’s try the Join transform by joining three tables from the legislators database: the previously-loaded persons and organizations tables and the memberships table. Load the latter as a DynamicFrame:</p><pre>memberships = glueContext.create_dynamic_frame.from_catalog(database=&quot;legislators&quot;, table_name=&quot;memberships_json&quot;)<br>print(&quot;Count: &quot;, memberships.count())<br>memberships.printSchema()</pre><pre>Count:  10439<br>root<br>|-- area_id: string<br>|-- on_behalf_of_id: string<br>|-- organization_id: string<br>|-- role: string<br>|-- person_id: string<br>|-- legislative_period_id: string<br>|-- start_date: string<br>|-- end_date: string</pre><p>Now let’s perform the join. Notice that we drop some of the fields: the join operation will keep all columns intact so the ones used to match the join keys will remain, even if they are redundant since they contain the same keys.</p><pre>l_history = Join.apply(orgs,<br>                       Join.apply(persons, memberships, &#39;id&#39;, &#39;person_id&#39;),<br>                       &#39;org_id&#39;, &#39;organization_id&#39;).drop_fields([&#39;person_id&#39;, &#39;org_id&#39;])<br>print(&quot;Count: &quot;, l_history.count())<br>l_history.printSchema()</pre><pre>Count:  10439<br>root<br>|-- role: string<br>|-- seats: int<br>|-- org_name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- type: string<br>|-- sort_name: string<br>|-- area_id: string<br>|-- images: array<br>|    |-- element: struct<br>|    |    |-- url: string<br>|-- on_behalf_of_id: string<br>|-- other_names: array<br>|    |-- element: struct<br>|    |    |-- lang: string<br>|    |    |-- note: string<br>|    |    |-- name: string<br>|-- name: string<br>|-- birth_date: string<br>|-- organization_id: string<br>|-- gender: string<br>|-- classification: string<br>|-- death_date: string<br>|-- legislative_period_id: string<br>|-- identifiers: array<br>|    |-- element: struct<br>|    |    |-- scheme: string<br>|    |    |-- identifier: string<br>|-- image: string<br>|-- given_name: string<br>|-- start_date: string<br>|-- family_name: string<br>|-- id: string<br>|-- contact_details: array<br>|    |-- element: struct<br>|    |    |-- type: string<br>|    |    |-- value: string<br>|-- end_date: string</pre><h3>Relationalize</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-Relationalize.html">Relationalize transform</a> will convert a DynamicFrame to form that fist within a relational database. The typical scenario for this is moving data from a NoSQL environment (like DynamoDB) to a relational database (like MySQL). Relational databases do not support nested structures, so this transform will flatten those structures, creating several DynamicFrames that can be written into multiple tables. Relationalize needs a name for the main output table and a temporary location to store the intermediate results.</p><p>Let’s apply this transform to the results of the join operation and see what tables are going to be created:</p><pre>dfc = l_history.relationalize(&quot;hist_root&quot;, &quot;s3://swbho-iad/tmpDir&quot;)<br>dfc.keys()</pre><pre>dict_keys([&#39;hist_root&#39;, &#39;hist_root_links&#39;, &#39;hist_root_images&#39;, &#39;hist_root_identifiers&#39;, &#39;hist_root_other_names&#39;, &#39;hist_root_contact_details&#39;])</pre><p>Now let’s compare the schema of one of the nested fields to the table that relationalize created to represent it. Notice how in the created table records are linked back to the main table via a foreign key (field ‘id’) and an index column was created to represent the positions of the array (column ‘index’):</p><pre>l_history.select_fields(&#39;contact_details&#39;).printSchema()<br>dfc.select(&#39;hist_root_contact_details&#39;).toDF().where(&quot;id = 10 or id = 75&quot;).orderBy([&#39;id&#39;,&#39;index&#39;]).show()</pre><pre>root<br>|-- contact_details: array<br>|    |-- element: struct<br>|    |    |-- type: string<br>|    |    |-- value: string</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>| 10|    0|                     fax|             202-228-3027|<br>| 10|    1|                   phone|             202-224-6542|<br>| 10|    2|                 twitter|               SenSchumer|<br>| 75|    0|                     fax|             202-224-6747|<br>| 75|    1|                   phone|             202-224-3934|<br>+---+-----+------------------------+-------------------------+</pre><h3>ResolveChoice</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-ResolveChoice.html">ResolveChoice transform</a> is used to specify how a column should be handled when it contains values of multiple types. You can choose to either cast the column to a single data type, discard one or more of the types, or retain all types in either separate columns or a structure. You can select a different resolution policy for each column or specify a global policy that is applied to all columns.</p><p>In order to test this transform we are going to load a table in the payments database in the catalog with a type discrepancy in one of its columns:</p><pre>medicare_dynamicframe = glueContext.create_dynamic_frame.from_catalog(<br>       database = &quot;payment&quot;,<br>       table_name = &quot;medicare&quot;)</pre><pre>medicare_dynamicframe.printSchema()<br>medicare_res.toDF().select(&quot;provider id&quot;).show()</pre><pre>root<br>|-- drg definition: string<br>|-- provider id: choice<br>|    |-- long<br>|    |-- string<br>|-- provider name: string<br>|-- provider street address: string<br>|-- provider city: string<br>|-- provider state: string<br>|-- provider zip code: long<br>|-- hospital referral region description: string<br>|-- total discharges: long<br>|-- average covered charges: string<br>|-- average total payments: string<br>|-- average medicare payments: string</pre><pre>+-----------+<br>|provider id|<br>+-----------+<br>|      10001|<br>|      10005|<br>|      10006|<br>|      10011|<br>|      10016|<br>|      10023|<br>|      10029|<br>|      10033|<br>|      10039|<br>|      10040|<br>|      10046|<br>|      10055|<br>|      10056|<br>|      10078|<br>|      10083|<br>|      10085|<br>|      10090|<br>|      10092|<br>|      10100|<br>|      10103|<br>+-----------+<br>only showing top 20 rows</pre><p>Notice how the ‘provider_id’ column is of ‘choice’ type, with two identified types: long and string. We can use the resolveChoice transform to take action on this. For example, let just turn everything into long values:</p><pre>medicare_res = medicare_dynamicframe.resolveChoice(specs = [(&#39;provider id&#39;,&#39;cast:long&#39;)])</pre><pre>medicare_res.printSchema()<br>medicare_res.toDF().select(&quot;provider id&quot;).show()</pre><pre>root<br>|-- drg definition: string<br>|-- provider id: long<br>|-- provider name: string<br>|-- provider street address: string<br>|-- provider city: string<br>|-- provider state: string<br>|-- provider zip code: long<br>|-- hospital referral region description: string<br>|-- total discharges: long<br>|-- average covered charges: string<br>|-- average total payments: string<br>|-- average medicare payments: string</pre><pre>+-----------+<br>|provider id|<br>+-----------+<br>|      10001|<br>|      10005|<br>|      10006|<br>|      10011|<br>|      10016|<br>|      10023|<br>|      10029|<br>|      10033|<br>|      10039|<br>|      10040|<br>|      10046|<br>|      10055|<br>|      10056|<br>|      10078|<br>|      10083|<br>|      10085|<br>|      10090|<br>|      10092|<br>|      10100|<br>|      10103|<br>+-----------+<br>only showing top 20 rows</pre><p>You can also make a new column for each type:</p><pre>df1 = ResolveChoice.apply(medicare_dynamicframe, choice = &quot;make_cols&quot;)</pre><pre>df1.printSchema()<br>df1.toDF().select(&quot;provider id_long&quot;,&quot;provider id_string&quot;).show()</pre><pre>root<br>|-- drg definition: string<br>|-- provider id_long: long<br>|-- provider id_string: string<br>|-- provider name: string<br>|-- provider street address: string<br>|-- provider city: string<br>|-- provider state: string<br>|-- provider zip code: long<br>|-- hospital referral region description: string<br>|-- total discharges: long<br>|-- average covered charges: string<br>|-- average total payments: string<br>|-- average medicare payments: string</pre><pre>+----------------+------------------+<br>|provider id_long|provider id_string|<br>+----------------+------------------+<br>|           10001|              null|<br>|           10005|              null|<br>|           10006|              null|<br>|           10011|              null|<br>|           10016|              null|<br>|           10023|              null|<br>|           10029|              null|<br>|           10033|              null|<br>|           10039|              null|<br>|           10040|              null|<br>|           10046|              null|<br>|           10055|              null|<br>|           10056|              null|<br>|           10078|              null|<br>|           10083|              null|<br>|           10085|              null|<br>|           10090|              null|<br>|           10092|              null|<br>|           10100|              null|<br>|           10103|              null|<br>+----------------+------------------+<br>only showing top 20 rows</pre><p>Or you can also turn it into a struct all found types as nested values:</p><pre>df2 = ResolveChoice.apply(medicare_dynamicframe, specs = [(&quot;provider id&quot;, &quot;make_struct&quot;)])<br>df2.printSchema()<br>df2.toDF().select(&quot;provider id&quot;).show()</pre><pre>root<br>|-- drg definition: string<br>|-- provider id: struct<br>|    |-- long: long<br>|    |-- string: string<br>|-- provider name: string<br>|-- provider street address: string<br>|-- provider city: string<br>|-- provider state: string<br>|-- provider zip code: long<br>|-- hospital referral region description: string<br>|-- total discharges: long<br>|-- average covered charges: string<br>|-- average total payments: string<br>|-- average medicare payments: string</pre><pre>+-----------+<br>|provider id|<br>+-----------+<br>|   [10001,]|<br>|   [10005,]|<br>|   [10006,]|<br>|   [10011,]|<br>|   [10016,]|<br>|   [10023,]|<br>|   [10029,]|<br>|   [10033,]|<br>|   [10039,]|<br>|   [10040,]|<br>|   [10046,]|<br>|   [10055,]|<br>|   [10056,]|<br>|   [10078,]|<br>|   [10083,]|<br>|   [10085,]|<br>|   [10090,]|<br>|   [10092,]|<br>|   [10100,]|<br>|   [10103,]|<br>+-----------+<br>only showing top 20 rows</pre><h3>SplitRows and SplitFields</h3><p>These transformations let you split your DynamicFrame by different criteria:</p><ul><li>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-SplitRows.html">SplitRows transform</a> lets you split a DynamicFrame horizontally by setting a condition based on the record’s contents.</li><li>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-SplitFields.html">SplitFields transform</a> lets you split a DynamicFrame vertically by giving it a list of fields to be separated.</li></ul><p>Let’s split one of the DynamicFrames previously generated by the Relationalize transform:</p><pre>frame_to_split=dfc.select(&#39;hist_root_contact_details&#39;)</pre><p>We’ll split it based on the values of the ‘id’ field, and we’ll give the names ‘low’ and ‘high’ to the two resulting chunks of data:</p><pre>frame_collection = SplitRows.apply(frame_to_split, {&quot;id&quot;: {&quot;&gt;&quot;: 10}}, &quot;low&quot;, &quot;high&quot;)</pre><p>This operation returns a <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-dynamic-frame-collection.html">DynamicFrameCollection</a>, an object used to represent a collection of DynamicFrames — in this case, the resulting chunks of data — as a whole. Some transforms have collection-specific versions that allow them to be applied to all DynamicFrames wihtin the collection simultaneously (<a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-MapToCollection.html">MapToCollection</a>, <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-flat-map.html">FlatMap</a>), and the <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-SelectFromCollection.html">SelectFromCollection</a> operation lets users pick an individual item from the collection:</p><pre>frame_collection.select(&#39;low&#39;).toDF().show()<br>frame_collection.select(&#39;high&#39;).toDF().show()</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>| 11|    0|                   phone|             202-224-3542|<br>| 11|    1|                 twitter|           sencortezmasto|<br>| 11|    2|                 twitter|           catherinefornv|<br>| 12|    0|                     fax|             202-224-4680|<br>| 12|    1|                   phone|             202-224-4642|<br>| 12|    2|                 twitter|              SenJackReed|<br>| 13|    0|                     fax|             202-224-4680|<br>| 13|    1|                   phone|             202-224-4642|<br>| 13|    2|                 twitter|              SenJackReed|<br>| 14|    0|                     fax|             202-224-4680|<br>| 14|    1|                   phone|             202-224-4642|<br>| 14|    2|                 twitter|              SenJackReed|<br>| 15|    0|                     fax|             202-224-4680|<br>| 15|    1|                   phone|             202-224-4642|<br>| 15|    2|                 twitter|              SenJackReed|<br>| 16|    0|                     fax|             202-224-4680|<br>| 16|    1|                   phone|             202-224-4642|<br>| 16|    2|                 twitter|              SenJackReed|<br>| 17|    0|                     fax|             202-224-4680|<br>| 17|    1|                   phone|             202-224-4642|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>|  1|    0|                     fax|             202-228-3027|<br>|  1|    1|                   phone|             202-224-6542|<br>|  1|    2|                 twitter|               SenSchumer|<br>|  2|    0|                     fax|             202-228-3027|<br>|  2|    1|                   phone|             202-224-6542|<br>|  2|    2|                 twitter|               SenSchumer|<br>|  3|    0|                     fax|             202-228-3027|<br>|  3|    1|                   phone|             202-224-6542|<br>|  3|    2|                 twitter|               SenSchumer|<br>|  4|    0|                     fax|             202-228-3027|<br>|  4|    1|                   phone|             202-224-6542|<br>|  4|    2|                 twitter|               SenSchumer|<br>|  5|    0|                     fax|             202-228-3027|<br>|  5|    1|                   phone|             202-224-6542|<br>|  5|    2|                 twitter|               SenSchumer|<br>|  6|    0|                     fax|             202-228-3027|<br>|  6|    1|                   phone|             202-224-6542|<br>|  6|    2|                 twitter|               SenSchumer|<br>|  7|    0|                     fax|             202-228-3027|<br>|  7|    1|                   phone|             202-224-6542|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><p>Now we’ll split it vertically by choosing a couple fields to separate:</p><pre>frame_to_split.printSchema()</pre><pre>root<br>|-- id: long<br>|-- index: int<br>|-- contact_details.val.type: string<br>|-- contact_details.val.value: string</pre><p>We’ll be splitting the ‘id’ and ‘index’ fields:</p><pre>frame_collection_2 = SplitFields.apply(frame_to_split, [&quot;id&quot;, &quot;index&quot;], &quot;left&quot;, &quot;right&quot;)<br>frame_collection_2.select(&quot;left&quot;).printSchema()<br>frame_collection_2.select(&quot;right&quot;).printSchema()</pre><pre>root<br>|-- id: long<br>|-- index: int</pre><pre>root<br>|-- contact_details.val.type: string<br>|-- contact_details.val.value: string</pre><h3>SelectFromCollection</h3><p>This <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-SelectFromCollection.html">transform</a> is used to select one DynamicFrame in a DynamicFrameCollection.Let’s try selecting the above two dynamic frames.</p><pre>frame_low = SelectFromCollection.apply(dfc = frame_collection, key = &quot;low&quot;)<br>frame_low.toDF().show()<br>frame_high = SelectFromCollection.apply(dfc = frame_collection, key = &quot;high&quot;)<br>frame_high.toDF().show()</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>| 11|    0|                   phone|             202-224-3542|<br>| 11|    1|                 twitter|           sencortezmasto|<br>| 11|    2|                 twitter|           catherinefornv|<br>| 12|    0|                     fax|             202-224-4680|<br>| 12|    1|                   phone|             202-224-4642|<br>| 12|    2|                 twitter|              SenJackReed|<br>| 13|    0|                     fax|             202-224-4680|<br>| 13|    1|                   phone|             202-224-4642|<br>| 13|    2|                 twitter|              SenJackReed|<br>| 14|    0|                     fax|             202-224-4680|<br>| 14|    1|                   phone|             202-224-4642|<br>| 14|    2|                 twitter|              SenJackReed|<br>| 15|    0|                     fax|             202-224-4680|<br>| 15|    1|                   phone|             202-224-4642|<br>| 15|    2|                 twitter|              SenJackReed|<br>| 16|    0|                     fax|             202-224-4680|<br>| 16|    1|                   phone|             202-224-4642|<br>| 16|    2|                 twitter|              SenJackReed|<br>| 17|    0|                     fax|             202-224-4680|<br>| 17|    1|                   phone|             202-224-4642|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>|  1|    0|                     fax|             202-228-3027|<br>|  1|    1|                   phone|             202-224-6542|<br>|  1|    2|                 twitter|               SenSchumer|<br>|  2|    0|                     fax|             202-228-3027|<br>|  2|    1|                   phone|             202-224-6542|<br>|  2|    2|                 twitter|               SenSchumer|<br>|  3|    0|                     fax|             202-228-3027|<br>|  3|    1|                   phone|             202-224-6542|<br>|  3|    2|                 twitter|               SenSchumer|<br>|  4|    0|                     fax|             202-228-3027|<br>|  4|    1|                   phone|             202-224-6542|<br>|  4|    2|                 twitter|               SenSchumer|<br>|  5|    0|                     fax|             202-228-3027|<br>|  5|    1|                   phone|             202-224-6542|<br>|  5|    2|                 twitter|               SenSchumer|<br>|  6|    0|                     fax|             202-228-3027|<br>|  6|    1|                   phone|             202-224-6542|<br>|  6|    2|                 twitter|               SenSchumer|<br>|  7|    0|                     fax|             202-228-3027|<br>|  7|    1|                   phone|             202-224-6542|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><h3>MapToCollection</h3><p>This <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-MapToCollection.html">transform</a> applies a transform to each DynamicFrame in a DynamicFrameCollection. Let’s try to apply the transformation DropNullFields to the above dynamicframe x.</p><pre>returned_collection = MapToCollection.apply(dfc=frame_collection, callable=DropNullFields())<br>for x in returned_collection.keys():<br>    y = returned_collection.select(x)<br>    print(x)<br>    y.printSchema()<br>    y.toDF().show()</pre><pre>null_fields []<br>null_fields []<br>low<br>root<br>|-- id: long<br>|-- index: int<br>|-- contact_details.val.type: string<br>|-- contact_details.val.value: string</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>| 11|    0|                   phone|             202-224-3542|<br>| 11|    1|                 twitter|           sencortezmasto|<br>| 11|    2|                 twitter|           catherinefornv|<br>| 12|    0|                     fax|             202-224-4680|<br>| 12|    1|                   phone|             202-224-4642|<br>| 12|    2|                 twitter|              SenJackReed|<br>| 13|    0|                     fax|             202-224-4680|<br>| 13|    1|                   phone|             202-224-4642|<br>| 13|    2|                 twitter|              SenJackReed|<br>| 14|    0|                     fax|             202-224-4680|<br>| 14|    1|                   phone|             202-224-4642|<br>| 14|    2|                 twitter|              SenJackReed|<br>| 15|    0|                     fax|             202-224-4680|<br>| 15|    1|                   phone|             202-224-4642|<br>| 15|    2|                 twitter|              SenJackReed|<br>| 16|    0|                     fax|             202-224-4680|<br>| 16|    1|                   phone|             202-224-4642|<br>| 16|    2|                 twitter|              SenJackReed|<br>| 17|    0|                     fax|             202-224-4680|<br>| 17|    1|                   phone|             202-224-4642|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><pre>high<br>root<br>|-- id: long<br>|-- index: int<br>|-- contact_details.val.type: string<br>|-- contact_details.val.value: string</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>|  1|    0|                     fax|             202-228-3027|<br>|  1|    1|                   phone|             202-224-6542|<br>|  1|    2|                 twitter|               SenSchumer|<br>|  2|    0|                     fax|             202-228-3027|<br>|  2|    1|                   phone|             202-224-6542|<br>|  2|    2|                 twitter|               SenSchumer|<br>|  3|    0|                     fax|             202-228-3027|<br>|  3|    1|                   phone|             202-224-6542|<br>|  3|    2|                 twitter|               SenSchumer|<br>|  4|    0|                     fax|             202-228-3027|<br>|  4|    1|                   phone|             202-224-6542|<br>|  4|    2|                 twitter|               SenSchumer|<br>|  5|    0|                     fax|             202-228-3027|<br>|  5|    1|                   phone|             202-224-6542|<br>|  5|    2|                 twitter|               SenSchumer|<br>|  6|    0|                     fax|             202-228-3027|<br>|  6|    1|                   phone|             202-224-6542|<br>|  6|    2|                 twitter|               SenSchumer|<br>|  7|    0|                     fax|             202-228-3027|<br>|  7|    1|                   phone|             202-224-6542|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><h3>MergeDynamicFrame</h3><p>This <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-dynamic-frame.html#aws-glue-api-crawler-pyspark-extensions-dynamic-frame-merge">transform</a> merges a DynamicFrame with a staging DynamicFrame based on the specified primary keys to identify records. Duplicate records (records with the same primary keys) are not de-duplicated. If there is no matching record in the staging frame, all records (including duplicates) are retained from the source. If the staging frame has matching records, the records from the staging frame overwrite the records in the source in AWS Glue. Let’s try to merge frame_high and frame_low.</p><pre>merged_frame = frame_high.mergeDynamicFrame(frame_low, [&quot;id&quot;]) <br>merged_frame.toDF().show()</pre><pre>+---+-----+------------------------+-------------------------+<br>| id|index|contact_details.val.type|contact_details.val.value|<br>+---+-----+------------------------+-------------------------+<br>|  7|    0|                     fax|             202-228-3027|<br>|  7|    1|                   phone|             202-224-6542|<br>|  7|    2|                 twitter|               SenSchumer|<br>|  6|    0|                     fax|             202-228-3027|<br>|  6|    1|                   phone|             202-224-6542|<br>|  6|    2|                 twitter|               SenSchumer|<br>|  9|    0|                     fax|             202-228-3027|<br>|  9|    1|                   phone|             202-224-6542|<br>|  9|    2|                 twitter|               SenSchumer|<br>|  5|    0|                     fax|             202-228-3027|<br>|  5|    1|                   phone|             202-224-6542|<br>|  5|    2|                 twitter|               SenSchumer|<br>|  1|    0|                     fax|             202-228-3027|<br>|  1|    1|                   phone|             202-224-6542|<br>|  1|    2|                 twitter|               SenSchumer|<br>| 10|    0|                     fax|             202-228-3027|<br>| 10|    1|                   phone|             202-224-6542|<br>| 10|    2|                 twitter|               SenSchumer|<br>|  3|    0|                     fax|             202-228-3027|<br>|  3|    1|                   phone|             202-224-6542|<br>+---+-----+------------------------+-------------------------+<br>only showing top 20 rows</pre><h3>Unbox</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-Unbox.html">Unbox transform</a> unboxes a string field from a DynamicFrame. The output is a DynamicFrame with the selected string field reformatted. The string field can be parsed and replaced with several fields. You provide a path in the schema for the string field to reformat and its current format type. For example, you might have a CSV file that has one field that is in JSON format {“a”: 3, “b”: “foo”, “c”: 1.2}. This transform can reformat the JSON into three fields: an int, a string, and a double.</p><p>None of our datasets have a String field representing such a structure, so we’ll generate one. The Map transform example generated a new JSON struct field, so we’ll reuse the map function there to generate a new field that’s just the String version of that JSON struct:</p><pre>import json</pre><pre>def MergeAddressToString(rec):<br>  rec[&quot;Address&quot;] = {}<br>  rec[&quot;Address&quot;][&quot;Street&quot;] = rec[&quot;Provider Street Address&quot;]<br>  rec[&quot;Address&quot;][&quot;City&quot;] = rec[&quot;Provider City&quot;]<br>  rec[&quot;Address&quot;][&quot;State&quot;] = rec[&quot;Provider State&quot;]<br>  rec[&quot;Address&quot;][&quot;Zip.Code&quot;] = rec[&quot;Provider Zip Code&quot;]<br>  rec[&quot;Address&quot;][&quot;Array&quot;] = [rec[&quot;Provider Street Address&quot;], rec[&quot;Provider City&quot;], rec[&quot;Provider State&quot;], rec[&quot;Provider Zip Code&quot;]]<br>  del rec[&quot;Provider Street Address&quot;]<br>  del rec[&quot;Provider City&quot;]<br>  del rec[&quot;Provider State&quot;]<br>  del rec[&quot;Provider Zip Code&quot;]<br>  rec[&quot;AddressString&quot;] = json.dumps(rec[&quot;Address&quot;])<br>  return rec</pre><p>Now we’ll apply the mapping and check the new String field is there:</p><pre>mapped_with_string =  Map.apply(frame = dyF, f = MergeAddressToString)<br>mapped_with_string.printSchema()<br>mapped_with_string.toDF().show()</pre><pre>root<br>|-- Average Total Payments: string<br>|-- AddressString: string<br>|-- Average Covered Charges: string<br>|-- DRG Definition: string<br>|-- Average Medicare Payments: string<br>|-- Hospital Referral Region Description: string<br>|-- Address: struct<br>|    |-- Zip.Code: string<br>|    |-- City: string<br>|    |-- Array: array<br>|    |    |-- element: string<br>|    |-- State: string<br>|    |-- Street: string<br>|-- Provider Id: string<br>|-- Total Discharges: string<br>|-- Provider Name: string</pre><pre>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>|Average Total Payments|       AddressString|Average Covered Charges|      DRG Definition|Average Medicare Payments|Hospital Referral Region Description|             Address|Provider Id|Total Discharges|       Provider Name|<br>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>|              $5777.24|{&quot;Street&quot;: &quot;1108 ...|              $32963.07|039 - EXTRACRANIA...|                 $4763.73|                         AL - Dothan|[36301, DOTHAN, [...|      10001|              91|SOUTHEAST ALABAMA...|<br>|              $5787.57|{&quot;Street&quot;: &quot;2505 ...|              $15131.85|039 - EXTRACRANIA...|                 $4976.71|                     AL - Birmingham|[35957, BOAZ, [25...|      10005|              14|MARSHALL MEDICAL ...|<br>|              $5434.95|{&quot;Street&quot;: &quot;205 M...|              $37560.37|039 - EXTRACRANIA...|                 $4453.79|                     AL - Birmingham|[35631, FLORENCE,...|      10006|              24|ELIZA COFFEE MEMO...|<br>|              $5417.56|{&quot;Street&quot;: &quot;50 ME...|              $13998.28|039 - EXTRACRANIA...|                 $4129.16|                     AL - Birmingham|[35235, BIRMINGHA...|      10011|              25|   ST VINCENT&#39;S EAST|<br>|              $5658.33|{&quot;Street&quot;: &quot;1000 ...|              $31633.27|039 - EXTRACRANIA...|                 $4851.44|                     AL - Birmingham|[35007, ALABASTER...|      10016|              18|SHELBY BAPTIST ME...|<br>|              $6653.80|{&quot;Street&quot;: &quot;2105 ...|              $16920.79|039 - EXTRACRANIA...|                 $5374.14|                     AL - Montgomery|[36116, MONTGOMER...|      10023|              67|BAPTIST MEDICAL C...|<br>|              $5834.74|{&quot;Street&quot;: &quot;2000 ...|              $11977.13|039 - EXTRACRANIA...|                 $4761.41|                     AL - Birmingham|[36801, OPELIKA, ...|      10029|              51|EAST ALABAMA MEDI...|<br>|              $8031.12|{&quot;Street&quot;: &quot;619 S...|              $35841.09|039 - EXTRACRANIA...|                 $5858.50|                     AL - Birmingham|[35233, BIRMINGHA...|      10033|              32|UNIVERSITY OF ALA...|<br>|              $6113.38|{&quot;Street&quot;: &quot;101 S...|              $28523.39|039 - EXTRACRANIA...|                 $5228.40|                     AL - Huntsville|[35801, HUNTSVILL...|      10039|             135| HUNTSVILLE HOSPITAL|<br>|              $5541.05|{&quot;Street&quot;: &quot;1007 ...|              $75233.38|039 - EXTRACRANIA...|                 $4386.94|                     AL - Birmingham|[35903, GADSDEN, ...|      10040|              34|GADSDEN REGIONAL ...|<br>|              $5461.57|{&quot;Street&quot;: &quot;600 S...|              $67327.92|039 - EXTRACRANIA...|                 $4493.57|                     AL - Birmingham|[35901, GADSDEN, ...|      10046|              14|RIVERVIEW REGIONA...|<br>|              $5356.28|{&quot;Street&quot;: &quot;4370 ...|              $39607.28|039 - EXTRACRANIA...|                 $4408.20|                         AL - Dothan|[36305, DOTHAN, [...|      10055|              45|    FLOWERS HOSPITAL|<br>|              $5374.65|{&quot;Street&quot;: &quot;810 S...|              $22862.23|039 - EXTRACRANIA...|                 $4186.02|                     AL - Birmingham|[35205, BIRMINGHA...|      10056|              43|ST VINCENT&#39;S BIRM...|<br>|              $5366.23|{&quot;Street&quot;: &quot;400 E...|              $31110.85|039 - EXTRACRANIA...|                 $4376.23|                     AL - Birmingham|[36207, ANNISTON,...|      10078|              21|NORTHEAST ALABAMA...|<br>|              $5282.93|{&quot;Street&quot;: &quot;1613 ...|              $25411.33|039 - EXTRACRANIA...|                 $4383.73|                         AL - Mobile|[36535, FOLEY, [1...|      10083|              15|SOUTH BALDWIN REG...|<br>|              $5676.55|{&quot;Street&quot;: &quot;1201 ...|               $9234.51|039 - EXTRACRANIA...|                 $4509.11|                     AL - Huntsville|[35609, DECATUR, ...|      10085|              27|DECATUR GENERAL H...|<br>|              $5930.11|{&quot;Street&quot;: &quot;6801 ...|              $15895.85|039 - EXTRACRANIA...|                 $3972.85|                         AL - Mobile|[36608, MOBILE, [...|      10090|              27| PROVIDENCE HOSPITAL|<br>|              $6192.54|{&quot;Street&quot;: &quot;809 U...|              $19721.16|039 - EXTRACRANIA...|                 $5179.38|                     AL - Tuscaloosa|[35401, TUSCALOOS...|      10092|              31|D C H REGIONAL ME...|<br>|              $4968.00|{&quot;Street&quot;: &quot;750 M...|              $10710.88|039 - EXTRACRANIA...|                 $3898.88|                         AL - Mobile|[36532, FAIRHOPE,...|      10100|              18|     THOMAS HOSPITAL|<br>|              $5996.00|{&quot;Street&quot;: &quot;701 P...|              $51343.75|039 - EXTRACRANIA...|                 $4962.45|                     AL - Birmingham|[35211, BIRMINGHA...|      10103|              33|BAPTIST MEDICAL C...|<br>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>only showing top 20 rows</pre><p>Applying the unbox transform turns that new field into a struct-type field:</p><pre>unboxed = mapped_with_string.unbox(&quot;AddressString&quot;, &quot;json&quot;)<br>unboxed.printSchema()<br>unboxed.toDF().show()</pre><pre>root<br>|-- Average Total Payments: string<br>|-- AddressString: struct<br>|    |-- Street: string<br>|    |-- City: string<br>|    |-- State: string<br>|    |-- Zip.Code: string<br>|    |-- Array: array<br>|    |    |-- element: string<br>|-- Average Covered Charges: string<br>|-- DRG Definition: string<br>|-- Average Medicare Payments: string<br>|-- Hospital Referral Region Description: string<br>|-- Address: struct<br>|    |-- Zip.Code: string<br>|    |-- City: string<br>|    |-- Array: array<br>|    |    |-- element: string<br>|    |-- State: string<br>|    |-- Street: string<br>|-- Provider Id: string<br>|-- Total Discharges: string<br>|-- Provider Name: string</pre><pre>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>|Average Total Payments|       AddressString|Average Covered Charges|      DRG Definition|Average Medicare Payments|Hospital Referral Region Description|             Address|Provider Id|Total Discharges|       Provider Name|<br>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>|              $5777.24|[1108 ROSS CLARK ...|              $32963.07|039 - EXTRACRANIA...|                 $4763.73|                         AL - Dothan|[36301, DOTHAN, [...|      10001|              91|SOUTHEAST ALABAMA...|<br>|              $5787.57|[2505 U S HIGHWAY...|              $15131.85|039 - EXTRACRANIA...|                 $4976.71|                     AL - Birmingham|[35957, BOAZ, [25...|      10005|              14|MARSHALL MEDICAL ...|<br>|              $5434.95|[205 MARENGO STRE...|              $37560.37|039 - EXTRACRANIA...|                 $4453.79|                     AL - Birmingham|[35631, FLORENCE,...|      10006|              24|ELIZA COFFEE MEMO...|<br>|              $5417.56|[50 MEDICAL PARK ...|              $13998.28|039 - EXTRACRANIA...|                 $4129.16|                     AL - Birmingham|[35235, BIRMINGHA...|      10011|              25|   ST VINCENT&#39;S EAST|<br>|              $5658.33|[1000 FIRST STREE...|              $31633.27|039 - EXTRACRANIA...|                 $4851.44|                     AL - Birmingham|[35007, ALABASTER...|      10016|              18|SHELBY BAPTIST ME...|<br>|              $6653.80|[2105 EAST SOUTH ...|              $16920.79|039 - EXTRACRANIA...|                 $5374.14|                     AL - Montgomery|[36116, MONTGOMER...|      10023|              67|BAPTIST MEDICAL C...|<br>|              $5834.74|[2000 PEPPERELL P...|              $11977.13|039 - EXTRACRANIA...|                 $4761.41|                     AL - Birmingham|[36801, OPELIKA, ...|      10029|              51|EAST ALABAMA MEDI...|<br>|              $8031.12|[619 SOUTH 19TH S...|              $35841.09|039 - EXTRACRANIA...|                 $5858.50|                     AL - Birmingham|[35233, BIRMINGHA...|      10033|              32|UNIVERSITY OF ALA...|<br>|              $6113.38|[101 SIVLEY RD, H...|              $28523.39|039 - EXTRACRANIA...|                 $5228.40|                     AL - Huntsville|[35801, HUNTSVILL...|      10039|             135| HUNTSVILLE HOSPITAL|<br>|              $5541.05|[1007 GOODYEAR AV...|              $75233.38|039 - EXTRACRANIA...|                 $4386.94|                     AL - Birmingham|[35903, GADSDEN, ...|      10040|              34|GADSDEN REGIONAL ...|<br>|              $5461.57|[600 SOUTH THIRD ...|              $67327.92|039 - EXTRACRANIA...|                 $4493.57|                     AL - Birmingham|[35901, GADSDEN, ...|      10046|              14|RIVERVIEW REGIONA...|<br>|              $5356.28|[4370 WEST MAIN S...|              $39607.28|039 - EXTRACRANIA...|                 $4408.20|                         AL - Dothan|[36305, DOTHAN, [...|      10055|              45|    FLOWERS HOSPITAL|<br>|              $5374.65|[810 ST VINCENT&#39;S...|              $22862.23|039 - EXTRACRANIA...|                 $4186.02|                     AL - Birmingham|[35205, BIRMINGHA...|      10056|              43|ST VINCENT&#39;S BIRM...|<br>|              $5366.23|[400 EAST 10TH ST...|              $31110.85|039 - EXTRACRANIA...|                 $4376.23|                     AL - Birmingham|[36207, ANNISTON,...|      10078|              21|NORTHEAST ALABAMA...|<br>|              $5282.93|[1613 NORTH MCKEN...|              $25411.33|039 - EXTRACRANIA...|                 $4383.73|                         AL - Mobile|[36535, FOLEY, [1...|      10083|              15|SOUTH BALDWIN REG...|<br>|              $5676.55|[1201 7TH STREET ...|               $9234.51|039 - EXTRACRANIA...|                 $4509.11|                     AL - Huntsville|[35609, DECATUR, ...|      10085|              27|DECATUR GENERAL H...|<br>|              $5930.11|[6801 AIRPORT BOU...|              $15895.85|039 - EXTRACRANIA...|                 $3972.85|                         AL - Mobile|[36608, MOBILE, [...|      10090|              27| PROVIDENCE HOSPITAL|<br>|              $6192.54|[809 UNIVERSITY B...|              $19721.16|039 - EXTRACRANIA...|                 $5179.38|                     AL - Tuscaloosa|[35401, TUSCALOOS...|      10092|              31|D C H REGIONAL ME...|<br>|              $4968.00|[750 MORPHY AVENU...|              $10710.88|039 - EXTRACRANIA...|                 $3898.88|                         AL - Mobile|[36532, FAIRHOPE,...|      10100|              18|     THOMAS HOSPITAL|<br>|              $5996.00|[701 PRINCETON AV...|              $51343.75|039 - EXTRACRANIA...|                 $4962.45|                     AL - Birmingham|[35211, BIRMINGHA...|      10103|              33|BAPTIST MEDICAL C...|<br>+----------------------+--------------------+-----------------------+--------------------+-------------------------+------------------------------------+--------------------+-----------+----------------+--------------------+<br>only showing top 20 rows</pre><h3>UnnestFrame</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-UnnestFrame.html">UnnestFrame transform</a> will flatten all struct fields within a DynamicFrame to top-level elements and generate joinkeys for array objects.</p><p>We can use the output of the Map transform to check this:</p><pre>mapped_dyF.printSchema()<br>mapped_dyF.toDF().select(&quot;Address&quot;).show()</pre><pre>root<br>|-- Average Total Payments: string<br>|-- Average Covered Charges: string<br>|-- DRG Definition: string<br>|-- Average Medicare Payments: string<br>|-- Hospital Referral Region Description: string<br>|-- Address: struct<br>|    |-- Zip.Code: string<br>|    |-- City: string<br>|    |-- Array: array<br>|    |    |-- element: string<br>|    |-- State: string<br>|    |-- Street: string<br>|-- Provider Id: string<br>|-- Total Discharges: string<br>|-- Provider Name: string</pre><pre>+--------------------+<br>|             Address|<br>+--------------------+<br>|[36301, DOTHAN, [...|<br>|[35957, BOAZ, [25...|<br>|[35631, FLORENCE,...|<br>|[35235, BIRMINGHA...|<br>|[35007, ALABASTER...|<br>|[36116, MONTGOMER...|<br>|[36801, OPELIKA, ...|<br>|[35233, BIRMINGHA...|<br>|[35801, HUNTSVILL...|<br>|[35903, GADSDEN, ...|<br>|[35901, GADSDEN, ...|<br>|[36305, DOTHAN, [...|<br>|[35205, BIRMINGHA...|<br>|[36207, ANNISTON,...|<br>|[36535, FOLEY, [1...|<br>|[35609, DECATUR, ...|<br>|[36608, MOBILE, [...|<br>|[35401, TUSCALOOS...|<br>|[36532, FAIRHOPE,...|<br>|[35211, BIRMINGHA...|<br>+--------------------+<br>only showing top 20 rows</pre><p>By unnesting it, all fields within the struct become top-level elements:</p><pre>unnested = UnnestFrame.apply(mapped_dyF)<br>unnested.printSchema()</pre><pre>root<br>|-- Average Total Payments: string<br>|-- Average Covered Charges: string<br>|-- DRG Definition: string<br>|-- Average Medicare Payments: string<br>|-- Hospital Referral Region Description: string<br>|-- Address.Zip.Code: string<br>|-- Address.City: string<br>|-- Address.Array: array<br>|    |-- element: string<br>|-- Address.State: string<br>|-- Address.Street: string<br>|-- Provider Id: string<br>|-- Total Discharges: string<br>|-- Provider Name: string</pre><h3>DropNullFields</h3><p>The <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-DropNullFields.html">DropNullFields transform</a> will output a new DynamicFrame where the fields of type ‘NullType’ will have been dropped. These are fields with missing or null values in every record in the DynamicFrame data set.</p><p>In order to test this we’ll add a new column of type null to the already-loaded ‘persons’ dataset:</p><pre>from pyspark.sql.functions import lit<br>from pyspark.sql.types import NullType<br>from awsglue.dynamicframe import DynamicFrame</pre><pre>persons_with_nulls = persons.toDF().withColumn(&#39;empty_column&#39;, lit(None).cast(NullType()))</pre><pre>persons_with_nulls_dyf = DynamicFrame.fromDF(persons_with_nulls, glueContext, &#39;persons_with_nulls&#39;)<br>persons_with_nulls_dyf.printSchema()</pre><pre>root<br>|-- family_name: string<br>|-- name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- gender: string<br>|-- image: string<br>|-- identifiers: array<br>|    |-- element: struct<br>|    |    |-- scheme: string<br>|    |    |-- identifier: string<br>|-- other_names: array<br>|    |-- element: struct<br>|    |    |-- lang: string<br>|    |    |-- note: string<br>|    |    |-- name: string<br>|-- sort_name: string<br>|-- images: array<br>|    |-- element: struct<br>|    |    |-- url: string<br>|-- given_name: string<br>|-- birth_date: string<br>|-- id: string<br>|-- contact_details: array<br>|    |-- element: struct<br>|    |    |-- type: string<br>|    |    |-- value: string<br>|-- death_date: string<br>|-- empty_column: null</pre><p>Applying the transform gets rid of this new column:</p><pre>nonulls = DropNullFields.apply(persons_with_nulls_dyf)<br>nonulls.printSchema()</pre><pre>null_fields [&#39;empty_column&#39;]<br>root<br>|-- family_name: string<br>|-- name: string<br>|-- links: array<br>|    |-- element: struct<br>|    |    |-- note: string<br>|    |    |-- url: string<br>|-- gender: string<br>|-- image: string<br>|-- identifiers: array<br>|    |-- element: struct<br>|    |    |-- scheme: string<br>|    |    |-- identifier: string<br>|-- other_names: array<br>|    |-- element: struct<br>|    |    |-- lang: string<br>|    |    |-- note: string<br>|    |    |-- name: string<br>|-- sort_name: string<br>|-- images: array<br>|    |-- element: struct<br>|    |    |-- url: string<br>|-- given_name: string<br>|-- birth_date: string<br>|-- id: string<br>|-- contact_details: array<br>|    |-- element: struct<br>|    |    |-- type: string<br>|    |    |-- value: string<br>|-- death_date: string</pre><h3>Error handling</h3><p>DynamicFrames are able to create error records upon certain error scenarios instead of failing like DataFrames would do. In order to showcase this we will load some sample JSON data where one of the records is malformed — it’s cut halfway through. This malformation would break the parsing of the file by Spark SQL, but DynamicFrames are able to recognize the issue and turn the malformed lines into an error record, which then can be handled individually.</p><p>Start by downloading the file error.json from the attachments in the <a href="https://w.amazon.com/bin/view/AmazonWebServices/SalesSupport/DeveloperSupport/Internal/Big_Data/Glue/Training/152-Glue-Transformations-Examples/#Attachments">wiki</a> locally to your computer and checking its contents. You’ll see how the second record is malformed, leading to the third being malformed as well (since it’s the closest closing bracket). Please upload the file in an S3 bucket and load that file to see what happens.</p><pre>errors = glueContext.create_dynamic_frame.from_options(<br>        &#39;s3&#39;,<br>        {&#39;paths&#39;: [&#39;s3://swbho-iad/Glue107/error.json&#39;]},<br>        &#39;json&#39;)</pre><pre>errors.printSchema()<br>errors.toDF().show()</pre><pre>root<br>|-- id: int<br>|-- name: string<br>|-- surname: string<br>|-- height: int</pre><pre>+---+------+----------+------+<br>| id|  name|   surname|height|<br>+---+------+----------+------+<br>|  1|george|washington|   178|<br>|  4|  john|       jay|   190|<br>+---+------+----------+------+</pre><p>As expected, only the first and fourth records weere properly loaded — the rest were not properly loaded. <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-dynamic-frame.html#aws-glue-api-crawler-pyspark-extensions-dynamic-frame-_errors">There’s a variety of methods</a> to handle these errors. Let’s see how many of them there are:</p><pre>errors.errorsCount()</pre><pre>1</pre><p>Error records contain information about the error itself. You can check the included information by exploring the record’s schema:</p><pre>print(&quot;output 1&quot;)<br>errors.errorsAsDynamicFrame().toDF().show()</pre><pre>print(&quot;output 2&quot;)<br>error = errors.errorsAsDynamicFrame().toDF().head()<br>print(&quot;output 3&quot;)<br>print(error.asDict().keys())</pre><pre>print(&quot;output 4&quot;)<br>error_fields = error[&#39;error&#39;]<br>print(&quot;output 5&quot;)<br>print(error_fields.asDict().keys())</pre><pre>print(&quot;output 6&quot;)<br>for key in error_fields.asDict().keys():<br>    print(&quot;\n&quot; + key + &quot;: &quot; + str(error_fields[key]))</pre><pre>output 1<br>+--------------------+<br>|               error|<br>+--------------------+<br>|[[  File &quot;/mnt/ya...|<br>+--------------------+</pre><pre>output 2<br>output 3<br>dict_keys([&#39;error&#39;])<br>output 4<br>output 5<br>dict_keys([&#39;callsite&#39;, &#39;msg&#39;, &#39;stackTrace&#39;, &#39;input&#39;, &#39;bytesread&#39;, &#39;source&#39;, &#39;dynamicRecord&#39;])<br>output 6</pre><pre>callsite: Row(site=&#39;  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/tmp/7874088785197734960&quot;, line 700, in &lt;module&gt;\n    sys.exit(main())\n  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/tmp/7874088785197734960&quot;, line 672, in main\n    response = handler(content)\n  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/tmp/7874088785197734960&quot;, line 318, in execute_request\n    result = node.execute()\n  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/tmp/7874088785197734960&quot;, line 224, in execute\n    exec(code, global_dict)\n  File &quot;&lt;stdin&gt;&quot;, line 4, in &lt;module&gt;\n  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/PyGlue.zip/awsglue/dynamicframe.py&quot;, line 608, in from_options\n    format_options, transformation_ctx, push_down_predicate, **kwargs)\n  File &quot;/mnt/yarn/usercache/livy/appcache/application_1620594693813_0001/container_1620594693813_0001_01_000001/PyGlue.zip/awsglue/context.py&quot;, line 202, in create_dynamic_frame_from_options\n    source.setFormat(format, **format_options)\n&#39;, info=&#39;&#39;)</pre><pre>msg: error in jackson reader</pre><pre>stackTrace: com.fasterxml.jackson.core.JsonParseException: Unexpected character (&#39;{&#39; (code 123)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name<br> at [Source: com.amazonaws.services.glue.readers.BufferedStream@25b7a31; line: 3, column: 2]<br>	at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1586)<br>	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:521)<br>	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:450)<br>	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleOddName(UTF8StreamJsonParser.java:2031)<br>	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parseName(UTF8StreamJsonParser.java:1669)<br>	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:752)<br>	at com.amazonaws.services.glue.readers.JacksonReader$$anonfun$hasNextGoodToken$1.apply(JacksonReader.scala:57)<br>	at com.amazonaws.services.glue.readers.JacksonReader$$anonfun$hasNextGoodToken$1.apply(JacksonReader.scala:57)<br>	at scala.collection.Iterator$$anon$9.next(Iterator.scala:162)<br>	at scala.collection.Iterator$$anon$16.hasNext(Iterator.scala:599)<br>	at scala.collection.Iterator$$anon$16.hasNext(Iterator.scala:598)<br>	at scala.collection.Iterator$class.foreach(Iterator.scala:891)<br>	at scala.collection.AbstractIterator.foreach(Iterator.scala:1334)<br>	at com.amazonaws.services.glue.readers.JacksonReader$$anonfun$1.apply(JacksonReader.scala:120)<br>	at com.amazonaws.services.glue.readers.JacksonReader$$anonfun$1.apply(JacksonReader.scala:116)<br>	at com.amazonaws.services.glue.DynamicRecordBuilder.handleErr(DynamicRecordBuilder.scala:210)<br>	at com.amazonaws.services.glue.DynamicRecordBuilder.handleErrorWithException(DynamicRecordBuilder.scala:203)<br>	at com.amazonaws.services.glue.readers.JacksonReader.nextFailSafe(JacksonReader.scala:116)<br>	at com.amazonaws.services.glue.readers.JacksonReader.next(JacksonReader.scala:109)<br>	at com.amazonaws.services.glue.readers.JSONReader.next(JSONReader.scala:207)<br>	at com.amazonaws.services.glue.hadoop.TapeHadoopRecordReaderSplittable.nextKeyValue(TapeHadoopRecordReaderSplittable.scala:103)<br>	at org.apache.spark.rdd.NewHadoopRDD$$anon$1.hasNext(NewHadoopRDD.scala:230)<br>	at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:462)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:462)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)<br>	at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:255)<br>	at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:247)<br>	at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)<br>	at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)<br>	at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)<br>	at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)<br>	at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)<br>	at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)<br>	at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)<br>	at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)<br>	at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)<br>	at org.apache.spark.scheduler.Task.run(Task.scala:121)<br>	at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)<br>	at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)<br>	at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)<br>	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)<br>	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)<br>	at java.lang.Thread.run(Thread.java:748)<br></pre><pre>input: </pre><pre>bytesread: 249</pre><pre>source: </pre><pre>dynamicRecord: Row(id=2, name=&#39;benjamin&#39;, surname=&#39;franklin&#39;)</pre><p>It’s important to note that <strong>unlike the Scala API, the Python API will not propagate error records through transformations</strong>. Applying a map transformation will remove the errors from the dataset:</p><pre>def MergeFields(rec):<br>  rec[&quot;NewField&quot;] = str(rec[&quot;id&quot;]) + rec[&quot;name&quot;]<br>  return rec</pre><pre>transformed =  Map.apply(frame = errors, f = MergeFields)<br>transformed.printSchema()<br>transformed.errorsCount()</pre><pre>root<br>|-- NewField: string<br>|-- name: string<br>|-- height: int<br>|-- surname: string<br>|-- id: int</pre><pre>0</pre><h3>Spigot</h3><p>The Spigot <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-spigot.html">transform</a> writes sample records to a specified destination during a transformation. Let’s try to use this transform on the nonulls dynamicframe created earlier in the notebook. Please check the output in the s3: bucket ‘yourS3bucket’ mentioned below.</p><pre>Spigot_output = Spigot.apply(frame = nonulls, path = &quot;s3://swbho-iad/Glue107/&quot;, options = {&quot;topk&quot;:10, &quot;prob&quot;:0.2})<br>Spigot_output.toDF().show()</pre><pre>+-----------+------------------+--------------------+------+--------------------+--------------------+--------------------+----------------+--------------------+----------+----------+--------------------+--------------------+----------+<br>|family_name|              name|               links|gender|               image|         identifiers|         other_names|       sort_name|              images|given_name|birth_date|                  id|     contact_details|death_date|<br>+-----------+------------------+--------------------+------+--------------------+--------------------+--------------------+----------------+--------------------+----------+----------+--------------------+--------------------+----------+<br>|    Collins|       Mac Collins|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, C0006...|[[bar, multilingu...|Collins, Michael|[[https://theunit...|   Michael|1944-10-15|0005af3a-9471-4d1...|                null|      null|<br>|   Huizenga|     Bill Huizenga|[[Wikipedia (de),...|  male|https://theunited...|[[ballotpedia, Bi...|[[da, multilingua...|  Huizenga, Bill|[[https://theunit...|      Bill|1969-01-31|00aa2dc0-bfb6-441...|[[fax, 202-226-07...|      null|<br>|    Clawson|      Curt Clawson|[[Wikipedia (comm...|  male|https://theunited...|[[bioguide, C0011...|[[bar, multilingu...| Clawson, Curtis|[[https://theunit...|    Curtis|1959-09-28|00aca284-9323-495...|[[phone, 202-225-...|      null|<br>|    Solomon|    Gerald Solomon|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, S0006...|[[, alternate, Ge...| Solomon, Gerald|[[https://theunit...|    Gerald|1930-08-14|00b73df5-4180-441...|                null|2001-10-26|<br>|     Rigell|   E. Scott Rigell|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, R0005...|[[, alternate, Sc...|  Rigell, Edward|[[https://theunit...|    Edward|1960-05-28|00bee44f-db04-4a7...|[[fax, 202-225-42...|      null|<br>|      Crapo|        Mike Crapo|[[Wikipedia (da),...|  male|https://theunited...|[[ballotpedia, Mi...|[[da, multilingua...|  Crapo, Michael|[[https://theunit...|   Michael|1951-05-20|00f8f12d-6e27-4a2...|[[twitter, MikeCr...|      null|<br>|      Hutto|        Earl Hutto|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, H0010...|[[, alternate, Ea...|     Hutto, Earl|[[https://theunit...|      Earl|1926-05-12|015d77c8-6edb-4ed...|                null|      null|<br>|      Ertel|       Allen Ertel|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, E0002...|[[, alternate, Al...|    Ertel, Allen|[[https://theunit...|     Allen|1937-11-07|01679bc3-da21-482...|                null|2015-11-19|<br>|     Minish|     Joseph Minish|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, M0007...|[[bar, multilingu...|  Minish, Joseph|[[https://theunit...|    Joseph|1916-09-01|018247d0-2961-423...|                null|2007-11-24|<br>|    Andrews| Robert E. Andrews|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, A0002...|[[, alternate, Ro...| Andrews, Robert|[[https://theunit...|    Robert|1957-08-04|01b100ac-192e-4b5...|[[phone, 202-225-...|      null|<br>|     Walden|       Greg Walden|[[Wikipedia (comm...|  male|https://theunited...|[[ballotpedia, Gr...|[[bar, multilingu...|    Walden, Greg|[[https://theunit...|      Greg|1957-01-10|01bc21bf-8939-487...|[[fax, 202-225-57...|      null|<br>|      Kazen|Abraham Kazen, Jr.|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, K0000...|[[, alternate, Ab...|  Kazen, Abraham|[[https://theunit...|   Abraham|1919-01-17|02059c1e-0bdf-481...|                null|1987-11-29|<br>|     Turner| Michael R. Turner|[[Wikipedia (comm...|  male|https://theunited...|[[ballotpedia, Mi...|[[, alternate, Mi...| Turner, Michael|[[https://theunit...|   Michael|1960-01-11|020aa7dd-54ef-435...|[[fax, 202-225-67...|      null|<br>|      Kolbe|         Jim Kolbe|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, K0003...|[[ca, multilingua...|    Kolbe, James|[[https://theunit...|     James|1942-06-28|02141651-eca2-4aa...|                null|      null|<br>|  Lowenthal| Alan S. Lowenthal|[[Wikipedia (de),...|  male|https://theunited...|[[ballotpedia, Al...|[[, alternate, Al...| Lowenthal, Alan|[[https://theunit...|      Alan|1941-03-08|0231c6ef-6e92-49b...|[[fax, 202-225-79...|      null|<br>|    Capuano|Michael E. Capuano|[[Wikipedia (de),...|  male|https://theunited...|[[ballotpedia, Mi...|[[, alternate, Mi...|Capuano, Michael|[[https://theunit...|   Michael|1952-01-09|0239032f-be5c-4af...|[[fax, 202-225-93...|      null|<br>|   Schrader|     Kurt Schrader|[[Wikipedia (de),...|  male|https://theunited...|[[ballotpedia, Ku...|[[bar, multilingu...|  Schrader, Kurt|[[https://theunit...|      Kurt|1951-10-19|0263f619-eff8-4e1...|[[fax, 202-225-56...|      null|<br>|     Nadler|    Jerrold Nadler|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, N0000...|[[ca, multilingua...| Nadler, Jerrold|[[https://theunit...|   Jerrold|1947-06-13|029e793d-ec40-4a1...|[[fax, 202-225-69...|      null|<br>|     Graves|        Tom Graves|[[Wikipedia (de),...|  male|https://theunited...|[[ballotpedia, To...|[[bar, multilingu...|     Graves, Tom|[[https://theunit...|       Tom|1970-02-03|02b621fc-0523-449...|[[fax, 202-225-82...|      null|<br>|   McMillan|     John McMillan|[[Wikipedia (de),...|  male|https://theunited...|[[bioguide, M0005...|[[, alternate, Al...|  McMillan, John|[[https://theunit...|      John|1932-05-09|03018f7c-f866-419...|                null|      null|<br>+-----------+------------------+--------------------+------+--------------------+--------------------+--------------------+----------------+--------------------+----------+----------+--------------------+--------------------+----------+<br>only showing top 20 rows</pre><h3>purge_table, purge_s3_path, transition_table, transition_s3_path</h3><p>Please test the above <a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-extensions-glue-context.html">transformations</a> only on your personal test S3 bucket as we do not want to make any changes to the S3 buckets/catalog used in the notebook above.</p><p>purge_table transform deletes files from Amazon S3 for the specified catalog’s database and table. If all files in a partition are deleted, that partition is also deleted from the catalog.</p><p>purge_s3_path transform deletes files from the specified Amazon S3 path recursively.</p><pre>glueContext.purge_table(&quot;database&quot;, &quot;table&quot;, {&quot;partitionPredicate&quot;: &quot;(month==&#39;march&#39;)&quot;, &quot;retentionPeriod&quot;: 1, &quot;excludeStorageClasses&quot;: [&quot;STANDARD_IA&quot;], &quot;manifestFilePath&quot;: &quot;s3://bucketmanifest/&quot;})</pre><pre>glueContext.purge_s3_path(&quot;s3://bucket/path/&quot;, {&quot;retentionPeriod&quot;: 1, &quot;excludeStorageClasses&quot;: [&quot;STANDARD_IA&quot;], &quot;manifestFilePath&quot;: &quot;s3://bucketmanifest/&quot;})</pre><p>transition_table transform transitions the storage class of the files stored on Amazon S3 for the specified catalog’s database and table.</p><pre>glueContext.transition_table(&quot;database&quot;, &quot;table&quot;, &quot;STANDARD_IA&quot;, {&quot;retentionPeriod&quot;: 1, &quot;excludeStorageClasses&quot;: [&quot;STANDARD_IA&quot;], &quot;manifestFilePath&quot;: &quot;s3://bucketmanifest/&quot;, &quot;accountId&quot;: &quot;12345678901&quot;, &quot;roleArn&quot;: &quot;arn:aws:iam::123456789012:user/example-username&quot;})</pre><p>transition_s3_path transform transitions the storage class of the files in the specified Amazon S3 path recursively.</p><pre>glueContext.transition_s3_path(&quot;s3://bucket/prefix/&quot;, &quot;STANDARD_IA&quot;, {&quot;retentionPeriod&quot;: 1, &quot;excludeStorageClasses&quot;: [&quot;STANDARD_IA&quot;], &quot;manifestFilePath&quot;: &quot;s3://bucketmanifest/&quot;, &quot;accountId&quot;: &quot;12345678901&quot;, &quot;roleArn&quot;: &quot;arn:aws:iam::123456789012:user/example-username&quot;})</pre><p>Thank you for reading throughout, hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e14d13145f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insert billions of rows in MySQL database for benchmarking]]></title>
            <link>https://swapnil-bhoite.medium.com/insert-millions-of-rows-in-mysql-database-for-benchmarking-e85046ee4612?source=rss-772637dfc6b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85046ee4612</guid>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Swapnil Bhoite]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 15:37:34 GMT</pubDate>
            <atom:updated>2022-04-06T07:07:35.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aRTc9jDn_8QQFoWK9oSIGA.jpeg" /></figure><p>After thorough research on web I see its difficult to import millions of row in MySQL. The pain starts with finding the right data source and once this is identified the insert part of this data is cumbersome and may take longer. I understand you can use large CSV files and import them with MySQL command line this will again take longer and if the database compute size is not big enough, this will cause the database to be exhausted.</p><p>In my project, I required to have hundreds of millions of records in MySQL database. Here I wanted to compare and benchmark the difference in <strong>AWS Glue</strong> default read and parallel read from JDBC and likewise default and parallel reads using <strong>Apache spark</strong>. Though I was able to find datasets online, these are not big enough to convey the enhancement offered by parallel reads, especially by <strong>AWS Glue</strong>. This was certainly a blocker to me for exploring the parallel read enhancements provided by Glue and Spark in today&#39;s BigData world. Finally, I found a solution where I can use sub-query approach in INSERT statements in MySQL to load the data.</p><ul><li>Create a sample table <strong><em>customers</em></strong> using the below statement in MySQL</li></ul><pre>CREATE TABLE IF NOT EXISTS customers (<br> id INT AUTO_INCREMENT PRIMARY KEY,<br> customer_name TEXT,<br> created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>) ENGINE=INNODB;</pre><p>To insert <strong>1Million</strong> rows in the above table you can use the below insert statement</p><pre>INSERT INTO customers (id, customer_name)<br>SELECT n, CONCAT(&#39;Customer&#39;, n)<br> FROM<br>(<br>select a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + f.N * 100000 + 1 N<br>from (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) d<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) e<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) f<br>) t</pre><p>In case if you need to increase the number of records further, you can add sub-queries in the above statement. In my case I imported <strong>1 Billion</strong> records in the <strong><em>customers</em></strong> table with below command</p><pre>INSERT INTO customers (id, customer_name)<br>SELECT n, CONCAT(&#39;Customer&#39;, n)<br> FROM<br>(<br>select a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + f.N * 100000 + g.N * 1000000 + h.N * 10000000 + i.N * 100000000 + 1 N<br>from (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) d<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) e<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) f<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) g<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) h<br> , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) i<br>) t</pre><p>Notice the difference in the sub-queries for insert statements with 1M and 1B inserts, likewise you can alter the insert statements to control the number of records inserted.</p><p>The MySQL database is running on <strong>AWS RDS</strong> of size <strong>db.m5.xlarge</strong>. The insert statement was performed by connecting to MySQL using mysql command line from <strong>MacOS 8GB RAM</strong> machine. The insert time might differ depending on the hardware used to insert statement and the compute power of the database engine. In terms of size, the above <strong>1M records are 1.2GB</strong> whereas <strong>1B records counts to 13GB</strong> when written out to <strong>AWS S3 </strong>bucket.</p><p>References:</p><p>[1] MySQL create table: <a href="https://www.mysqltutorial.org/mysql-create-table/">https://www.mysqltutorial.org/mysql-create-table/</a></p><p>[2] Insert statement: <a href="https://stackoverflow.com/a/24837185">https://stackoverflow.com/a/24837185</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85046ee4612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Glue Triggers]]></title>
            <link>https://swapnil-bhoite.medium.com/aws-glue-triggers-2a2098f148c0?source=rss-772637dfc6b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a2098f148c0</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[glue]]></category>
            <dc:creator><![CDATA[Swapnil Bhoite]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 13:58:21 GMT</pubDate>
            <atom:updated>2021-08-16T11:05:05.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CRLbS-Ho0NEg3k6g9OuOHA.jpeg" /></figure><p><strong>Glue triggers are used to start one or more crawlers or extract, transform, and load (ETL) jobs. Using triggers, you can design a chain of dependent jobs and crawlers.</strong></p><p>Currently, the AWS Glue console supports only jobs, not crawlers, when working with triggers, you can use the AWS CLI or AWS Glue API to configure triggers for both jobs and crawlers [1]. Looking into the create trigger CLI documentation [2] for creating a trigger for crawler, this does not have any examples. The intention of this article is to provide an example for creating trigger for crawler using AWS CLI, as triggers for ETL job can be created from the console.</p><p>Below is the example CLI command to create trigger for crawler</p><pre>$ aws glue create-trigger --name testTrigger --type CONDITIONAL --predicate &#39;Logical=AND,Conditions=[{LogicalOperator=EQUALS,JobName=testJob,State=SUCCEEDED}]&#39; --actions CrawlerName=testCrawler --start-on-creation</pre><p>The above will create a trigger named ‘testTrigger’ which will start the crawler ‘testCrawler’ once the ‘testJob’ is succeeded. Note that the testJob needs to be started using a trigger only, if this is started manually then the testCrawler will not get fired by trigger. In Glue, dependent jobs or crawlers are only started if the job or crawler that completes was started by a trigger. All jobs or crawlers in a dependency chain must be descendants of scheduled or on-demand This behavior documented here [3].</p><p>The above trigger can also be created using python boto3 SDK.</p><pre>import boto3<br>client = boto3.client(&#39;glue&#39;)</pre><pre>response = client.create_trigger(<br>    Name=&#39;testTrigger&#39;,<br>    Type=&#39;CONDITIONAL&#39;,<br>    Predicate={<br>        &#39;Logical&#39;: &#39;AND&#39;,<br>        &#39;Conditions&#39;: [<br>            {<br>                &#39;LogicalOperator&#39;: &#39;EQUALS&#39;,<br>                &#39;JobName&#39;: &#39;testJob&#39;,<br>                &#39;State&#39;: &#39;SUCCEEDED&#39;<br>            },<br>        ]<br>    },<br>    Actions=[<br>        {<br>            &#39;CrawlerName&#39;: &#39;testCrawler&#39;<br>       },<br>    ],<br>    StartOnCreation=True,<br>    <br>)</pre><p>Either of the above approach should assist to create a trigger for Glue crawler.</p><p>References</p><p>—</p><p>[1] <a href="https://docs.aws.amazon.com/glue/latest/dg/console-triggers.html">https://docs.aws.amazon.com/glue/latest/dg/console-triggers.html</a></p><p>[2] <a href="https://docs.aws.amazon.com/cli/latest/reference/glue/create-trigger.html">https://docs.aws.amazon.com/cli/latest/reference/glue/create-trigger.html</a></p><p>[3] <a href="https://docs.aws.amazon.com/glue/latest/dg/about-triggers.html">https://docs.aws.amazon.com/glue/latest/dg/about-triggers.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a2098f148c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>