<?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 Soubhik Khankary on Medium]]></title>
        <description><![CDATA[Stories by Soubhik Khankary on Medium]]></description>
        <link>https://medium.com/@soubhikkhankary28?source=rss-efdb1ac902b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*tbHddFMDdQiTjrNA.</url>
            <title>Stories by Soubhik Khankary on Medium</title>
            <link>https://medium.com/@soubhikkhankary28?source=rss-efdb1ac902b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:52:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@soubhikkhankary28/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[Glue ,Delta Tables, S3 and Acid transactions]]></title>
            <link>https://medium.com/@soubhikkhankary28/glue-delta-tables-s3-and-acid-transactions-1e5cdb4439c5?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5cdb4439c5</guid>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 06:14:52 GMT</pubDate>
            <atom:updated>2024-11-13T18:44:23.276Z</atom:updated>
            <content:encoded><![CDATA[<h3>Glue ,Delta Tables, S3 and Acid transactions</h3><p><strong>Use Case</strong>: I have got an use case from the client where client wanted to perform ACID based transactions in S3 but they were confident enough to not use databricks and only use glue for their scenario. They also had a huge dataset which had to be validated and de-duplicated before it is loaded to redshift to make sure the redshift doesn’t consume enough space for their loads.</p><p><strong>Glue:</strong></p><p>AWS Glue is an event-driven, serverless computing platform provided by Amazon as a part of Amazon Web Services. It was introduced in August 2017. The primary purpose of Glue is to scan other services in the same Virtual Private Cloud, particularly S3</p><p><strong>S3:</strong></p><p>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. Customers of all sizes and industries can use Amazon S3 to store and protect any amount of data for a range of use cases, such as data lakes, websites, mobile applications, backup and restore, archive, enterprise applications, IoT devices, and big data analytics. Amazon S3 provides management features so that you can optimize, organize, and configure access to your data to meet your specific business, organizational, and compliance requirements</p><p><strong>Delta Tables:</strong></p><p>Delta Lake is the optimized storage layer that provides the foundation for tables in a lakehouse on Databricks. Delta Lake is <a href="https://delta.io/">open source software</a> that extends Parquet data files with a file-based transaction log for <a href="https://docs.databricks.com/en/lakehouse/acid.html">ACID transactions</a> and scalable metadata handling. Delta Lake is fully compatible with Apache Spark APIs, and was developed for tight integration with Structured Streaming, allowing you to easily use a single copy of data for both batch and streaming operations and providing incremental processing at scale</p><p><strong>ACID:</strong></p><p>ACID is an acronym that refers to the set of 4 key properties that define a transaction: Atomicity, Consistency, Isolation, and Durability. If a database operation has these ACID properties, it can be called an ACID transaction, and data storage systems that apply these operations are called transactional systems</p><p><strong>Sample Code</strong>from pyspark.sql import SparkSession<br>from delta.tables import DeltaTable<br># Initialize the Spark session<br>spark = SparkSession.builder \<br>.appName(&quot;Delta Lake Upsert Data Aggregations&quot;) \<br>.config(&quot;spark.sql.extensions&quot;, &quot;io.delta.sql.DeltaSparkSessionExtension&quot;) \<br>.config(&quot;spark.sql.catalog.spark_catalog&quot;, &quot;org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;) \<br>.getOrCreate()<br># Define S3 bucket paths<br># .config(&quot;spark.databricks.delta.retentionDurationCheck.enabled&quot;, &quot;false&quot;) \<br>s3_bucket_path = &quot;s3://dev-raw-data-{ur account number}-us-east-2&quot;<br>#s3://dev-raw-data-{account number}-us-east-2/sap/ocustsales/tablename_2024_09_12_10_10_02_617.parquet<br>input_path = f&quot;{s3_bucket_path}/sap/ocustsales/&quot;<br>output_path = f&quot;{s3_bucket_path}/delta_lake/orders&quot;<br>df = spark.read.format(&quot;parquet&quot;).load(input_path)<br>delta_table_exists = DeltaTable.isDeltaTable(spark, output_path)<br><br>if delta_table_exists:<br><br> ## Load the Delta table<br> delta_table = DeltaTable.forPath(spark, output_path)<br><br> ## Perform UPSERT (MERGE)<br><br> delta_table.alias(&quot;target&quot;).merge(<br> df.alias(&quot;source&quot;),<br> &quot;target.primary_key = source.primary_key&quot;<br> ).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()<br><br>else:<br><br> # If the Delta table does not exist, create one by writing out the current aggregation<br> df.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(output_path)<br> # Stop the Spark session<br> spark.stop()</p><p><strong>Conclusion:</strong></p><p>We were able to successfully perform ACID based transactions and fix the required changes given by the client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5cdb4439c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activate Scheduled Appflow using Lambda]]></title>
            <link>https://medium.com/@soubhikkhankary28/activate-scheduled-appflow-using-lambda-16b74bcd11f6?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b74bcd11f6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-certification]]></category>
            <category><![CDATA[aws-appflow]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 08:52:24 GMT</pubDate>
            <atom:updated>2024-04-23T08:52:24.901Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>AWS AppFlow is a fully managed integration service provided by Amazon Web Services (AWS). It enables you to securely transfer data between different software-as-a-service (SaaS) applications and AWS services</p><p><strong>General key use cases are:</strong></p><p>Data Integration</p><p>Data Synchronization</p><p>Data Transformation</p><p>Automation</p><p>Monitoring and Logging</p><p><strong>Problem Statement:</strong></p><p>Generally the scheduled appflows will have future date and time and you don’t want the appflows to be activated as soon as it is deployed in aws environment. If you have 700–800 appflow, data engineers also don’t want to manually activate each one of them.</p><p>Please find the code below :</p><pre>import logging<br><br>import boto3<br><br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br>### To start all the appflows<br>#{<br>#  &quot;type&quot;: &quot;start_all&quot;<br>#}<br>### To stop all the appflows<br>#{<br>#  &quot;type&quot;: &quot;stop_all&quot;<br>#}<br><br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;<br>    For all flows, activate flow if never activated.<br><br>    event: {<br>        &#39;type&#39;: &#39;start_all&#39; | &#39;stop_all&#39;,<br>    }<br>    &quot;&quot;&quot;<br>    validate_event(event)<br><br>    appflow = boto3.client(<br>        &#39;appflow&#39;<br>    )<br><br>    # Get all flows<br>    flows = []<br>    flows_response = appflow.list_flows(<br>        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appflow/client/list_flows.html<br>    )<br>    flows.extend(flows_response[&#39;flows&#39;])<br>    while &#39;nextToken&#39; in flows_response:<br>        flows_response = appflow.list_flows(<br>            nextToken=flows_response[&#39;nextToken&#39;]<br>        )<br>        flows.extend(flows_response[&#39;flows&#39;])<br><br>    # Filter valid flow names<br>    flows = [<br>        flow<br>        for flow in flows<br>        if (flow[&#39;flowName&#39;].split(&#39;-&#39;)[-1] in {&#39;full&#39;, &#39;incr&#39;})<br>    ]<br>    print(flows)<br>    print(&quot;The number of appflows is start&quot;)<br>    print(len(flows))<br>    print(&quot;The number of appflows is end&quot;)<br>    ##Activate flow if no execution record<br>    for flow in flows:<br>        flow_name = flow[&#39;flowName&#39;]<br>        flow_status= flow[&#39;flowStatus&#39;]<br>        if event[&#39;type&#39;] == &#39;start_all&#39; and (flow_status==&#39;Draft&#39; or flow_status==&#39;Suspended&#39;):<br>            execution_records_response = appflow.describe_flow_execution_records(<br>                # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appflow/client/describe_flow_execution_records.html<br>                flowName=flow_name,<br>            )<br>            executions: list = execution_records_response[&#39;flowExecutions&#39;]<br>            if not executions:<br>                appflow.start_flow(<br>                    # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appflow/client/start_flow.html<br>                    flowName=flow_name,<br>                )<br>                logger.info(f&#39;Started {flow_name=}&#39;)<br>        elif event[&#39;type&#39;] == &#39;stop_all&#39; and flow_status==&#39;Active&#39;:<br>            try:<br>                appflow.stop_flow(<br>                    # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/appflow/client/stop_flow.html<br>                    flowName=flow_name,<br>                )<br>                logger.info(f&#39;Stopped {flow_name=}&#39;)<br>            except Exception as e:<br>                if &#39;Flow is already deactivated&#39; in repr(e):<br>                    pass<br><br><br>def validate_event(event):<br>    assert &#39;type&#39; in event<br>    assert event[&#39;type&#39;] in {&#39;start_all&#39;, &#39;stop_all&#39;}<br><br><br>def test():<br>    &quot;&quot;&quot;Drafts for testing while developing&quot;&quot;&quot;<br>    appflow = boto3.client(&#39;appflow&#39;)<br><br>    flows = [{&#39;flowName&#39;: &quot;appflow_name_test&quot;}]<br>    try:<br>        resp = appflow.stop_flow(flowName=flow_name)<br>    except Exception as e:<br>        if &#39;Flow is already deactivated&#39; in repr(e):<br>            pass<br>    print(&#39;resp&#39;)<br>    print(resp)</pre><p>Description:</p><p>a) event_type: start_all</p><p>This configuration will help you to start/activate all the scheduled appflows.</p><p>b) event_type: stop_all</p><p>This configuration will help you to deactivate all the scheduled appflows.</p><p><strong>Note:</strong></p><p>If you want to activate the appflow as soon as it is deployed via CFT template . Then there is a configuration below using which it automatically gets activated.</p><pre>Type: AWS::AppFlow::Flow<br>Properties:<br>  Description: String<br>  DestinationFlowConfigList: <br>    - DestinationFlowConfig<br>  FlowName: String<br>  FlowStatus: String<br>  KMSArn: String<br>  MetadataCatalogConfig: <br>    MetadataCatalogConfig<br>  SourceFlowConfig: <br>    SourceFlowConfig<br>  Tags: <br>    - Tag<br>  Tasks: <br>    - Task<br>  TriggerConfig: <br>    TriggerConfig</pre><p>FlowStatus: Active configuration would deploy the appflow and activate it as soon as it is deployed to AWS environment. This is applicable only for scheduled appflow.</p><p>Please feel free to drop me questions if you have any . Thanks for your valuable time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b74bcd11f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redshift Node Selection & Data Modelling]]></title>
            <link>https://medium.com/@soubhikkhankary28/redshift-node-selection-data-modelling-1f8d4c1a8d3e?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f8d4c1a8d3e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 10:49:55 GMT</pubDate>
            <atom:updated>2024-03-22T10:51:17.377Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Problem Statement:</strong></p><p>Client wanted us to chose the right instance and number of nodes to help them start the project with a very little cost impact as budget was very tight constraint . They also wanted a solutioning of how data should be segregated in their redshift cluster as data was ingested from 4 different source systems at the same time. Here, in this blog I will be talking about the database structure in redshift, data modelling we chose and how queries were prioritized based on user’s id.</p><p><strong>Redshift:</strong></p><p>Amazon Redshift is a fully managed, petabyte-scale data warehouse service in the cloud. It supports the common SQL querying which is preferred by most of the developers.</p><p><strong>Features:</strong></p><ol><li>Amazon Redshift uses SQL to analyze structured and semi-structured data across data warehouses, operational databases, and data lakes, using AWS-designed hardware and machine learning to deliver the best price performance at any scale.</li><li>Break through data silos and gain real time and predictive insights on all your data in a few clicks, with no data movement or data transformation.</li><li>Gain up to 3x better price performance than any other cloud data warehouse, with performance innovation out of the box at no additional cost to you.</li><li>Get data to insights in seconds without worrying about infrastructure management, with a secure and reliable analytics service.</li></ol><p><strong>How to select data instance node type and Number of Nodes:</strong></p><p>Go to the redshift cluster page and click on help me Choose option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*HYgg62SUem9J6qxWLn6pyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*4gVFdsL4W2DKJMX3ZSkREA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*RPQt9m6Eaj-9F6XTAUAPgQ.png" /></figure><p>As per the information shared above AWS suggests us to start with dc2.large and 3 nodes.</p><p><strong>Note:</strong></p><p>Please make sure you reserve the right instance if you are sure about the data inflow but in our case we were not very sure as the client’s data was increasing exponentially day by day. Also based on our data model we had a requirement for cross database joins which is currently supported by.</p><ul><li><strong>Amazon Redshift supports cross-database query on the ra3.4xlarge, ra3.16xlarge, and ra3.xlplus node types.</strong></li><li><strong>Amazon Redshift supports joining data from tables or views across one or more databases in the same Amazon Redshift cluster.</strong></li></ul><p>In our case we started with ra3.4xlarge and 2 nodes to make the system highly available. We used to take automated snapshots for recovering the data in case if database goes down for some reason.</p><p><strong>Spin up Redshift Cluster:</strong></p><p>Please select the right instance type and number of nodes based on the requirement. After choosing and setting up the security groups along with VPC the redshift must be spun for usage.</p><p><strong>NOTE:</strong> I have spinned up redshift serverless as I have got 300 $ credits for the same. In project it could turn out to be a costly option if data processing is not immediately required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPwJYVSNRKtN2wE5MuYCnw.png" /></figure><p><strong>Redshift Data Structures &amp; Organization of databases:</strong></p><p>We need to understand about the different types of modelling techniques before we design the skeleton of the data model. There are different types of data model and finally we took a decision of using a model which did suit our requirements.</p><p>Good data model allows organizations to establish baselines, benchmarks, and goals to keep moving forward. In order for data to allow this measuring, it has to be organized through data description, data semantics, and consistency constraints of data. A Data Model is this abstract model that allows the further building of conceptual models and to set relationships between data items.</p><p>Data Modeling in <a href="https://www.simplilearn.com/how-to-become-a-software-engineer-article">software engineering</a> is the process of simplifying the diagram or data model of a software system by applying certain formal techniques. It involves expressing data and information through text and symbols. The data model provides the blueprint for building a new database or reengineering legacy applications.</p><h3>Data Modeling Examples</h3><h4>1. ER (Entity-Relationship) Model</h4><p>This model is based on the notion of real-world entities and relationships among them. It creates an entity set, relationship set, general attributes, and constraints.</p><p>Here, an entity is a real-world object; for instance, an employee is an entity in an employee database. An attribute is a property with value, and entity sets share attributes of identical value. Finally, there is the relationship between entities.</p><h4>2. Hierarchical Model</h4><p>This data model arranges the data in the form of a tree with one root, to which other data is connected. The hierarchy begins with the root and extends like a tree. This model effectively explains several real-time relationships with a single one-to-many relationship between two different kinds of data.</p><p>For example, one supermarket can have different departments and many aisles. Thus, the ‘root’ node supermarket will have two ‘child’ nodes of (1) Pantry, (2) Packaged Food.</p><h4>3. Network Model</h4><p>This <a href="https://www.simplilearn.com/what-is-database-management-article">database model</a> enables many-to-many relationships among the connected nodes. The data is arranged in a graph-like structure, and here ‘child’ nodes can have multiple ‘parent’ nodes. The parent nodes are known as owners, and the child nodes are called members.</p><h4>4. Relational Model</h4><p>This popular data model example arranges the data into tables. The tables have columns and rows, each cataloging an attribute present in the entity. It makes relationships between data points easy to identify.</p><p>For example, e-commerce websites can process purchases and track inventory using the relational model.</p><h4>5. Object-Oriented Database Model</h4><p>This data model defines a database as an object collection, or recyclable software components, with related methods and features.</p><p>For instance, architectural and engineering real-time systems used in 3D modeling use this<a href="https://www.simplilearn.com/data-modeling-interview-question-and-answers-article"> data modeling process.</a></p><h4>6. Object-Relational Model</h4><p>This model is a combination of an object-oriented database model and a relational database model. Therefore, it blends the advanced functionalities of the object-oriented model with the ease of the relational data model.</p><h4>7. Data Vault Model:</h4><p>A data vault is a data modeling design pattern used to build a data warehouse for enterprise-scale analytics. The data vault has three types of entities: hubs, links, and satellites. Hubs represent core business concepts, links represent relationships between hubs, and satellites store information about hubs and relationships between them.</p><p>(Please let me know if you need more details on the above concept)</p><p>We went with Data Vault modelling technique as we had to integrate and standardize multiple sources of data . We also had a requirement to maintain history tables and follow agile development method which makes it easier for developer to make changes.</p><p><strong>Datamodel Sample:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtJUkWFPNXnOLMtbYsFC5Q.jpeg" /></figure><p>Data model is generally a thought process which is iterative and keeps changing based on business requirements. Data model is selected based on the requirement we had and it suited all our plausible needs. I will not be able to share the exact replica of data model we used but it was a sample which replicates the business model that was implemented in our project. Please do comment me if you have any questions.</p><p><strong>Database Segregation/Structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ahFHm4gO4WkzZ2eVWJljeg.png" /></figure><p><strong>RAW: </strong>Pull the data from different sources and maintain different databases based on source systems . (Keep 1 to 1 mapping)</p><p><strong>REFINED: </strong>Creation of hubs links and satellites at this layer based on your data model.</p><p><strong>PUBLISH: </strong>Please create the view that has to be extracted or exposed to tableau based on business requirements.</p><p><strong>Prioritize Query Based On User:</strong></p><p>In Amazon Redshift workload management (WLM), query monitoring rules define metrics-based performance boundaries for WLM queues and specify what action to take when a query goes beyond those boundaries. For example, for a queue dedicated to short running queries, you might create a rule that cancels queries that run for more than 60 seconds. To track poorly designed queries, you might have another rule that logs queries that contain nested loops.</p><pre>&quot;rules&quot;: <br>[<br>    {<br>        &quot;rule_name&quot;: &quot;sample_rule&quot;,<br>        &quot;predicate&quot;: [<br>            {<br>                &quot;metric_name&quot;: &quot;query_execution_time&quot;,<br>                &quot;operator&quot;: &quot;&gt;&quot;,<br>                &quot;value&quot;: 50<br>            }<br>        ],<br>        &quot;action&quot;: &quot;abort&quot;<br>    }            <br>]</pre><p>Note: In our case we have given high priority for our queries getting submitted from the admin group as admin group gets the highest privileges.</p><p>Second priority was given to the developer group which had high privilege.</p><p>Third lowest priority was given to analyst group who just had the read access for testing data.</p><pre>[<br>    {<br>        &quot;user_group&quot;: [<br>            &quot;admin&quot;<br>        ],<br>        &quot;priority&quot;: &quot;highest&quot;,<br>        &quot;queue_type&quot;: &quot;wlm_priority_1&quot;<br>    },<br>    {<br>        &quot;user_group&quot;: [<br>            &quot;reporting&quot;<br>        ],<br>        &quot;priority&quot;: &quot;lowest&quot;,<br>        &quot;queue_type&quot;: &quot;auto&quot;<br>    },<br>    {<br>        &quot;user_group&quot;: [<br>            &quot;developer&quot;<br>        ],<br>        &quot;priority&quot;: &quot;high&quot;,<br>        &quot;queue_type&quot;: &quot;wlm_priority_1&quot;,<br>        &quot;auto_wlm&quot;: true<br>    }<br>]</pre><p><strong>Snapshots:</strong></p><p>Snapshots are point-in-time backups of a cluster. There are two types of snapshots: <em>automated</em> and <em>manual</em>. Amazon Redshift stores these snapshots internally in Amazon S3 by using an encrypted Secure Sockets Layer (SSL) connection.</p><p><strong>Automated:</strong></p><p>When automated snapshots are enabled for a cluster, Amazon Redshift periodically takes snapshots of that cluster after certain schedule.</p><p><strong>Manual:</strong></p><p>You can take a manual snapshot any time. By default, manual snapshots are retained indefinitely, even after you delete your cluster. You can specify the retention period when you create a manual snapshot, or you can change the retention period by modifying the snapshot.</p><p>Please feel free to drop me questions if you have any . Thanks for your valuable time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f8d4c1a8d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dicom File Predictor using Simple CNN & Python Flask]]></title>
            <link>https://medium.com/@soubhikkhankary28/dicom-file-predictor-using-simple-cnn-python-flask-1a22dd8bdc71?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a22dd8bdc71</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[dicom]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 04:17:21 GMT</pubDate>
            <atom:updated>2024-02-17T04:18:00.477Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Problem Statement:</strong> In this blog I will showcasing you all a small project where we would be training our model based on the input dicom images/files and then using it to predict the outcome of the dicom files getting generated at the clinic/hospital using a simple application. I will be showcasing a simple application using which we could predict the outcome of the dicom file.</p><p><strong>Note:</strong> In this blog we are just deciding whether lungs are in good condition or not.</p><p><strong>Input Data Files:</strong></p><p>Please download the dicom dataset from Kaggle which is available on internet easily. In case, you want to try out with the same dataset please do let me know I will share the same via S3 location making it public.</p><p><a href="https://www.kaggle.com/datasets?search=dicom">https://www.kaggle.com/datasets?search=dicom</a>(sample datasets)</p><p><strong>Preprocessing:</strong></p><p>Data cleaning, Data transformation, Data reduction, and Data integration are the major steps in data preprocessing.</p><p><strong>Data Cleaning</strong></p><p>Data cleaning, one of the major preprocessing steps in machine learning, locates and fixes errors or discrepancies in the data. From duplicates and outliers to missing numbers, it fixes them all. Methods like transformation, removal, and imputation help ML professionals perform data cleaning seamlessly.</p><p><strong>Data Integration</strong></p><p>Data integration is among the major responsibilities of data preprocessing in machine learning. This process integrates (merges) information extracted from multiple sources to outline and create a single dataset. The fact that you need to handle data in multiple forms, formats, and semantics makes data integration a challenging task for many ML developers.</p><p><strong>Data Transformation</strong></p><p>ML programmers must pay close attention to data transformation when it comes to data preprocessing steps. This process entails putting the data in a format that will allow for analysis. Normalization, standardization, and discretisation are common data transformation procedures. While standardization transforms data to have a zero mean and unit variance, normalization scales data to a common range. Continuous data is discretized into discrete categories using this technique.</p><p><strong>Data Reduction</strong></p><p>Data reduction is the process of lowering the dataset’s size while maintaining crucial information. Through the use of feature selection and feature extraction algorithms, data reduction can be accomplished. While feature extraction entails translating the data into a lower-dimensional space while keeping the crucial information, feature selection requires choosing a subset of pertinent characteristics from the dataset.</p><p><strong>Steps in Data Preprocessing in Machine Learning</strong><br> 1. Acquire the dataset<br> 2. Import all the crucial libraries<br> 3. Import the dataset<br> 4. Identifying and handling the EXCEPTIONS<br> 5. Encoding the dataset. In case of images we will convert into a Nparray</p><pre>import numpy as np<br>print(np.__version__)<br>import os<br>print(os.getcwd())<br>import pydicom<br>from pathlib import Path<br>import numpy as np<br>import cv2<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from tqdm.notebook import tqdm<br>lables=pd.read_csv(&#39;path where files stored&#39;)<br>lables.head(10)<br>lables.shape<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*AX83n8dHKGqF0DJ4YPhKWQ.png" /><figcaption>Check the shape of dataframe</figcaption></figure><pre>ROOT_PATH=&#39;&#39;<br>PROCESSED_PATH=&#39;&#39;<br>SAVE_PATH=&#39;processed/&#39;<br>### Just checking images###<br>fig,axis=plt.subplots(3,3,figsize=(15,15))<br>c=0<br>for i in range(3):<br>    for j in range(3):<br>        patient_id=lables.patientId.iloc[c]<br>        dcmpath=ROOT_PATH+&#39;\\&#39;+patient_id+&#39;.dcm&#39;<br>        print(dcmpath)<br>        dcm_array=pydicom.read_file(dcmpath).pixel_array<br>        print(dcm_array.shape)<br>        if len(dcm_array.shape) != 3 or dcm_array.shape[2] != 3:<br>            dcm_array = np.stack((dcm_array,) * 3, -1)<br>            print(&quot;after shape change&quot;)<br>            print(dcm_array.shape)<br>        label=lables.Target.iloc[c]<br>        axis[i][j].imshow(dcm_array,cmap=&#39;gray&#39;)<br>        axis[i][j].set_title(label)<br>        c=c+1</pre><p>Changing the shape of the array and standardizing it based on the number of pixels we have got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iavs4quGeJTJ2h4OPhRpYQ.png" /></figure><pre>##########Just checking metadata##############<br>fig,axis=plt.subplots(3,3,figsize=(15,15))<br>c=0<br>for i in range(3):<br>    for j in range(3):<br>        patient_id=lables.patientId.iloc[c]<br>        dcmpath=ROOT_PATH+&#39;\\&#39;+patient_id+&#39;.dcm&#39;<br>        print(dcmpath)<br>        dcm_array=pydicom.read_file(dcmpath)<br>        print(&quot;The metadata is&quot;)<br>        print(dcm_array)<br>        dcm_array=pydicom.read_file(dcmpath).pixel_array<br>        label=lables.Target.iloc[c]<br>        axis[i][j].imshow(dcm_array,cmap=&#39;gray&#39;)<br>        axis[i][j].set_title(label)<br>        c=c+1<br>        if c==3:<br>            break</pre><p>Checking the metadata and pasting the sample below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ag0lSl4DFVpUPH0At3A3og.png" /><figcaption>Metadata in the dicom file</figcaption></figure><p>Resize or reduce the size of dicom file 3d image to make it easier to compute or run machine learning models.I am reducing the size from 1024,1024,3 to 224,224,3.</p><pre>####Just adding this code to read the dicom Files##########<br>import os<br>data=[]<br>sums,sum_squared=0,0<br>for c,patientid in enumerate(tqdm(lables.patientId)):<br>    patient_id=lables.patientId.iloc[c]<br>    dcmpath=ROOT_PATH+&#39;\\&#39;+patient_id+&#39;.dcm&#39;<br>    dcm_array=pydicom.read_file(dcmpath).pixel_array/255<br>    if len(dcm_array.shape) != 3 or dcm_array.shape[2] != 3:<br>            dcm_array = np.stack((dcm_array,) * 3, -1)<br>    print(&quot;the shape is&quot;)<br>    print(dcm_array.shape)<br>    dcm_resize_array=cv2.resize(dcm_array,(224,224)).astype(np.float16)<br>    print(dcm_resize_array)<br>    label=lables.Target.iloc[c]<br>    train_or_val=&#39;train&#39;<br>    data.append([dcm_resize_array,label])<br>########################################################3<br>#     if c&lt;24000:<br>#         train_or_val=&#39;train&#39;<br>#     else:<br>#         train_or_val=&#39;test&#39;<br>#     label_str=str(label)<br>#     current_save_path=PROCESSED_PATH+&#39;\\&#39;+train_or_val+&#39;\\&#39;+label_str<br>#     isExist = os.path.exists(current_save_path)<br>#     if not isExist:<br>#         os.makedirs(current_save_path)<br>#     filepath=&#39;&#39;<br>#     filepath=current_save_path+&#39;\\&#39;+patient_id<br>#     print(dcm_resize_array)<br>#     data.append([dcm_resize_array,label])<br>#     np.save(filepath,dcm_resize_array)<br>#     print(&quot;iam done&quot;)<br>#     if c==5:<br>#        break</pre><pre>###Checked and verified if the file is in correct format<br>x1=np.load(&quot;path\\Desktop\\All_pyspar_codes\\dicomdata\\Processed\\train\\1\\00436515-870c-4b36-a041-de91049b9ab4.npy&quot;)<br>print(x1)<br>datasave = np.asarray([data])<br># save to npy file<br>np.save(&#39;datasave.npy&#39;, datasave)<br><br>#Save the array in some location</pre><p>Preprocessing:</p><ol><li>Conversion of dicom to jpg is done</li><li>Conversion of JPG to array is done</li><li>Compress the image pixels from 1024,1024,3 to 224,224,3 is done</li><li>Machine learning models could understand only numbers and it is important to convert images to nparray.</li></ol><p><strong>Training the dataset using CNN:</strong></p><h4>Convolutional neural network (CNN):</h4><p>A convolutional neural network (CNN) is a category of machine learning model, namely a type of deep learning algorithm well suited to analyzing visual data. CNNs — sometimes referred to as <em>convnets</em> — use principles from linear algebra, particularly convolution operations, to extract features and identify patterns within images. Although CNNs are predominantly used to process images, they can also be adapted to work with audio and other signal data.</p><p><strong>Back to work :</strong>Create a new python file in notebook and read the arrays and check shapes using below commands.</p><pre>import pickle<br>X_train=pickle.load(open(&#39;X_train.pk1&#39;,&#39;rb&#39;))<br>y_train=pickle.load(open(&#39;y_train.pk1&#39;,&#39;rb&#39;))<br>X_test=pickle.load(open(&#39;X_test.pk1&#39;,&#39;rb&#39;))<br>y_test=pickle.load(open(&#39;y_test.pk1&#39;,&#39;rb&#39;))<br>X_train.shape<br>y_train.shape<br>X_test.shape<br>y_test.shape<br>X_test.shape</pre><p>Install tensor flow as it will be useful for implementing CNN data model. Run the command below:</p><p>pip install tensorflow — user</p><pre>import tensorflow as tf<br>print(tf.__version__)<br>##2.12.0 make sure the version is matching </pre><p>Implementing Deep learning model</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D,Dense,Flatten,MaxPooling2D,Dropout<br>from tensorflow.keras.callbacks import TensorBoard<br>####Design sequential layers#########<br>model=Sequential()<br>#####################################<br>model.add(Conv2D(filters = 32, kernel_size = (3,3),padding = &#39;Same&#39;, activation =&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.2))<br>#####################################<br>model.add(Flatten())<br>#####################################<br>model.add(Dense(128,activation=&#39;relu&#39;,input_shape = (224, 224, 3)))<br>#####################################<br>model.add(Dense(2,activation=&#39;softmax&#39;))<br>#####################################</pre><p>Please let me know if you are not aware of any of the conepts above. I could write a separate blog in detail. This blog requires you to understand the basics of CNN concepts.</p><p>Try compiling the data model by mentioning optimizer as <strong>“adam” </strong>and metrics as <strong>accuracy.</strong></p><pre>model.compile(optimizer=&#39;adam&#39;,loss=&#39;sparse_categorical_crossentropy&#39;,metrics=[&#39;ac<br>curacy&#39;])l</pre><p>Fit and train the model in your training dataset.</p><pre>history =model.fit(X_train,y_train,epochs=4,validation_split=0.1,batch_size=32, verbose=0)</pre><p>Check whether you are happy with the accuracy you achieved. Please make sure that based on the business you will have to take a call whether to chose accuracy or recall metric. I have chosen accuracy to make the project look easier but metric might depend on case to case basis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*iDQEtCEG2AdhE8OIW_46Xw.png" /><figcaption>Important keys validated &amp; stored</figcaption></figure><pre>###<br>fcl_loss, fcl_accuracy = model.evaluate(X_test, y_test, verbose=1)<br>print(&#39;Test loss:&#39;, fcl_loss)<br>print(&#39;Test accuracy:&#39;, fcl_accuracy)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*yLCp9MKmB5cIufXfiaTxWQ.png" /><figcaption>Achieved an accuracy of 77 %. Sounds good for pilot project</figcaption></figure><p>Let’s summarize the history of accuracy betwee train and test dataset in every epoch that was iterated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*EW86wwAKKV6w-PZgoXHLTQ.png" /><figcaption>Summarize model accuracy</figcaption></figure><p>Though my model didn’t perform well with test dataset when compared with training dataset. It is called as overfitting problem but I will proceed further as I want to make the pilot project look easy for all the viewers going through my post. I could fix and share the code if you need the best model but please make sure you keep trying at your end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*mE0BCqi10cT7GU1ll_n01w.png" /><figcaption>Summarize model loss</figcaption></figure><p>Let me show you the confusion matrix which make my viewers to easily implement math and understand what we have achieved.</p><pre>from sklearn.metrics import confusion_matrix<br>import itertools<br>plt.subplots(figsize=(22,7)) #set the size of the plot <br><br>def plot_confusion_matrix(cm, classes,<br>                          normalize=False,<br>                          title=&#39;Confusion matrix&#39;,<br>                          cmap=plt.cm.Blues):<br>    plt.imshow(cm, interpolation=&#39;nearest&#39;, cmap=cmap)<br>    plt.title(title)<br>    plt.colorbar()<br>    tick_marks = np.arange(len(classes))<br>    plt.xticks(tick_marks, classes, rotation=45)<br>    plt.yticks(tick_marks, classes)<br><br>    if normalize:<br>        cm = cm.astype(&#39;float&#39;) / cm.sum(axis=1)[:, np.newaxis]<br><br>    thresh = cm.max() / 2.<br>    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):<br>        plt.text(j, i, cm[i, j],<br>                 horizontalalignment=&quot;center&quot;,<br>                 color=&quot;white&quot; if cm[i, j] &gt; thresh else &quot;black&quot;)<br><br>    plt.tight_layout()<br>    plt.ylabel(&#39;True label&#39;)<br>    plt.xlabel(&#39;Predicted label&#39;)<br><br><br># plot the confusion matrix<br>plot_confusion_matrix(confusion_mtx, classes = range(2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*lB0yiLVBmlDjvMsaDIYaag.png" /><figcaption>Confusion Matrix viewable</figcaption></figure><p>Sample code below on how to predict the outcome for dicom files we receive .</p><ol><li>Convert the dicom to Jpeg</li><li>Jpeg must be converted to array to make it readable by your learning model</li><li>Preprocess the image to convert the 1024,1024,3 to 224,224,3</li></ol><pre>from sklearn.metrics import confusion_matrix<br>import itertools<br>import numpy as np<br># Predict the values from the validation dataset<br>Y_pred = model.predict(X_test)<br># Convert predictions classes to one hot vectors <br>print(Y_pred)</pre><p><strong>Generation of Pickle file:</strong></p><p>Pickle allows for flexibility when De-serializing objects. You can easily save different variables into a Pickle file and load them back in a different Python session, recovering your data exactly the way it was without having to edit your code. You could save the model summary in the .pkl format and use it in your front end application. Please find the code below:</p><pre>import pickle <br>pickle.dump(model,open(&#39;pickled_model.pk1&#39;,&#39;wb&#39;))</pre><p><strong>Designing of Simple front end application:</strong></p><p>The purpose of the application is that it could be easily hosted in doctor’s clinic and to use it to predict for the incoming patient’s dicom file . We could iteratively keep training the dataset and improve the model accuracy based on our needs.</p><p>I have designed the simple app to make you all understand the impact of ML and how easy the life would become.</p><p>Let me share you the code and html pages to make it easier for you all to follow the code.</p><p>I have designed the application using flask.</p><p><strong>App.py file:</strong></p><pre>from flask import Flask, render_template, request, redirect, url_for<br>from werkzeug.utils import secure_filename<br>import os<br>import pydicom<br>import shutil<br>import json<br>import pydicom<br>import numpy as np<br>import cv2<br>import keras<br>import tensorflow as tf<br>app = Flask(__name__)<br>upload_folder=os.path.join(&#39;static&#39;, &#39;uploads&#39;)<br>img = os.path.join(&#39;static&#39;, &#39;uploads&#39;)<br>app.config[&#39;UPLOAD&#39;] = upload_folder<br>outdir=os.path.join(&#39;static&#39;,&#39;converted&#39;)<br>import pprint<br>import pickle<br># @app.route(&#39;/&#39;)<br># def home():<br>#     #return &quot;Hello Soubhik&quot;<br>#     file=os.path.join(img, &#39;dog.png&#39;)<br>#     return render_template(&#39;image_render.html&#39;,image=file)<br><br>def pred(new_img):<br>    m1_data=[]<br>    dcm_array=new_img<br>    if len(dcm_array.shape) != 3 or dcm_array.shape[2] != 3:<br>        dcm_array = np.stack((dcm_array,) * 3, -1)<br>    # print(&quot;the shape is&quot;)<br>    # print(dcm_array.shape)<br>    dcm_resize_array = cv2.resize(dcm_array, (224, 224)).astype(np.float16)<br>    #dcm_resize_array = cv2.resize(dcm_array, (1080, 1080)).astype(np.float16)<br>    # print(dcm_resize_array.shape)<br>    m1_data.append(dcm_resize_array)<br>    m1_data = np.array(m1_data)<br>    print(m1_data.shape)<br>    pickled_model = pickle.load(open(&#39;Desktop\\All_pyspar_codes\\pickled_model.pk1&#39;, &#39;rb&#39;))<br>    predict_value = pickled_model.predict(m1_data)<br>    Y_pred_classes = np.argmax(predict_value, axis=1)<br>    Y_pred_string=&#39;&#39;<br>    if Y_pred_classes[0]==0:<br>        Y_pred_string=&#39;Lungs are in good condition&#39;<br>    else:<br>        Y_pred_string = &#39;Lungs are not in good condition(pneumonia)&#39;<br>    return Y_pred_string<br>def dicomreader(path1):<br>    file1=pydicom.read_file(path1)<br>    print(&quot;The metadata is&quot;)<br>    img = file1.pixel_array<br>    #new_img=file1.pixel_array/1<br>    new_img=file1.pixel_array/255<br>    prediction=pred(new_img)<br>    #prediction=&#39;Lungs are in good condition&#39;<br>    print(&quot;img is &quot;)<br>    print(img)<br>    file_name1=path1.split(&#39;\\&#39;)[-1]<br>    print(&quot;only dcm filename is&quot;)<br>    print(file_name1)<br>    file_name2=file_name1.replace(&#39;.dcm&#39;, &#39;.png&#39;)<br>    print(&quot;the updated jpeg filename is &quot;)<br>    print(file_name2)<br>    cv2.imwrite(outdir + file_name1.replace(&#39;.dcm&#39;, &#39;.png&#39;), img)<br>    final_out_dir=outdir+file_name2<br>    print(file1)<br>    print(&quot;what is the type&quot;)<br>    print(type(file1))<br>    #print(file1.PatientName)<br>    print(file1[&#39;PatientName&#39;])<br>    print(&quot;listing all tags&quot;)<br>    print(file1.dir(&quot;pat&quot;))<br>    #print(file1.group_dataset())<br>    print(&quot;converting into a dictionary for pat related info&quot;)<br>    ##calling func######<br>    final_dict={}<br>    #final_dict=json.dumps(list_to_dict(file1),indent=2)<br>    final_dict=list_to_dict(file1)<br>    print(&quot;final dict is &quot;)<br>    print(final_dict)<br>    # niceText = pprint.pformat(final_dict)<br>    # print(&quot;nice text is &quot;)<br>    # print(niceText)<br>    # htmlLines = []<br>    # for textLine in pprint.pformat(final_dict).splitlines():<br>    #     htmlLines.append(&#39;&lt;br/&gt;%s&#39; % textLine)  # or something even nicer<br>    # htmlText = &#39;\n&#39;.join(htmlLines)<br>    # final_dict=htmlText<br>    #final_dict=json.dumps(list_to_dict(file1),indent=2).replace(&#39; &#39;, &#39;&amp;nbsp&#39;).replace(&#39;,\n&#39;, &#39;,&lt;br&gt;&#39;).replace(&#39;\n&#39;, &#39;&lt;br&gt;&#39;)<br>    ###end calling<br>    print(final_dict)<br>    return final_out_dir,final_dict,prediction<br>def list_to_dict(filecontent):<br>    l1=filecontent.dir(&#39;pat&#39;)<br>    dict1={}<br>    pat_det_string=&quot;&quot;<br>    for i in l1:<br>        print(filecontent[i])<br>        print(type(filecontent[i]))<br>        str2=str(filecontent[i])<br>        dict1[i]=str2.split(&quot;:&quot;)[-1].replace(&quot;&#39;&quot;,&quot;&quot;)<br>        #dict1[i] = filecontent.i<br>    str4buff = &quot;&quot;<br>    for key,val in dict1.items():<br><br>        str4buff=str4buff+key+&quot;:&quot;+val+&quot;\n&quot;<br>    print(str4buff)<br>    #return str4buff<br>    return dict1<br>@app.route(&#39;/upload&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def upload_file():<br><br>    if request.method == &#39;POST&#39;:<br>        print(request)<br>        file = request.files[&#39;img&#39;]<br>        filename = secure_filename(file.filename)<br>        file.save(os.path.join(app.config[&#39;UPLOAD&#39;], filename))<br>        img = os.path.join(app.config[&#39;UPLOAD&#39;], filename)<br>        print(img)<br>        final_out_dir,final_dict,prediction=dicomreader(img)<br>        s1=request.form.get(&#39;s3upload&#39;)<br>        print(&quot;s1 is&quot;)<br>        print(s1)<br>        if request.form.get(&quot;s3upload&quot;):<br>            print(&quot;I am copying &quot;)<br>            print(final_out_dir)<br>            shutil.copy(final_out_dir, outdir)<br>        else:<br>            print(&quot;I am not copying&quot;)<br><br>        return render_template(&#39;image_render.html&#39;, img=final_out_dir,pat_detail=final_dict,prediction=prediction)<br>    return render_template(&#39;image_render.html&#39;)<br>@app.route(&#39;/success/&lt;name&gt;&#39;)<br>def success(name):<br>    return &#39;welcome %s&#39; % name<br>@app.route(&#39;/login1&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def login_user():<br>    msg=&#39;&#39;<br>    user=&#39;&#39;<br>    if request.method==&#39;POST&#39;:<br>        if request.form[&#39;username&#39;]!=&#39;admin&#39; and request.form[&#39;password&#39;]!=&#39;admin&#39;:<br>            error=&quot;invalid credentials&quot;<br>            user=request.form[&#39;username&#39;]<br>        else:<br>            print(request.form)<br><br>            user=request.form[&#39;username&#39;]<br>            #return redirect(url_for(&#39;success&#39;,name=user))<br>            return redirect(&#39;/upload&#39;)<br>    return render_template(&#39;login.html&#39;,msg=msg)<br>@app.route(&#39;/&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def loginbaba():<br>    return &#39;&lt;h1&gt;welcome to the world of dicom viewer&lt;/h1&gt;&#39;<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True, port=9000)</pre><p>image_render.html file</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Rendering Local Images Using Flask&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;img src= &quot;{{image}}&quot; &gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>index.html file</p><pre>&lt;!-- Store this code in &#39;index.html&#39; file inside the &#39;templates&#39; folder--&gt;<br> <br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt; Index &lt;/title&gt;<br>        &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;style.css&#39;) }}&quot;&gt;                    <br>    &lt;/head&gt;<br>    &lt;body&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;<br>        &lt;div align=&quot;center&quot;&gt;<br>          &lt;div align=&quot;center&quot; class=&quot;border&quot;&gt;<br>             &lt;div class=&quot;header&quot;&gt;<br>                &lt;h1 class=&quot;word&quot;&gt;Index&lt;/h1&gt;<br>             &lt;/div&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;<br>                &lt;h1 class=&quot;bottom&quot;&gt;<br>                     Hi {{session.username}}!!&lt;/br&gt;&lt;/br&gt; Welcome to the index page...                <br>                &lt;/h1&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;<br>                &lt;a href=&quot;{{ url_for(&#39;logout&#39;) }}&quot; class=&quot;btn&quot;&gt;Logout&lt;/a&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Render Page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3u6JSolQVuImH6cC_VhTw.png" /><figcaption>Top Section for Render Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NPgKJYS_QecwTvT1EVVKg.png" /><figcaption>Bottom Section for Render Page</figcaption></figure><p>Thanks to you all for reviewing my blog and it took me a lot of hardwork to generate the blog. Please clap, comment and help me with the suggestions to improve my blog writing skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a22dd8bdc71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run & test your glue Job Locally?]]></title>
            <link>https://medium.com/@soubhikkhankary28/how-to-run-test-your-glue-job-locally-3a1609865c65?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a1609865c65</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 10:10:27 GMT</pubDate>
            <atom:updated>2024-01-25T10:10:27.747Z</atom:updated>
            <content:encoded><![CDATA[<p>I always had a problem in debugging my glue job code and testing out the glue job was a very expensive process. In this blog I will help you all to work around the issue. It will help you to debug the glue job without even deploying on AWS.</p><p><strong>Step_1:</strong> Configure AWS environment via powershell and run the below commands.</p><p>aws configure</p><p>or</p><p>aws configure sso</p><p>Provide access_keys and password in the .aws file or on the prompt to get that file created automatically.</p><p><strong>Step_2: Download docker for desktop in your windows machine from the below link.</strong></p><p><a href="https://www.docker.com/products/docker-desktop/">Docker Desktop: The #1 Containerization Tool for Developers | Docker</a></p><p><strong>Step_3: Pull the image that is required based on your project requirement. Like if your project needs 3.0 or 4.0 version to be compatible with the code.</strong></p><p>docker pull amazon/aws-glue-libs:glue_libs_4.0.0_image_01</p><p><strong>Step_4: Run the image using the below command. Change your path and profile name accordingly.</strong></p><p>docker run -it `<br> -v C:\Users\soubhikkhankary28\.aws:/home/glue_user/.aws `<br> -v ./jupyter_workspace/:/home/glue_user/workspace/jupyter_workspace/ `<br> -e AWS_PROFILE=dev `<br> -e DISABLE_SSL=true `<br> — rm -p 4040:4040 `<br> -p 18080:18080 `<br> -p 8998:8998 `<br> -p 8888:8888 `<br> — name glue_jupyter_lab amazon/aws-glue-libs:glue_libs_4.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh</p><p><strong>Step_5: Jupyter notebook will open automatically post this and you must be able to write the code to read the data from s3 location. I have checked by using the code snippets below.</strong></p><pre>import pyspark<br>from pyspark.sql import SparkSession <br>spark=SparkSession.builder.appName(&quot;test&quot;).getOrCreate()<br>spark.sql(&quot;show databases&quot;).show()</pre><p>We can also do the same set up using VS Code and it gives more flexibity. Please let me know if any additional help is required. Thanks for the time!!!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a1609865c65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async method to Check query status in Redshift Part-2]]></title>
            <link>https://medium.com/@soubhikkhankary28/async-method-to-check-query-status-in-redshift-part-2-63a740bd66cd?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a740bd66cd</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[aws-lambda-functions]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 07:15:18 GMT</pubDate>
            <atom:updated>2024-01-25T10:23:33.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*gcBxxCsCgvoxpRBY_Fj1ZA.png" /></figure><p>This post is in continuation of my previous blog. I have shared my link below:</p><p><a href="https://medium.com/@soubhikkhankary28/async-method-to-run-queries-in-redshift-part-1-d34a7c30ccba">Async method to run queries in Redshift Part-1</a></p><p>Please go through the above link for the initial steps and the problem statement we discussed.</p><p>Problem_Statement:</p><p>I will have to write second AWS lambda function which would perform the next steps after the query is submitted in redshift cluster.</p><ol><li>Check the status of the query if it is still running or aborted or in failed status.</li><li>Update the status of the query in the audit table if it is in aborted or failed status.</li><li>If the query is in running status please wait for the query to get completed.</li><li>Send sns notification for the queries which errored out.</li></ol><p>Code Snippet:</p><p>The below code has been used for performing the above functions.</p><pre>import os<br>import json<br>import boto3<br>import logging<br>import psycopg2<br>from datetime import datetime<br>from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT<br><br># Set Logging Level<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Fetch environment variables<br>ENV = os.environ[&#39;ENV&#39;]<br>REDSHIFT_SECRET_NAME = os.environ[&#39;REDSHIFT_SECRET_NAME&#39;]<br>ERROR_SNS_ARN = os.environ[&#39;ERROR_SNS_ARN&#39;]<br>SUCCESS_SNS_ARN = os.environ[&#39;SUCCESS_SNS_ARN&#39;]<br>LAMBDA_NAME = os.environ[&#39;LAMBDA_NAME&#39;]<br>REDSHIFT_AUDIT_TABLE = os.environ[&#39;REDSHIFT_AUDIT_TABLE&#39;]<br>REDSHIFT_CLUSTER_NAME = os.environ[&#39;REDSHIFT_CLUSTER_NAME&#39;]<br>DB_NAME = os.environ[&#39;DB_NAME&#39;]<br><br># Establish redshift connection<br>def create_redshift_connection(db=None):<br>    return redshift_conn(db)<br><br># Close redshift connection<br>def close_redshift_connection(psycopg_conn):<br>    psycopg_conn.close()<br><br># Fetch redshift data client<br>def get_redshift_data_client():<br>    return boto3.client(&#39;redshift-data&#39;)<br><br># Create and return sns client<br>def get_sns_client():<br>    return boto3.client(&#39;sns&#39;)<br><br># Create current timestamp<br>def create_current_timestamp():<br>    time_now = datetime.now()<br>    return time_now.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>def send_success_sns(subject, message):<br>    &quot;&quot;&quot; <br>    Function to send success sns email<br>    &quot;&quot;&quot;<br>    logger.info(&quot;send_success_sns starts...&quot;)<br>    sns_client = get_sns_client()<br>    sns_client.publish(<br>        TopicArn = SUCCESS_SNS_ARN,<br>        Subject = subject,<br>        Message = message<br>    )<br>    logger.info(&quot;send_success_sns ends...&quot;)<br><br>def send_error_sns(subject, message):<br>    &quot;&quot;&quot; <br>    Function to send error sns email<br>    &quot;&quot;&quot;<br>    logger.info(&quot;send_error_sns starts...&quot;)<br>    sns_client = get_sns_client()<br>    sns_client.publish(<br>        TopicArn = ERROR_SNS_ARN,<br>        Subject = subject,<br>        Message = message<br>    )<br>    logger.info(&quot;send_error_sns ends...&quot;)<br><br>def user_pwd_retrieve():<br>    &quot;&quot;&quot;<br>    Function to retrieve username and password from secrets manager<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Retrieving username and password from secrets manager&quot;)<br>    client = boto3.client(&#39;secretsmanager&#39;)<br>    response = client.get_secret_value(SecretId=REDSHIFT_SECRET_NAME)<br>    database_secrets = json.loads(response[&#39;SecretString&#39;])<br>    pwd = database_secrets[&#39;password&#39;]<br>    host = database_secrets[&#39;host&#39;]<br>    port = database_secrets[&#39;port&#39;]<br>    db_nm = database_secrets[&#39;dbname&#39;]<br>    usernames = database_secrets[&#39;username&#39;]<br>    logger.info(&quot;Username and password fetched successfully&quot;)<br>    return usernames,pwd,host,port,db_nm<br><br>def redshift_conn(db=None):<br>    &quot;&quot;&quot;<br>    Function to create a connection to redshift<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Creating connection to redshift&quot;)<br><br>    user1, pwd1, host, port, default_db=user_pwd_retrieve()<br><br>    if not db:<br>        ps_connection = psycopg2.connect(user=user1,<br>                                     password=pwd1,<br>                                     host=host,<br>                                     port=port,<br>                                     database=default_db)<br>    else:<br>        ps_connection = psycopg2.connect(user=user1,<br>                                     password=pwd1,<br>                                     host=host,<br>                                     port=port,<br>                                     database=db)<br>    ps_connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)<br><br>    logger.info(&quot;Connection to redshift successful&quot;)<br>    return ps_connection<br><br>def fetch_audit_record(psycopg_conn, db_nm, exec_id):<br>    &quot;&quot;&quot;<br>    Function to fetch the audit record using the exec_id<br>    &quot;&quot;&quot;<br>    logger.info(&quot;fetch_audit_record starts&quot;)<br><br>    query = f&quot;&quot;&quot;<br>    select * from {db_nm}.audit.{REDSHIFT_AUDIT_TABLE}<br>    where exec_id = &#39;{exec_id}&#39;<br>    &quot;&quot;&quot;<br><br>    cursor = psycopg_conn.cursor()<br>    logger.info(cursor)<br>    cursor.execute(query)<br><br>    result: tuple = cursor.fetchone()<br>    proc_nm, exec_id, redshift_pid, create_ts, update_ts, status, error_msg, buss_unit, src_system = result<br><br>    logger.info(&quot;fetch_audit_record ends&quot;)<br>    return (proc_nm, exec_id, status, error_msg, buss_unit, src_system)<br><br>def update_audit_table(psycopg_conn, db_nm, exec_id, redshift_pid, query_status, err_reason=None):<br>    &quot;&quot;&quot;<br>    Function to update redshift audit table per execution query id<br>    &quot;&quot;&quot;<br>    logger.info(&quot;update_audit_table starts&quot;)<br>    # Fetch current timestamp<br>    current_timestamp = create_current_timestamp()<br><br>    # Limiting error message length to 50K<br>    if err_reason is not None:<br>        err_reason = err_reason[:50000]<br>        err_reason = err_reason.replace(&quot;&#39;&quot;, &quot;\\&#39;&quot;)<br><br>    # Formulate the update query<br>    query = &quot;&quot;&quot;<br>    update {}.audit.{} <br>    set status = &#39;{}&#39;<br>    ,redshift_pid = {}<br>    ,error_msg = &#39;{}&#39;<br>    ,update_ts = &#39;{}&#39;<br>    where exec_id = &#39;{}&#39;;<br>    &quot;&quot;&quot;.format(db_nm, REDSHIFT_AUDIT_TABLE, query_status, redshift_pid, <br>    err_reason, current_timestamp, exec_id)<br><br>    logger.info(f&quot;Audit Query: {query}&quot;)<br><br>    # Execute and commit the query<br>    cursor = psycopg_conn.cursor()<br>    logger.info(cursor)<br>    cursor.execute(query)<br>    psycopg_conn.commit()<br><br>    logger.info(&quot;update_audit_table ends&quot;)<br>    return &quot;success&quot;<br><br>def clean_audit_table(psycopg_conn, db_nm, days=10):<br>    &quot;&quot;&quot;<br>    Function to cleanup redshift audit table<br>    &quot;&quot;&quot;<br>    logger.info(&quot;clean_audit_table starts&quot;)<br><br>    logger.info(f&quot;All redshift data older than {days} days will be deleted now.&quot;)<br><br>    # Formulate the cleanup query<br>    query = f&quot;&quot;&quot;<br>    delete from {db_nm}.audit.{REDSHIFT_AUDIT_TABLE}<br>    where create_ts &lt; current_date-{days};<br>    &quot;&quot;&quot;<br><br>    logger.info(f&quot;Audit Cleanup Query: {query}&quot;)<br><br>    # Execute and commit the query<br>    cursor = psycopg_conn.cursor()<br>    logger.info(cursor)<br>    cursor.execute(query)<br>    psycopg_conn.commit()<br><br>    logger.info(&quot;clean_audit_table ends&quot;)<br>    return &quot;success&quot;</pre><p>Below is the main lambda_handler function which would help us to orchestrate &amp; control the function in aws lambda .</p><pre>def lambda_handler(event, context):<br>    &quot;&quot;&quot;<br>    Lambda to check and audit the status of procedures currently under<br>    execution to load data from redshift raw to stage<br>    &quot;&quot;&quot;<br>    logger.info(&quot;lambda_handler starts&quot;)<br>    exec_list = []<br>    failure_list = []<br>    response = {}<br><br>    try:<br>        # Redshift data client<br>        redshift_client = get_redshift_data_client()<br><br>        # Establish a connection to redshift<br>        psycopg_conn = create_redshift_connection(DB_NAME)<br>        <br>        if &quot;exec_list&quot; not in event:<br>            logger.info(&quot;Nothing to process&quot;)<br>            return {}<br><br>        # Iterating over all the execution id(s) and checking status<br>        for eid in event[&quot;exec_list&quot;]:<br>            describe_response = redshift_client.describe_statement(<br>                Id = eid<br>            )<br><br>            # Logging the describe response<br>            logger.info(f&quot;Execution Id: {eid}\nDescribe Response: {describe_response}&quot;)<br><br>            # Fetching status    <br>            query_status = describe_response[&quot;Status&quot;]<br><br>            # Fetching redshift process id<br>            redshift_pid = describe_response[&quot;RedshiftPid&quot;]<br><br>            if query_status in (&#39;ABORTED&#39;, &#39;FAILED&#39;):<br>                logger.info(f&quot;Query with id {eid} failed\nStatus: {query_status}\nAdding to failure list&quot;)<br><br>                err_reason = describe_response[&quot;Error&quot;]<br>                if not err_reason:<br>                    err_reason = &quot;No information provided&quot;<br>                # Update audit table<br>                update_audit_table(psycopg_conn, DB_NAME, eid, redshift_pid, query_status, err_reason)<br>                failure_list.append(eid)<br><br>                # Fetch audit record status for sns logging<br>                proc_nm, exec_id, status, error_msg, buss_unit, src_system = fetch_audit_record(<br>                    psycopg_conn, DB_NAME, eid<br>                )<br>                db_nm, schema_nm, p_nm = proc_nm.split(&quot;.&quot;)<br>                ############# SENDING SNS #############<br>                subject = f&quot;Procedure from redshift stage to raw failed&quot;<br>                error_msg = (<br>                    f&quot;Database Name: {db_nm}\n&quot; \<br>                    f&quot;Schema Name: {schema_nm}\n&quot; \<br>                    f&quot;Procedure Name: {p_nm}\n&quot; \<br>                    f&quot;Execution ID: {exec_id}\n&quot; \<br>                    f&quot;Business Unit: {buss_unit}\n&quot; \<br>                    f&quot;Source System: {src_system}\n&quot; \<br>                    f&quot;Status: {status}\n&quot; \<br>                    f&quot;Error Message: {error_msg}\n&quot; \<br>                )<br>                send_error_sns(subject, error_msg)<br>                logger.info(&quot;Successfully sent error sns notification.&quot;)<br>                ############# SENDING SNS #############<br><br>            elif query_status in (&#39;SUBMITTED&#39;,&#39;PICKED&#39;,&#39;STARTED&#39;):<br>                logger.info(f&quot;Query with id {eid} has not yet finished\nStatus: {query_status}\nAdding to list for recheck&quot;)<br>                exec_list.append(eid)<br><br>            elif query_status == &#39;FINISHED&#39;:<br>                logger.info(f&quot;Query with id: {eid} has finished execution successfully&quot;)<br>                # Update audit table<br>                update_audit_table(psycopg_conn, DB_NAME, eid, redshift_pid, query_status, None)<br><br>                # Fetch audit record status for sns logging<br>                proc_nm, exec_id, status, error_msg, buss_unit, src_system = fetch_audit_record(<br>                    psycopg_conn, DB_NAME, eid<br>                )<br>                db_nm, schema_nm, p_nm = proc_nm.split(&quot;.&quot;)<br>                ############# SENDING SNS #############<br>                subject = f&quot;Procedure from redshift stage to raw completed successfully&quot;<br>                success_msg = (<br>                    f&quot;Database Name: {db_nm}\n&quot; \<br>                    f&quot;Schema Name: {schema_nm}\n&quot; \<br>                    f&quot;Procedure Name: {p_nm}\n&quot; \<br>                    f&quot;Execution ID: {exec_id}\n&quot; \<br>                    f&quot;Business Unit: {buss_unit}\n&quot; \<br>                    f&quot;Source System: {src_system}\n&quot; \<br>                    f&quot;Status: {status}\n&quot; \<br>                    f&quot;Message: Procedure has completed successfully&quot;<br>                )<br>                send_success_sns(subject, success_msg)<br>                logger.info(&quot;Successfully sent success sns notification.&quot;)<br>                ############# SENDING SNS #############<br><br>        # Cleanup redshift audit table<br>        logger.info(&quot;Redshift audit table cleanup will be done.&quot;)<br>        redshift_cleanup_response = clean_audit_table(psycopg_conn, DB_NAME) # Default 10 days<br>        if &quot;success&quot; in redshift_cleanup_response:<br>            logger.info(&quot;Redshift audit table cleanup completed successfully.&quot;)<br><br>        # Close redshift connection<br>        close_redshift_connection(psycopg_conn)<br><br>        # Checking if earlier failures were there<br>        if &#39;failure_list&#39; in event:        <br>            # Adding the old failure list<br>            failure_list = event[&#39;failure_list&#39;]<br>        <br>        if failure_list:<br>            response[&#39;failure_list&#39;] = failure_list<br>            <br>        if exec_list:<br>            response[&#39;exec_list&#39;] = exec_list<br>    <br>    except Exception as ee:<br>        logger.error(&quot;Error occured in redshift lambda await&quot;)<br>        logger.error(f&quot;Reason: {ee}&quot;)<br>        ############# SENDING SNS #############<br>        current_timestamp = create_current_timestamp()<br>        subject = f&quot;Lambda: {LAMBDA_NAME} failed&quot;<br>        error_msg = (<br>            f&quot;Message: Lambda: {LAMBDA_NAME} failed\n&quot; \<br>            f&quot;Status: FAILED\n&quot; \<br>            f&quot;Error Reason: {ee}\n&quot; \<br>            f&quot;Timestamp: {current_timestamp}\n&quot; \<br>        )<br>        send_error_sns(subject, error_msg)<br>        logger.info(&quot;Successfully sent error sns notification.&quot;)<br>        ############# SENDING SNS #############<br>        raise ee<br><br>    logger.info(&quot;lambda_handler ends&quot;)<br>    return response</pre><p>This code should be able to help you out in executing the queries in redshift cluster in asynchronous manner. I have orchestrated the lambda functions using step functions and await functionality. Please let me know if you have any questions from your side. Thanks !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a740bd66cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async method to run queries in Redshift Part-1]]></title>
            <link>https://medium.com/@soubhikkhankary28/async-method-to-run-queries-in-redshift-part-1-d34a7c30ccba?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34a7c30ccba</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[lambda-function]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 06:14:26 GMT</pubDate>
            <atom:updated>2024-01-25T10:23:04.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*gcBxxCsCgvoxpRBY_Fj1ZA.png" /></figure><p>Problem_Statement:</p><p>I had a requirement where I wanted to use compute service(Lambda/glue) to trigger the redshift query or procedure but I wanted to save the compute costs by switching it off post the procedure run is done.</p><p><strong>WHY?</strong></p><ol><li>Lambda could be executed for only 15 minutes at maximum. In case of glue If I try running redshift procedure it is going to cost me a bit more and wouldn’t be a plausible solution.</li><li>Possibility/Probability of running the procedure on redshift and time it might take more than 15 minutes is high and lambda wouldn’t be a good solution as per the scenario.</li></ol><p><strong>Async method makes running , execution &amp; monitoring the redshift procedure via AWS lambda. Best part is we won’t require additional packages to be installed as well.</strong></p><p>Step_1 Import the required packages to create a synchronous connection with redshift cluster. I have created multiple functions to create different modules and proper segregation</p><pre># Fetch environment variables<br>ENV = os.environ[&#39;ENV&#39;]<br>REDSHIFT_SECRET_NAME = os.environ[&#39;REDSHIFT_SECRET_NAME&#39;]<br>ERROR_SNS_ARN = os.environ[&#39;ERROR_SNS_ARN&#39;]<br>SUCCESS_SNS_ARN = os.environ[&#39;SUCCESS_SNS_ARN&#39;]<br>LAMBDA_NAME = os.environ[&#39;LAMBDA_NAME&#39;]<br>CODE_BUCKET_NAME = os.environ[&#39;CODE_BUCKET_NAME&#39;]<br>S3_PROC_LIST_FILE_KEY = os.environ[&#39;S3_PROC_LIST_FILE_KEY&#39;]<br>REDSHIFT_AUDIT_TABLE = os.environ[&#39;REDSHIFT_AUDIT_TABLE&#39;]<br>REDSHIFT_CLUSTER_NAME = os.environ[&#39;REDSHIFT_CLUSTER_NAME&#39;]<br>DB_NAME = os.environ[&#39;DB_NAME&#39;]<br><br># Create and return s3 client<br>def get_s3_client():<br>    return boto3.client(&#39;s3&#39;)<br><br># Create and return sns client<br>def get_sns_client():<br>    return boto3.client(&#39;sns&#39;)<br><br># Fetch redshift data client<br>def get_redshift_data_client():<br>    return boto3.client(&#39;redshift-data&#39;)<br><br># Establish redshift connection<br>def create_redshift_connection(db=None):<br>    return redshift_conn(db)<br><br># Close redshift connection<br>def close_redshift_connection(psycopg_conn):<br>    psycopg_conn.close()<br><br># Create current timestamp<br>def create_current_timestamp():<br>    time_now = datetime.now()<br>    return time_now.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>def send_error_sns(subject, message):<br>    &quot;&quot;&quot; <br>    Function to send error sns email<br>    &quot;&quot;&quot;<br>    logger.info(&quot;send_error_sns starts...&quot;)<br><br>    sns_client = get_sns_client()<br>    sns_client.publish(<br>        TopicArn = ERROR_SNS_ARN,<br>        Subject = subject,<br>        Message = message<br>    )<br><br>    logger.info(&quot;send_error_sns ends...&quot;)<br><br>def user_pwd_retrieve():<br>    &quot;&quot;&quot;<br>    Function to retrieve username and password from secrets manager<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Retrieving username and password from secrets manager&quot;)<br>    client = boto3.client(&#39;secretsmanager&#39;)<br>    response = client.get_secret_value(SecretId=REDSHIFT_SECRET_NAME)<br>    database_secrets = json.loads(response[&#39;SecretString&#39;])<br>    pwd = database_secrets[&#39;password&#39;]<br>    host = database_secrets[&#39;host&#39;]<br>    port = database_secrets[&#39;port&#39;]<br>    db_nm = database_secrets[&#39;dbname&#39;]<br>    usernames = database_secrets[&#39;username&#39;]<br>    logger.info(&quot;Username and password fetched successfully&quot;)<br>    return usernames,pwd,host,port,db_nm<br><br>def redshift_conn(db=None):<br>    &quot;&quot;&quot;<br>    Function to create a connection to redshift<br>    &quot;&quot;&quot;<br>    logger.info(&quot;Creating connection to redshift&quot;)<br><br>    user1, pwd1, host, port, default_db=user_pwd_retrieve()<br><br>    if not db:<br>        ps_connection = psycopg2.connect(user=user1,<br>                                     password=pwd1,<br>                                     host=host,<br>                                     port=port,<br>                                     database=default_db)<br>    else:<br>        ps_connection = psycopg2.connect(user=user1,<br>                                     password=pwd1,<br>                                     host=host,<br>                                     port=port,<br>                                     database=db)<br>    ps_connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)<br><br>    logger.info(&quot;Connection to redshift successful&quot;)<br>    return ps_connection<br><br><br>def read_and_fetch_s3_json_object(s3_client):<br>    &quot;&quot;&quot;<br>    Function to read the proc list file in s3 and return the json object for further processing<br>    &quot;&quot;&quot;<br>    logger.info(&quot;read_and_fetch_s3_json_object starts&quot;)<br><br>    s3_response = s3_client.get_object(Bucket = CODE_BUCKET_NAME, Key = S3_PROC_LIST_FILE_KEY)<br>    s3_file_content = s3_response[&quot;Body&quot;]<br>    s3_json_object = json.loads(s3_file_content.read())<br><br>    logger.info(&quot;read_and_fetch_s3_json_object ends&quot;)<br>    return s3_json_object<br><br>def execute_procedure(redshift_client, db_nm, schema_nm, proc_nm):<br>    &quot;&quot;&quot;<br>    Function to execute the query asynchronously<br>    &quot;&quot;&quot;<br>    logger.info(&quot;execute_procedure starts&quot;)<br>    # Construct redshift call query<br>    query = f&quot;call {db_nm}.{schema_nm}.{proc_nm}&quot;<br><br>    # Execute the query<br>    response = redshift_client.execute_statement(<br>        ClusterIdentifier=REDSHIFT_CLUSTER_NAME,<br>        Database=db_nm,<br>        Sql=query,<br>        SecretArn=REDSHIFT_SECRET_NAME<br>    )<br><br>    logger.info(&quot;execute_procedure ends&quot;)<br>    return response<br><br><br>def create_audit_entry(psycopg_conn, db_nm, schema_nm, proc_nm, exec_id):<br>    &quot;&quot;&quot;<br>    Function to create an entry in redshift audit table<br>    &quot;&quot;&quot;<br>    logger.info(&quot;create_audit_entry starts&quot;)<br><br>    # Fetch current timestamp<br>    current_timestamp = create_current_timestamp()<br><br>    # Source system<br>    if &quot;_&quot; in schema_nm:<br>        src_system = schema_nm.split(&quot;_&quot;)[0]<br>    else:<br>        src_system = schema_nm<br><br>    # Formulate the insert query<br>    query = f&quot;&quot;&quot;<br>    insert into {db_nm}.audit.{REDSHIFT_AUDIT_TABLE} <br>    select &#39;{db_nm}.{schema_nm}.{proc_nm}&#39; as proc_nm <br>    ,&#39;{exec_id}&#39; as exec_id <br>    ,NULL as redshift_pid<br>    ,&#39;{current_timestamp}&#39; as create_ts <br>    ,&#39;{current_timestamp}&#39; as update_ts <br>    ,&#39;SUBMITTED&#39; as status <br>    ,&#39;&#39; as error_msg <br>    ,&#39;project&#39; as buss_unit <br>    ,&#39;{src_system}&#39; as src_system&quot;&quot;&quot;<br>    <br>    logger.info(f&quot;Audit Query: {query}&quot;)<br><br>    # Execute and commit the query<br>    cursor = psycopg_conn.cursor()<br>    logger.info(cursor)<br>    cursor.execute(query)<br>    psycopg_conn.commit()<br><br>    logger.info(&quot;create_audit_entry ends&quot;)<br>    return &quot;success&quot;<br><br></pre><p>You could see the power of boto3 which could be used for creating a client with redshift-data and could be used to connect with redshift cluster. The sample code helps to establish a connection with redshift cluster and submit the query . Once the query is submitted the lambda makes a synchronous entry into the redshift cluster in the audit table.</p><pre>def lambda_handler(event, context):<br>    &quot;&quot;&quot;<br>    Lambda to execute stored procedures to load data from<br>    redshift raw to redshift stage in async fashion<br>    &quot;&quot;&quot;<br>    logger.info(&quot;lambda_handler starts&quot;)<br>    try:<br>        # S3 Client<br>        s3_client = get_s3_client()<br><br>        # Redshift data client<br>        redshift_client = get_redshift_data_client()<br><br>        # Execution Id List<br>        exec_list = []<br><br>        # Establish a connection to redshift<br>        psycopg_conn = create_redshift_connection(DB_NAME)<br><br>        # Reading the file which has the list of procedures and creating a json object<br>        s3_json_object = read_and_fetch_s3_json_object(s3_client)<br>        logger.info(f&quot;S3 json object fetched successfully: {s3_json_object}&quot;)<br><br>        # Iterating over all the input procs<br>        for item in s3_json_object[&quot;payload&quot;]:<br>            logger.info(f&quot;Processing: {item}&quot;)<br>            # Splitting input by database, schema and procedure name<br>            db_nm, schema_nm, proc_nm = item.split(&quot;.&quot;)<br>            logger.info(f&quot;DB Name: {db_nm}, Schema Name: {schema_nm}, Proc Name: {proc_nm}&quot;)<br><br>            # Execute the procedure in redshift<br>            execute_response = execute_procedure(redshift_client, db_nm, schema_nm, proc_nm)<br>            logger.info(execute_response)<br><br>            # Append it to execution id list<br>            exec_list.append(execute_response[&quot;Id&quot;])<br><br>            # Add to redshift audit table<br>            audit_response = create_audit_entry(psycopg_conn, db_nm, schema_nm, proc_nm,execute_response[&quot;Id&quot;])<br><br>            if &quot;success&quot; in audit_response:<br>                logger.info(f&quot;Successfully inserted audit entry into redshift for execution id: {execute_response[&#39;Id&#39;]}&quot;)<br><br>        # Close redshift connection<br>        close_redshift_connection(psycopg_conn)<br>    <br>    except Exception as ee:<br>        logger.error(&quot;Error occured in redshift lambda async&quot;)<br>        logger.error(f&quot;Reason: {ee}&quot;)<br>        ############# SENDING SNS #############<br>        current_timestamp = create_current_timestamp()<br>        subject = f&quot;Lambda: {LAMBDA_NAME} failed&quot;<br>        error_msg = (<br>            f&quot;Message: Lambda: {LAMBDA_NAME} failed\n&quot; \<br>            f&quot;Status: FAILED\n&quot; \<br>            f&quot;Error Reason: {ee}\n&quot; \<br>            f&quot;Timestamp: {current_timestamp}\n&quot; \<br>        )<br>        send_error_sns(subject, error_msg)<br>        logger.info(&quot;Successfully sent error sns notification.&quot;)<br>        ############# SENDING SNS #############<br>        raise ee<br><br>    logger.info(&quot;lambda_handler ends&quot;)<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;message&#39;: &#39;Successfully executed!&#39;,<br>        &#39;exec_list&#39;: exec_list<br>    }</pre><p>This code helped us resolve the problem statement and we were able to use the compute power at its best. We also saved a lot of costs as our compute service was not switched on and we were able to get good outcomes of it.</p><p>Thanks for your time for going through the post. Please do let me know if you have any questions. Thanks !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34a7c30ccba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS-Appflow-Sharepoint]]></title>
            <link>https://medium.com/@soubhikkhankary28/aws-appflow-sharepoint-73e55c2e8ad4?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e55c2e8ad4</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-appflow]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dáta]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 04:27:55 GMT</pubDate>
            <atom:updated>2024-01-25T04:27:55.972Z</atom:updated>
            <content:encoded><![CDATA[<p>Appflow integration with enterprise SharePoint application</p><p><strong>About Appflow:</strong></p><p>Appflow helps you to automate the flow to/from SAAS application into AWS services with a very low code implementation. We could implement full load or incremental load based on the requirement and also we could do simple transformation, partitions and aggregations based on the requirements.</p><p>Please follow the post for appflow-salesforce integration details:</p><p><a href="https://medium.com/@soubhikkhankary28/appflow-salesforce-d0222a79aca5">Appflow-Salesforce</a></p><p><strong>Problem Statement:</strong></p><p>We had a requirement to pull in the changed/modified files from sharepoint online. Only the modified objects must be detected and pulled into the S3 location at scheduled intervals daily.</p><p>Important requirements from the clients were:</p><ol><li>Low Code/No Code</li><li>Low Maintenance</li><li>Easy development and push the jobs to higher environments</li><li>Secured way of establishing the connection with source</li></ol><p><strong>Solution:</strong></p><p>Appflow is the AWS service which fulfilled all our requirements. I will also provide the CFT template which will fulfill the above requirements. I will also walk through the basic steps below :</p><p><strong>Step_1: Create Connection with SharePoint online securely</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyRngQTFzuKl5GrKO3zIcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNkaYouMTHxQayqLo6qHMg.png" /></figure><p>Once we click on Connect button we will be redirected to key in username, password and rsa token. Once all the details are keyed in successfully the connection gets created successfully. Username and password gets stored in Secrets manager and only the users with proper permissions to fetch the credentials when required.</p><p><strong>Step_2: Deploy AppFlow jobs scheduled to pull in the history+CDC(Changed Data Capture) data</strong></p><p>Once the connection is successfully established it is time to create appflow jobs to pull in the modified documents from the sharepoint locations.</p><p>Create the appflow job using the CFT template below and after running it for the first time verify the S3 location for metadata file and document dumps.</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Parameters:<br>  EnvPrefix:<br>    Description: &quot;Environment Prefix Variable &quot;<br>    Type: String<br>  ScheduleStartTime:<br>    Description: &quot;Time at which the appflow would become active&quot;<br>    Type: String<br>  BucketName:<br>    Description: &quot;Bucket name to land the file&quot;<br>    Type: String<br>  ScheduleExpression:<br>    Description: &quot;Rate at which the incremental workflow has to take place&quot;<br>    Type: String<br>  connectionnames:<br>    Description: &quot;Rate at which the incremental workflow has to take place&quot;<br>    Type: String<br>  entityname:<br>    Description: &quot;entity name&quot;<br>    Type: String<br>Resources:<br>  spFlow:<br>    Type: AWS::AppFlow::Flow<br>    Properties:<br>      FlowName: <br>        !Join<br>          - &#39;-&#39;<br>          - - !Ref EnvPrefix<br>            - &quot;projectname-appflow-sharepoint-incr&quot;<br>      Description: App Flow to import data from sharepoint to S3<br>      TriggerConfig:<br>        TriggerType: Scheduled<br>        TriggerProperties:<br>          DataPullMode: Incremental<br>          ScheduleExpression: !Ref ScheduleExpression<br>          ScheduleStartTime: !Ref ScheduleStartTime<br>          TimeZone: US/Eastern<br><br>      SourceFlowConfig:<br>        ApiVersion: v1.0<br>        IncrementalPullConfig:<br>          DatetimeTypeFieldName: lastModifiedDateTime<br>        ConnectorType: CustomConnector<br>        ConnectorProfileName: !Ref connectionnames<br>        SourceConnectorProperties:<br>          CustomConnector:<br>            EntityName: !Ref entityname<br>            CustomProperties:<br>              &quot;subEntities&quot;: &quot;[\&quot;put your own drives\&quot;]&quot;<br>      DestinationFlowConfigList:<br>        - ConnectorType: S3<br>          DestinationConnectorProperties:<br>            S3:<br>              BucketName:<br>                !Join<br>                    - &#39;-&#39;<br>                    - - !Ref EnvPrefix<br>                      - !Ref BucketName<br>              BucketPrefix: sharepoint/payload/incr<br>              S3OutputFormatConfig:<br>                 FileType: JSON<br>                 AggregationConfig:<br>                   AggregationType: SingleFile<br>                 PrefixConfig:<br>                   PrefixFormat: DAY<br>                   PrefixType: PATH<br><br>      Tasks:<br>        - TaskType: Map_all<br>          SourceFields: []<br>          TaskProperties: <br>          - Key: EXCLUDE_SOURCE_FIELDS_LIST<br>            Value: &#39;[]&#39;<br>          ConnectorOperator:<br>            CustomConnector: NO_OP</pre><p><strong>File Metadata Structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*INPaIhBMJnLsDkAD_JGHRg.png" /></figure><p>Limitation of Appflow with SharePoint Online:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*XAhN6k1gy1XL8KvWOUvp9g.png" /></figure><p>Please let me know if you find the blog useful. The CFT template shared above must be saving your time while doing development. Thanks Again !!!</p><p>References Used:</p><p><a href="https://docs.aws.amazon.com/appflow/latest/userguide/connectors-microsoft-sharepoint-online.html">https://docs.aws.amazon.com/appflow/latest/userguide/connectors-microsoft-sharepoint-online.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e55c2e8ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS-Appflow-SAP]]></title>
            <link>https://medium.com/@soubhikkhankary28/aws-appflow-sap-7b95e333568f?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b95e333568f</guid>
            <category><![CDATA[aws-appflow]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineer-skills]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 13:47:04 GMT</pubDate>
            <atom:updated>2024-01-24T13:47:04.701Z</atom:updated>
            <content:encoded><![CDATA[<p>Appflow integration with enterprise SharePoint application</p><p><strong>About Appflow:</strong></p><p>Appflow helps you to automate the flow to/from SAAS application into AWS services with a very low code implementation. We could implement full load or incremental load based on the requirement and also we could do simple transformation, partitions and aggregations based on the requirements.</p><p><strong>Problem Statement:</strong></p><p>We had a requirement to pull in the changed/modified data from SAP OData incrementally.</p><p>Important requirements from the clients were:</p><ol><li>Low Code/No Code</li><li>Low Maintenance</li><li>Easy development and push the jobs to higher environments</li><li>Secured way of establishing the connection with source</li></ol><p><strong>Solution:</strong></p><p>Appflow is the AWS service which fulfilled all our requirements. I will also provide the CFT template which will fulfill the above requirements. I will also walk through the basic steps below :</p><p><strong>Step_1: Create Connection with SharePoint online securely</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-usK20K7yInO-Rosok8jA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9J3K6Myz7kTSvdAxkBMWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*bfm5-eSVQcf-AW5EOHHWFw.png" /></figure><p>After the correct details are filled in please click on connect and you must be seeing the connection getting created successfully.</p><p>Step_2 <strong>Create Appflow job for full load+CDC loads in SAP</strong></p><p>I will be sharing the CFT template using which we could create appflow jobs and pull data from sap enterprise application.</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Parameters:<br>  EnvPrefix:<br>    Description: &quot;Environment Prefix Variable &quot;<br>    Type: String<br>  ScheduleStartTime:<br>    Description: &quot;Time at which the appflow would become active&quot;<br>    Type: String<br>  BucketName:<br>    Description: &quot;Bucket name to land the file&quot;<br>    Type: String<br>  ScheduleExpression:<br>    Description: &quot;Rate at which the incremtal workflow has to take place&quot;<br>    Type: String<br>  connectionnames:<br>    Description: &quot;Rate at which the incremtal workflow has to take place&quot;<br>    Type: String<br><br>Resources:<br>###########1###############<br>  testeventFlow:<br>    Type: AWS::AppFlow::Flow<br>    Properties:<br>      FlowName:<br>        !Join<br>          - &#39;-&#39;<br>          - - !Ref EnvPrefix<br>            - &#39;projectec-appflow-sap-subobject-incr&#39;<br>      Description: App Flow to import data from sap to s3 incrementally<br>      TriggerConfig:<br>        TriggerType: Scheduled<br>        TriggerProperties:<br>          DataPullMode: Incremental<br>          ScheduleExpression: !Ref ScheduleExpression<br>          ScheduleStartTime: !Ref ScheduleStartTime<br>          TimeZone: US/Eastern<br><br>      SourceFlowConfig:<br>        ConnectorType: SAPOData<br>        ConnectorProfileName: !Ref connectionnames<br>        SourceConnectorProperties:<br>          SAPOData:<br>            ObjectPath: /sap/path/subobject<br>      DestinationFlowConfigList:<br>        - ConnectorType: S3<br>          DestinationConnectorProperties:<br>            S3:<br>              BucketName:<br>                !Join<br>                    - &#39;-&#39;<br>                    - - !Ref EnvPrefix<br>                      - !Ref BucketName<br>              BucketPrefix: project/sap/subobject/payload/full<br>              S3OutputFormatConfig:<br>                 FileType: JSON<br>                 AggregationConfig:<br>                   AggregationType: SingleFile<br>                 PrefixConfig:<br>                   PrefixFormat: DAY<br>                   PrefixType: PATH<br><br>      Tasks:<br>        - TaskType: Map_all<br>          SourceFields: []<br>          TaskProperties: <br>          - Key: EXCLUDE_SOURCE_FIELDS_LIST<br>            Value: &#39;[]&#39;<br>          ConnectorOperator:<br>            SAPOData: NO_OP</pre><p>Please let me know if you find the post useful. Please let me know if you have any questions . Thanks !!!</p><p>Reference:</p><p><a href="https://docs.aws.amazon.com/appflow/latest/userguide/sapodata.html">https://docs.aws.amazon.com/appflow/latest/userguide/sapodata.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b95e333568f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS-Appflow-Salesforce]]></title>
            <link>https://medium.com/@soubhikkhankary28/appflow-salesforce-d0222a79aca5?source=rss-efdb1ac902b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0222a79aca5</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[aws-appflow]]></category>
            <dc:creator><![CDATA[Soubhik Khankary]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 11:53:07 GMT</pubDate>
            <atom:updated>2024-01-24T12:13:20.803Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Appflow Integration with enterprise application salesforce</strong></p><p><strong>About Appflow:</strong></p><p>Appflow helps you to automate the flow to/from SAAS application into AWS services with a very low code implementation. We could implement full load or incremental load based on the requirement and also we could do simple transformation, partitions and aggregations based on the requirements.</p><p><strong>Requirement:</strong></p><p>Currently I had a requirement to pull the data from salesforce and push to AWS S3 service securely. The data has to undergo multiple data quality checks and transformation rules before we load the data into redshift. Also the appflow jobs must be created via IAAS(Infrastructue as a Service code) using either CFT or terraform(Used CFT for the current discussion). Appflow load must be scheduled daily once and undergo incremental load only.(Schedules could be changed based on requirement)</p><p><strong>Implementation:</strong></p><p>Step_1:</p><p>It is very important to remember that when appflow is scheduled for incremental load it only pulls the last 90 days records and subsequently it goes for incremental loads.</p><p>To pull the data from salesforce object which has records older than 90 days we must create a appflow job in on demand mode which pulls in the complete historical data from source.</p><p><strong>Note</strong>: Depends on how old the data should be pulled in for analysis purpose.</p><p><strong>Simple Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzju_2u-0KqI_JTLrz2Ybw.png" /></figure><p>Step_2:</p><p>Create a connection with salesforce application and it is always good to create the connection manually. Generally the connection are created manually by salesforce administrators who will authenticate the the access by providing OTP or RSA token.</p><p>Go to appflow section in AWS and click on connection section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhuowfPQ1YUXWUy3DPtPqQ.png" /></figure><p>Choose salesforce in the connectors dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qml7Jvp-Oj01hGXS_7wECQ.png" /></figure><p>Click on Create connection. Post the click you will be prompted to enter the details like username and password for the salesforce environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XrZCRZXcldu3zmvUHyryQ.png" /></figure><p>Salesforce login page would pop up once we click on connect button. Administrator must be able to key in username/password along with RSA token.Once the connection is successfully established you could see them in connections tab. Username and password is stored in secrets manager automatically .(Will talk about this service in other blogs)</p><p>Step_3:</p><p>Creating appflow for multiple objects would be a tough job if done manually. So we will have to use IAAC code setup like CFT template to make the deployment smoother, faster and error free. I will be uploading the CFT template sample for your help.</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Parameters:<br>  EnvPrefix:<br>    Description: &quot;Environment Prefix Variable &quot;<br>    Type: String<br>  ScheduleStartTime:<br>    Description: &quot;Time at which the appflow would become active&quot;<br>    Type: String<br>  BucketName:<br>    Description: &quot;Bucket name to land the file&quot;<br>    Type: String<br>  ScheduleExpression:<br>    Description: &quot;Rate at which the incremtal workflow has to take place&quot;<br>    Type: String<br>  connectionnames:<br>    Description: &quot;Rate at which the incremtal workflow has to take place&quot;<br>    Type: String<br>Resources:<br>  AccountFlow:<br>    Type: AWS::AppFlow::Flow<br>    Properties:<br>      FlowName:<br>        !Join<br>          - &#39;-&#39;<br>          - - !Ref EnvPrefix<br>            - &#39;projectname-appflow-salesforce-objectname-full&#39;<br>      Description: App Flow to import data from salesforce to S3 for table object_name<br>      TriggerConfig:<br>        TriggerType: OnDemand<br><br>      SourceFlowConfig:<br>        ConnectorType: Salesforce<br>        ConnectorProfileName: !Ref connectionnames<br>        SourceConnectorProperties:<br>          Salesforce:<br>            Object: Object_name<br>            EnableDynamicFieldUpdate: false<br>            IncludeDeletedRecords: true<br>      DestinationFlowConfigList:<br>        - ConnectorType: S3<br>          DestinationConnectorProperties:<br>            S3:<br>              BucketName:<br>                !Join<br>                    - &#39;-&#39;<br>                    - - !Ref EnvPrefix<br>                      - !Ref BucketName<br>              BucketPrefix: projectname/salesforce/object_name/payload/full<br>              S3OutputFormatConfig:<br>                 FileType: JSON<br>                 AggregationConfig:<br>                   AggregationType: SingleFile<br>                 PrefixConfig:<br>                   PrefixFormat: DAY<br>                   PrefixType: PATH<br><br>      Tasks:<br>        - TaskType: Map_all<br>          SourceFields: []<br>          TaskProperties: <br>          - Key: EXCLUDE_SOURCE_FIELDS_LIST<br>            Value: &#39;[]&#39;<br>          ConnectorOperator:<br>            Salesforce: NO_OP<br><br><br></pre><p>Quick short description:</p><ol><li>Mention the CFT template version</li><li>Mention the variables that needs to be parameterized for different env like dev or qa</li><li>Mention the source connection that was created along with object name</li><li>Mention the destination s3 location where the data would be dumped. Data format could be in json, csv or parquet based on the requirement which could vary.</li><li>In the above shared CFT all the fields are getting mapped</li><li>If the full load schedule has to be incremental just change the below code block</li></ol><pre>TriggerType: Scheduled<br>        TriggerProperties:<br>          DataPullMode: Incremental<br>          ScheduleExpression: !Ref ScheduleExpression<br>          ScheduleStartTime: !Ref ScheduleStartTime<br>          TimeZone: US/Eastern</pre><p>Please upload the CFT template after making some changes based on the requirement and you could see the appflow job would be created very quickly with in few minutes.</p><p><strong>Conclusion:</strong></p><p>We were able to create and pull in mutliple objects from salesforce using appflow and level of code &amp; maintenance was quite low . Please let me know if you have anymore questions. Thanks !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0222a79aca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>