<?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 Naresh Erukulla on Medium]]></title>
        <description><![CDATA[Stories by Naresh Erukulla on Medium]]></description>
        <link>https://medium.com/@nerukulla0719?source=rss-2ac42812f8fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7O2lC6oqCZ01VBYM1Z8MDQ.jpeg</url>
            <title>Stories by Naresh Erukulla on Medium</title>
            <link>https://medium.com/@nerukulla0719?source=rss-2ac42812f8fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:58:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nerukulla0719/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[A Guide to Custom DataFlow Pipeline for Bigquery]]></title>
            <link>https://medium.com/@nerukulla0719/custom-dataflow-pipeline-to-read-events-from-pub-sub-and-write-to-multiple-destination-tables-in-48dbf221f14b?source=rss-2ac42812f8fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/48dbf221f14b</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Naresh Erukulla]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 18:21:33 GMT</pubDate>
            <atom:updated>2024-10-24T05:45:35.180Z</atom:updated>
            <content:encoded><![CDATA[<h4>Custom DataFlow Pipeline to Read Events from Pub/Sub and Write to Multiple Destination Tables in BigQuery using Key Identifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*f_eTF_eyPb_MzzfOfKxm6g.png" /><figcaption>Prepared from MicrosoftPresentation</figcaption></figure><h3>Introduction</h3><p>Have you ever challenged with a use case where you need to read events from one source and write to multiple Bigquery destinations? And route failed messages to dead letter?</p><h3>Let’s discuss in detail….</h3><p>Google Cloud’s <a href="https://cloud.google.com/dataflow/docs/overview">Dataflow</a> service provides a powerful, flexible, and fully managed solution for stream and batch processing. When dealing with real-time data ingestion, it’s common to use Pub/Sub as the source. In Real-world use cases, there is a necessity to write streaming data from an external source to different tables in Bigquery for easy maintenance. In that case, you might need to route data to different BigQuery tables based on a key identifier in the incoming JSON message. This blog post will guide you through creating a Dataflow custom template to achieve this and best practice methods to use.</p><h3>Services Intro:</h3><h4>Google Cloud Pub/Sub</h4><blockquote>Google Cloud Pub/Sub is a fully-managed messaging service that enables reliable, asynchronous communication between distributed applications. It decouples services that produce events from those that process events, allowing for scalable and flexible data flow.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEbup36FtbiOmXKWCBv12g.png" /><figcaption>Enable Cloud Pub/Sub API</figcaption></figure><ul><li><a href="https://cloud.google.com/pubsub/docs/overview">Google Cloud Pub/Sub Documentation</a></li><li><a href="https://cloud.google.com/pubsub">Google Cloud Pub/Sub Overview</a></li></ul><h4><strong>Google Cloud Dataflow</strong></h4><blockquote>Google Cloud Dataflow is a fully-managed service for stream and batch processing that allows you to develop and execute a wide range of data processing patterns. It supports Apache Beam pipelines, providing a unified programming model and reducing the operational overhead.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlqvfKggzsNJgFgE9W3nVw.png" /><figcaption>Enable DataFlow API</figcaption></figure><ul><li><a href="https://cloud.google.com/dataflow/docs/overview">Google Cloud Dataflow Documentation</a></li><li><a href="https://cloud.google.com/dataflow">Google Cloud Dataflow Overview</a></li></ul><h4>Apache Beam</h4><blockquote>Apache Beam is an open-source, unified model for defining both batch and streaming data-parallel processing pipelines. It provides a set of SDKs for writing data processing applications that can be executed across multiple execution engines, including Google Cloud Dataflow.</blockquote><ul><li><a href="https://beam.apache.org/documentation/">Apache Beam Documentation</a></li><li><a href="https://beam.apache.org/get-started/beam-overview/">Apache Beam Overview</a></li></ul><h4>Google Cloud BigQuery</h4><blockquote>Google Cloud BigQuery is a fully-managed, serverless data warehouse that enables super-fast SQL queries using the processing power of Google’s infrastructure. It is designed for analyzing large datasets quickly and efficiently, with built-in machine learning capabilities.</blockquote><ul><li><a href="https://cloud.google.com/bigquery/docs">Google Cloud BigQuery</a> Documentation</li><li><a href="https://cloud.google.com/bigquery">Google Cloud BigQuery</a> Overview</li></ul><h4>Google Cloud Storage</h4><blockquote>Google Cloud Storage is a scalable and secure object storage service offered by Google Cloud. It allows you to store and retrieve any amount of data at any time. GCS is designed to provide durability, availability, and security for your data. It supports a variety of use cases, such as serving website content, storing backups, and distributing large data objects to users.</blockquote><ul><li><a href="https://cloud.google.com/storage/docs">Google Cloud Storage</a> Documentation</li><li><a href="https://cloud.google.com/storage/docs/overview">Google Cloud Storage</a> Overview</li></ul><h3>Prerequisites</h3><p>Before we begin, ensure you have the following:<br>- A Google Cloud Project<br>- <a href="https://cloud.google.com/pubsub/docs/overview">Pub/Sub</a> topic and subscription<br>- BigQuery <a href="https://cloud.google.com/bigquery/docs/datasets-intro">datasets</a> and <a href="https://cloud.google.com/bigquery/docs/tables">tables</a><br>- Follow <a href="https://cloud.google.com/dataflow/docs/guides/installing-beam-sdk">Google Cloud SDK</a> steps to install Google Cloud SDK<br>- Install <a href="https://www.python.org/downloads/">Python</a> 3.7 or later</p><h3>DataFlow Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vxIjQOJVkbnFuZI9EjPkuA.png" /><figcaption>Streaming DataFlow Architecture</figcaption></figure><h3><strong>Step 1: Setting Up Pub/Sub</strong></h3><p>First, create a Pub/Sub topic and subscription. Run below commands in Bash(command line) or cloud console(Cloud CLI in google cloud).</p><pre>gcloud pubsub topics create Incoming_JSON<br>gcloud pubsub subscriptions create Incoming_JSON_Sub --topic=Incoming_JSON</pre><p>Output Screenshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLLfUCpbISI6g3dhcM45eQ.png" /><figcaption>PubSub Topic and Subscription</figcaption></figure><p><strong>Service Account Setup:</strong></p><p>You may need to setup Service Account for your needs-</p><p>Use below References:</p><p>- <a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts">Creating and Managing Service Accounts</a></p><p>- <a href="https://cloud.google.com/iam/docs/granting-roles-to-service-accounts">Granting Roles</a> to Service Accounts</p><p>- <a href="https://cloud.google.com/docs/authentication/production">Setting Up Authentication</a> for Server to Server Production Applications</p><h3><strong>Step 2: Setting Up BigQuery Tables</strong></h3><p>Create BigQuery dataset and tables where the data will be stored. For this example, we’ll assume you have three tables: “Sales”, “Orders” and “Returns”.</p><p>Dataset create command:</p><pre>bq mk local_dataset</pre><p>Sales table create command:</p><pre>bq mk --table local_dataset.sales \<br>category:STRING,sale_id:STRING,product_id:STRING,sale_date:TIMESTAMP,quantity:INTEGER,total_revenue:FLOAT,store_id:STRING,region:STRING</pre><p>Orders table create command:</p><pre>bq mk --table local_dataset.orders \<br>category:STRING,order_id:STRING,customer_id:STRING,product_id:STRING,order_date:TIMESTAMP,quantity:INTEGER,total_price:FLOAT,status:STRING</pre><p>Returns table create command:</p><pre>bq mk --table local_dataset.returns \<br>category:STRING,return_id:STRING,order_id:STRING,return_date:TIMESTAMP,quantity:INTEGER,refund_amount:FLOAT,reason:STRING,store_id:STRING</pre><p>Google cloud storage bucket create command:</p><pre>gsutil mb -p supple-hulling-431203-j4 -l us-central1 gs://ingestion-bucket-431/</pre><p>Screenshot of Dataset and Tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmsvcl0BuxJWlY8dcF5fIA.png" /><figcaption>Executing “bq” table create commands in CloudShell</figcaption></figure><h3>Step 3: Creating the Dataflow Pipeline</h3><p>Write the Dataflow pipeline using Apache Beam using Python. The pipeline will read messages from Pub/Sub, process them, and write to the appropriate BigQuery table based on the “<strong>category”</strong> field in the JSON message.</p><p><strong>3.1. Install Required Libraries</strong></p><p>Install the required Python libraries.</p><pre>pip3 install apache-beam[gcp]<br>pip3 install google-cloud-pubsub</pre><blockquote>pip install apache-beam[gcp]</blockquote><p>This command installs the apache-beam library along with the Google Cloud Platform (GCP) dependencies.</p><blockquote>pip install google-cloud-pubsub</blockquote><p>This command installs the google-cloud-pubsub library, which is used to interact with Google Cloud Pub/Sub.</p><p><strong>3.2. Write the Dataflow Pipeline</strong></p><p>Python code for the Dataflow pipeline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d64ab61d0ad97a2f4c15f2c1d1fade/href">https://medium.com/media/57d64ab61d0ad97a2f4c15f2c1d1fade/href</a></iframe><p><strong>Results</strong>:</p><p><strong>DataFlow screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Utx9CAH8laeUF4SlUyy_Q.png" /><figcaption>DataFlow Graph View from console after job starts running</figcaption></figure><p><strong>Sample Payloads sent to Pub/Sub:</strong></p><pre># Orders Payload<br>{<br>  &quot;order_id&quot;: &quot;12345&quot;,<br>  &quot;category&quot;: &quot;Orderinfo&quot;,<br>  &quot;customer_id&quot;: &quot;67890&quot;,<br>  &quot;product_id&quot;: &quot;54321&quot;,<br>  &quot;order_date&quot;: &quot;2023-07-01T12:34&quot;,<br>  &quot;quantity&quot;: 2,<br>  &quot;total_price&quot;: 49.99,<br>  &quot;status&quot;: &quot;confirmed&quot;<br>}<br><br># Sales Payload<br>{<br>  &quot;sale_id&quot;: &quot;98765&quot;,<br>  &quot;category&quot;: &quot;SaleInfo&quot;,<br>  &quot;product_id&quot;: &quot;54321&quot;,<br>  &quot;sale_date&quot;: &quot;2023-07-02T14:56&quot;,<br>  &quot;quantity&quot;: 1,<br>  &quot;total_revenue&quot;: 24.99,<br>  &quot;store_id&quot;: &quot;11223&quot;,<br>  &quot;region&quot;: &quot;North&quot;<br>}<br><br># Retuns Payload<br>{<br>  &quot;return_id&quot;: &quot;24680&quot;,<br>  &quot;category&quot;: &quot;RetrunInfo&quot;,<br>  &quot;order_id&quot;: &quot;12345&quot;,<br>  &quot;return_date&quot;: &quot;2023-07-03T16:18&quot;,<br>  &quot;quantity&quot;: 1,<br>  &quot;refund_amount&quot;: 24.99,<br>  &quot;reason&quot;: &quot;damaged&quot;,<br>  &quot;store_id&quot;: &quot;11223&quot;<br>}</pre><p><strong>Sales table screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMU8yKD5CT4r2HYeKSkvRA.png" /><figcaption>Sales table showing records inserted from DataFlow</figcaption></figure><p><strong>Orders table screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuGjVyvDK1sEb-nLy9Mxzw.png" /><figcaption>Orders table showing records inserted from DataFlow</figcaption></figure><p><strong>Returns table screenshot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFNCcmVKx7XreuaQpG3Z7g.png" /><figcaption>Returns table showing records inserted from DataFlow</figcaption></figure><p><strong>Dead letter table screenshot(For error records):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGtziNLuQY0QMBMmfe3R4g.png" /><figcaption>Dead Letter table showing error records inserted from DataFlow</figcaption></figure><p><strong>3.3. Code Explanation</strong></p><ul><li><strong>ParseMessageFn</strong>:</li></ul><blockquote>This `DoFn` processes each Pub/Sub message by decoding it from bytes to a string and then parsing the JSON content.</blockquote><ul><li><strong>CategorizeAndWriteToBigQuery</strong>:</li></ul><blockquote>This `DoFn` routes the data to the appropriate BigQuery table based on the “<strong>category”</strong> field values in the JSON message. For example: “SalesInfo”, “OrderInfo”, “ReturnsInfo” etc. This program yields the output with a tag and it will used in the pipeline process stage.</blockquote><ul><li><strong>ReadFromPubSub</strong>:</li></ul><blockquote>Reads messages from the specified Pub/Sub subscription. In this case: “projects/supple-hulling-431203-j4/subscriptions/Incoming_JSON_Sub”</blockquote><ul><li><strong>WriteToBQ</strong>:</li></ul><blockquote>This is the <strong><em>custom Bigquery</em></strong> Function , which process each message from “<strong>CategorizeAndWriteToBigQuery</strong>” step tagged output and based on the table passed in the pipeline.</blockquote><blockquote>Writes the processed data to the appropriate BigQuery table based on the Batch Size (Instead of processing each element at a time which puts pressure on Bigquery). Currently flush batch size is set to 50 in the program and can be changed to any value based on use case. Refer to “process” function definition.</blockquote><blockquote>If there is an error while loading the message to BigQuery Table(refer to _flush_batch section), it will push the “<strong>Error</strong>” information and original “<strong>Message</strong>” contents with the timestamp into the “<strong>Dead letter table</strong>” defined in the pipeline(<em>supple-hulling-431203-j4:local_dataset.dead_letter_table</em>).</blockquote><blockquote>Before program captures and writes the error messages, it will first retry inserting into the original table 3 times exponentially(retries can be adjusted based on the use case).</blockquote><ul><li><strong>Key Notes</strong>:</li></ul><blockquote>Refer Pipeline step “CategorizeAndWriteToBigQuery” and “for” loop for processing the data to multiple tables.</blockquote><pre> <br>    with beam.Pipeline(options=options) as p:<br>        messages = (p <br>                    | &#39;ReadFromPubSub&#39; &gt;&gt; ReadFromPubSub(subscription=&#39;projects/supple-hulling-431203-j4/subscriptions/Incoming_JSON_Sub&#39;)<br>                    | &#39;ParseMessages&#39; &gt;&gt; beam.ParDo(ParseMessageFn())<br>                    # tag each output based on Key Identifier<br>                    | &#39;CategorizeAndWriteToBigQuery&#39; &gt;&gt; beam.ParDo(CategorizeAndWriteToBigQuery()).with_outputs(&#39;SaleInfo&#39;, &#39;OrderInfo&#39;,&#39;ReturnInfo&#39;, main=&#39;main_output&#39;)<br>                    )<br>        #for loop to process each tagged output<br>        for tag, table_spec in [(&#39;SaleInfo&#39;, &#39;supple-hulling-431203-j4.local_dataset.sales&#39;), (&#39;OrderInfo&#39;, &#39;supple-hulling-431203-j4.local_dataset.orders&#39;),<br>                                (&#39;ReturnInfo&#39;, &#39;supple-hulling-431203-j4.local_dataset.returns&#39;)]:<br>                                global_window = &quot;Window-&quot; + tag<br>                                WriteToBq = &quot;WriteTo&quot; + tag<br>                                GlobalWindow_Failed = &quot;GlobalWindow&quot; + tag + &quot;-Failed&quot;<br>                                Write_To_dead_letter = &quot;Error-&quot; + tag<br>                                # write to bigquery table and tag any message that is failed to write as &quot;failed&quot;<br>                                messages_load = (<br>                                    messages[tag]<br>                                    | global_window &gt;&gt; beam.WindowInto(GlobalWindows())<br>                                    | WriteToBq &gt;&gt; beam.ParDo(WriteToBQ(table_spec)).with_outputs(&#39;failed&#39;)<br>                                    )<br>                                # write each failed message to dead letter table<br>                                messages_failed = (<br>                                        messages_load.failed<br>                                        | GlobalWindow_Failed &gt;&gt; beam.WindowInto(GlobalWindows())<br>                                        | Write_To_dead_letter &gt;&gt; beam.io.WriteToBigQuery(<br>                                            table=dead_letter_table_spec,<br>                                            schema=dead_letter_schema,<br>                                            create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,<br>                                            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,<br>                                            method=&quot;STREAMING_INSERTS&quot;<br>                                        )<br>                                    )</pre><h3><strong>Step 4: Running the Dataflow Pipeline</strong></h3><p>You can run the pipeline on your local machine for testing or submit it to the Dataflow service for production use.</p><p><strong>Local Execution</strong></p><p>To run the pipeline locally:</p><pre>python dataflow_ingest_pipeline.py</pre><p><strong>Submitting to Dataflow</strong></p><p>To submit the pipeline to Dataflow: You can also pass service account using “- -<em>service-account-email</em>” parameter while executing the pipeline. I currently used my credentials for this execution so you don’t see this parameter mentioned in below.</p><pre>python dataflow_ingest_pipeline.py \<br>--runner=DataflowRunner \<br>--project=supple-hulling-431203-j4 \<br>--region=us-east4 \<br>--temp_location=gs://ingestion-bucket-431/temp \<br>--staging_location=gs://ingestion-bucket-431/staging</pre><p>Replace “project name”, “bucket”, and other placeholders with your actual project ID and Cloud Storage bucket names.</p><h3><strong>Monitoring and Error Handling</strong></h3><p>Once the pipeline is running, you can monitor it through the Google Cloud Console under the Dataflow section. Ensure you have proper error handling in your pipeline to manage any issues that arise during execution. You can add logging and monitoring tools to track the health of your pipeline.</p><h3><strong>Conclusion</strong></h3><p>In this guide, we’ve created a custom Dataflow pipeline with custom BigQuery function to read data from Pub/Sub and write to multiple BigQuery tables based on a key identifier in the incoming JSON message. This setup is essential for real-time data processing in many applications, especially in complex systems like retail or finance.</p><p>By following the steps outlined, you should now be able to build and deploy your own Dataflow pipelines, ensuring your data is processed efficiently and correctly routed to the appropriate destinations.</p><p>Are you interested in more in-depth guides on data engineering, cloud solutions, data analytics and machine learning? Follow me on <a href="https://medium.com/@nerukulla0719">Medium</a> or <a href="http://www.linkedin.com/in/naresh-erukulla-80529a121">LinkedIn</a> for the latest articles, and feel free to share your thoughts or questions in the comments below. If you found this article helpful, share it with your network and help others unlock the potential of data engineering.</p><p>You might be interested in additional articles that I wrote here on Medium:</p><ul><li><a href="https://medium.com/@nerukulla0719/building-real-time-retail-analytics-with-google-cloud-from-data-ingestion-to-demand-forecasting-e2766c9e9a4e">Building Real-Time Retail Analytics with Google Cloud: From Data Ingestion to Demand Forecasting</a></li><li><a href="https://towardsdev.com/transforming-xml-to-json-for-bigquery-integration-6e639110809a">Transforming XML to JSON for BigQuery Integration</a></li><li><a href="https://towardsdev.com/window-functions-vs-subqueries-a-battle-of-sql-powerhouses-ca1759ee9c05">Window Functions vs Subqueries: A Battle of SQL Powerhouses</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48dbf221f14b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Window Functions vs Subqueries: A Battle of SQL Powerhouses]]></title>
            <link>https://medium.com/@nerukulla0719/window-functions-vs-subqueries-a-battle-of-sql-powerhouses-ca1759ee9c05?source=rss-2ac42812f8fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1759ee9c05</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Naresh Erukulla]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 04:50:39 GMT</pubDate>
            <atom:updated>2024-10-24T05:46:02.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GcXO-PhK7SUXWVNf" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of SQL, we often find ourselves needing to perform calculations that go beyond simple aggregations. One common task is calculating running totals, where we want to see the cumulative sum of a value over a specific period or group. This is where two powerful SQL features come into play: window functions and subqueries.</p><p>Let’s dive into a real-world example to understand how these two approaches work and which one might be better suited for your needs.</p><h3><strong>Scenario: Tracking Sales Performance</strong></h3><p>Imagine you’re working for a company that sells various products. You need to analyze sales data to understand the performance of each product over time. Your dataset has the following columns:</p><blockquote>order_date: The date of the order.</blockquote><blockquote>product_id: The unique identifier for each product.</blockquote><blockquote>sales_amount: The total amount of sales for that order.</blockquote><p><strong>Goal</strong>: Calculate the running total of sales for each product, showing the cumulative sales amount for each order date.</p><h4>Subquery Approach</h4><p>We can achieve this using a correlated subquery:</p><pre>SELECT<br>  order_date,<br>  product_id,<br>  sales_amount,<br>  (<br>    SELECT SUM(sales_amount)<br>    FROM sales_data s2<br>    WHERE s2.product_id = s1.product_id<br>      AND s2.order_date &lt;= s1.order_date<br>  ) AS running_total<br>FROM<br>  sales_data s1;</pre><p>This query works by iterating through each row in the sales_data table (aliased as s1). For each row, it executes a subquery (aliased as s2) that sums up the sales_amount for the same product_id where the order_date is less than or equal to the current row&#39;s order_date. This gives us the running total for each row.</p><h4>Window Function Approach</h4><p>Using a window function, we can achieve the same result more efficiently:</p><pre>SELECT<br>  order_date,<br>  product_id,<br>  sales_amount,<br>  SUM(sales_amount) OVER (PARTITION BY product_id ORDER BY order_date) AS running_total<br>FROM<br>  sales_data;</pre><p>This query uses the SUM window function with a PARTITION BY clause to group the data by product_id and an ORDER BY clause to order the data by order_date. The SUM function then calculates the running total for each product, accumulating the sales_amount as we move through the ordered data.</p><h4>Sample Results:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*AHqLa4tYJcHp8_7vO30NHw.png" /><figcaption>Sample Results Captured on Local Machine</figcaption></figure><h3>Pros and Cons</h3><h4>Subqueries :</h4><h4>Pros:</h4><blockquote><em>Can be used for more complex calculations involving multiple tables.</em></blockquote><blockquote><em>More flexible for handling specific conditions.</em></blockquote><h4>Cons:</h4><blockquote>Can be less efficient than window functions, especially for large datasets.</blockquote><blockquote>Can be harder to read and understand, especially for complex queries.</blockquote><h4>Window Functions :</h4><h4>Pros:</h4><blockquote>Generally more efficient than subqueries, especially for large datasets.</blockquote><blockquote>More concise and readable syntax.</blockquote><blockquote>Offer more flexibility with options like ROWS and RANGE boundaries.</blockquote><h4>Cons:</h4><blockquote>Can be less flexible for complex calculations involving multiple tables.</blockquote><blockquote>Not as widely supported in all database systems.</blockquote><h4>When to Use Which</h4><ul><li><strong><em>Subqueries</em></strong><em>:</em> Use subqueries when you need to perform complex calculations involving multiple tables or when you need to access data based on specific conditions.</li><li><strong><em>Window Functions</em></strong>: Use window functions for calculations over partitions of data, especially when performance is critical and readability is important.</li></ul><h4>In Conclusion</h4><p>Both subqueries and window functions are powerful tools in the SQL arsenal. Understanding their strengths and weaknesses allows you to choose the most appropriate approach for your specific needs. While window functions often offer a more efficient and readable solution for calculations over partitions, subqueries remain valuable for complex calculations and specific data access scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1759ee9c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-Time Retail Analytics with Google Cloud: From Data Ingestion to Demand Forecasting]]></title>
            <link>https://medium.com/@nerukulla0719/building-real-time-retail-analytics-with-google-cloud-from-data-ingestion-to-demand-forecasting-e2766c9e9a4e?source=rss-2ac42812f8fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2766c9e9a4e</guid>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[retail-forecasting]]></category>
            <category><![CDATA[lstm-networks]]></category>
            <category><![CDATA[ai-model]]></category>
            <dc:creator><![CDATA[Naresh Erukulla]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 22:27:04 GMT</pubDate>
            <atom:updated>2024-07-30T22:27:04.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*STZd6BPCJOVMioLkiqFevw.jpeg" /></figure><p>The retail industry is rapidly evolving, and the need for real-time analytics has never been more critical. Accurate demand forecasting across various product attributes, such as size, color, and design, can significantly impact inventory management, customer satisfaction, and overall profitability. In this article, we will explore how to build an end-to-end real-time analytics solution using Google Cloud services, specifically Pub/Sub, Dataflow, and BigQuery. We will also integrate machine learning (ML) and artificial intelligence (AI) tools to forecast demand based on geographic locations, customer behavior, and seasonality.</p><h3>1. Introduction</h3><p>Real-time data analytics provides retailers with the ability to make informed decisions quickly. By analyzing data from both digital and brick-and-mortar stores, businesses can optimize their inventory, pricing strategies, and marketing efforts. This article will guide you through the architecture and implementation of a comprehensive real-time analytics solution, showcasing its application in retail demand forecasting.</p><h3>2. System Architecture Overview</h3><p>The solution consists of the following components:</p><ol><li><strong>Data Ingestion</strong>: Google Cloud Pub/Sub for real-time data streaming.</li><li><strong>Data Processing</strong>: Google Cloud Dataflow for real-time data transformation and enrichment.</li><li><strong>Data Storage and Analysis</strong>: Google BigQuery for scalable storage and complex analytical queries.</li><li><strong>Machine Learning and AI</strong>: ML models for demand forecasting, considering various factors such as historical data, customer behavior, and seasonality.</li></ol><h3>3. Data Ingestion with Google Cloud Pub/Sub</h3><p>Google Cloud Pub/Sub is a fully managed messaging service that enables reliable and real-time event ingestion. In our solution, Pub/Sub ingests data from multiple sources, including:</p><ul><li><strong>E-commerce Transactions</strong>: Data on product views, add-to-cart actions, and purchases.</li><li><strong>In-Store Sales Data</strong>: Point-of-sale (POS) data from physical stores.</li><li><strong>Customer Interaction Data</strong>: Feedback, reviews, and customer service interactions.</li></ul><h3>Example: Publishing a Message to Pub/Sub</h3><pre>from google.cloud import pubsub_v1<br>import json<br># Set up your GCP project and topic<br>project_id = &quot;your-gcp-project-id&quot;<br>topic_id = &quot;retail-transaction-data&quot;<br>publisher = pubsub_v1.PublisherClient()<br>topic_path = publisher.topic_path(project_id, topic_id)<br># Example data representing a retail transaction<br>data = {<br>    &quot;product_id&quot;: &quot;123&quot;,<br>    &quot;action&quot;: &quot;purchase&quot;,<br>    &quot;timestamp&quot;: &quot;2024-07-30T12:34:56Z&quot;,<br>    &quot;size&quot;: &quot;M&quot;,<br>    &quot;color&quot;: &quot;red&quot;,<br>    &quot;price&quot;: 29.99,<br>    &quot;promotion&quot;: &quot;summer_sale&quot;,<br>    &quot;coupon_eligibility&quot;: True,<br>    &quot;location&quot;: &quot;online&quot;,<br>    &quot;shipping_time&quot;: 3,<br>    &quot;store_id&quot;: &quot;store_456&quot;,<br>    &quot;foot_traffic&quot;: 150,<br>    &quot;region&quot;: &quot;north&quot;,<br>    &quot;store_promotions&quot;: &quot;BOGO&quot;,<br>    &quot;season&quot;: &quot;summer&quot;,<br>    &quot;quantity&quot;: 1<br>}<br># Publish the message to the Pub/Sub topic<br>message_data = json.dumps(data).encode(&quot;utf-8&quot;)<br>publisher.publish(topic_path, data=message_data)</pre><h3>Data Processing with Google Cloud Dataflow</h3><p>Google Cloud Dataflow is a unified stream and batch data processing service. It allows for real-time data transformations, such as filtering, aggregation, and enrichment, before the data is stored in BigQuery.</p><h3>Dataflow Pipeline Example</h3><pre>import apache_beam as beam<br>from apache_beam.options.pipeline_options import PipelineOptions<br>def parse_event(element):<br>    import json<br>    event = json.loads(element)<br>    return event<br>def filter_purchases(event):<br>    # Keep only purchase actions<br>    return event[&#39;action&#39;] == &#39;purchase&#39;<br>def format_for_bigquery(event):<br>    # Format the event for BigQuery<br>    return {<br>        &#39;product_id&#39;: event[&#39;product_id&#39;],<br>        &#39;timestamp&#39;: event[&#39;timestamp&#39;],<br>        &#39;size&#39;: event[&#39;size&#39;],<br>        &#39;color&#39;: event[&#39;color&#39;],<br>        &#39;price&#39;: event[&#39;price&#39;],<br>        &#39;promotion&#39;: event[&#39;promotion&#39;],<br>        &#39;coupon_eligibility&#39;: event[&#39;coupon_eligibility&#39;],<br>        &#39;location&#39;: event[&#39;location&#39;],<br>        &#39;shipping_time&#39;: event[&#39;shipping_time&#39;],<br>        &#39;store_id&#39;: event[&#39;store_id&#39;],<br>        &#39;foot_traffic&#39;: event[&#39;foot_traffic&#39;],<br>        &#39;region&#39;: event[&#39;region&#39;],<br>        &#39;store_promotions&#39;: event[&#39;store_promotions&#39;],<br>        &#39;season&#39;: event[&#39;season&#39;],<br>        &#39;quantity&#39;: event[&#39;quantity&#39;]<br>    }<br># Dataflow pipeline options<br>pipeline_options = PipelineOptions(<br>    project=&#39;your-gcp-project-id&#39;,<br>    temp_location=&#39;gs://your-bucket/temp&#39;,<br>    runner=&#39;DataflowRunner&#39;<br>)<br># Define the Dataflow pipeline<br>with beam.Pipeline(options=pipeline_options) as p:<br>    (p <br>     | &#39;Read from Pub/Sub&#39; &gt;&gt; beam.io.ReadFromPubSub(topic=&#39;projects/your-gcp-project-id/topics/retail-transaction-data&#39;)<br>     | &#39;Parse JSON&#39; &gt;&gt; beam.Map(parse_event)<br>     | &#39;Filter Purchases&#39; &gt;&gt; beam.Filter(filter_purchases)<br>     | &#39;Format for BigQuery&#39; &gt;&gt; beam.Map(format_for_bigquery)<br>     | &#39;Write to BigQuery&#39; &gt;&gt; beam.io.WriteToBigQuery(<br>           &#39;your-gcp-project-id:dataset.table&#39;,<br>           schema=&#39;product_id:STRING, timestamp:TIMESTAMP, size:STRING, color:STRING, price:FLOAT, promotion:STRING, coupon_eligibility:BOOLEAN, location:STRING, shipping_time:INTEGER, store_id:STRING, foot_traffic:INTEGER, region:STRING, store_promotions:STRING, season:STRING, quantity:INTEGER&#39;<br>       )<br>    )</pre><h3>5. Data Storage and Analysis with Google BigQuery</h3><p>Google BigQuery is a fully managed data warehouse that enables super-fast SQL queries using the processing power of Google’s infrastructure. It’s an ideal choice for storing and analyzing large datasets.</p><h3>Example BigQuery Query</h3><pre>SELECT <br>  product_id,<br>  size,<br>  color,<br>  price,<br>  promotion,<br>  coupon_eligibility,<br>  location,<br>  shipping_time,<br>  store_id,<br>  foot_traffic,<br>  region,<br>  store_promotions,<br>  season,<br>  COUNT(*) AS sales_count,<br>  SUM(quantity) AS total_quantity,<br>  EXTRACT(DATE FROM timestamp) AS date<br>FROM <br>  `your-gcp-project-id.dataset.table`<br>WHERE <br>  promotion = &#39;summer_sale&#39;<br>GROUP BY <br>  product_id, size, color, price, promotion, coupon_eligibility, location, shipping_time, store_id, foot_traffic, region, store_promotions, season, date<br>ORDER BY <br>  date DESC, sales_count DESC;</pre><h3>6. AI Models for Demand Forecasting</h3><p>We will build and compare two AI models to forecast retail demand:</p><ol><li><strong>Linear Regression</strong>: A simple, interpretable model.</li><li><strong>LSTM (Long Short-Term Memory)</strong>: A more complex model capable of capturing temporal dependencies in the data.</li></ol><h4>6.1 Data Preparation and Feature Engineering</h4><p>To build the demand forecasting models, we first need to prepare the data and engineer features. Features can include historical sales, promotions, holidays, weather data, and more.</p><pre>import pandas as pd<br>import numpy as np<br><br># Sampledata preparation<br>data = pd.DataFrame({<br>    &#39;date&#39;: pd.date_range(start=&#39;2024-01-01&#39;, periods=180, freq=&#39;D&#39;),<br>    &#39;product_id&#39;: [&#39;123&#39;] * 180,<br>    &#39;size&#39;: [&#39;M&#39;] * 180,<br>    &#39;color&#39;: [&#39;red&#39;] * 180,<br>    &#39;price&#39;: np.random.uniform(20, 40, 180),<br>    &#39;promotion&#39;: [&#39;summer_sale&#39;] * 180,<br>    &#39;coupon_eligibility&#39;: [True] * 180,<br>    &#39;location&#39;: [&#39;online&#39;] * 180,<br>    &#39;shipping_time&#39;: [3] * 180,<br>    &#39;store_id&#39;: [&#39;store_456&#39;] * 180,<br>    &#39;foot_traffic&#39;: np.random.randint(100, 200, 180),<br>    &#39;region&#39;: [&#39;north&#39;] * 180,<br>    &#39;store_promotions&#39;: [&#39;BOGO&#39;] * 180,<br>    &#39;season&#39;: [&#39;summer&#39;] * 180,<br>    &#39;quantity&#39;: np.random.poisson(lam=20, size=180)<br>})<br><br># Create additional features<br>data[&#39;day_of_week&#39;] = data[&#39;date&#39;].dt.dayofweek<br>data[&#39;is_weekend&#39;] = data[&#39;day_of_week&#39;].apply(lambda x: 1 if x &gt;= 5 else 0)<br>data[&#39;month&#39;] = data[&#39;date&#39;].dt.month<br><br># Target variable<br>data[&#39;target&#39;] = data[&#39;quantity&#39;].shift(-1)  # Forecast next day&#39;s quantity<br>data.dropna(inplace=True)</pre><h4>6.2 Model Building with Linear Regression and LSTM</h4><p><strong>Linear Regression Model</strong></p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_absolute_error, mean_squared_error<br><br># Split data into training and testing<br>X = data[[&#39;day_of_week&#39;, &#39;is_weekend&#39;, &#39;month&#39;, &#39;price&#39;, &#39;foot_traffic&#39;]]<br>y = data[&#39;target&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Initialize and train the model<br>linear_model = LinearRegression()<br>linear_model.fit(X_train, y_train)<br><br># Predictions<br>y_pred_lr = linear_model.predict(X_test)<br><br># Evaluation<br>mae_lr = mean_absolute_error(y_test, y_pred_lr)<br>mse_lr = mean_squared_error(y_test, y_pred_lr)<br>print(f&#39;Linear Regression MAE: {mae_lr}, MSE: {mse_lr}&#39;)</pre><p><strong>LSTM Model</strong></p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, LSTM<br><br># Reshape data for LSTM model<br>X_lstm = np.expand_dims(X.values, axis=2)<br>X_train_lstm, X_test_lstm, y_train_lstm, y_test_lstm = train_test_split(X_lstm, y, test_size=0.2, random_state=42)<br><br># Define the LSTM model<br>lstm_model = Sequential([<br>    LSTM(64, activation=&#39;relu&#39;, input_shape=(X_train_lstm.shape[1], X_train_lstm.shape[2])),<br>    Dense(1)<br>])<br><br># Compile the model<br>lstm_model.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;, metrics=[&#39;mae&#39;])<br><br># Train the model<br>lstm_model.fit(X_train_lstm, y_train_lstm, epochs=50, batch_size=16, validation_split=0.2)<br><br># Predictions<br>y_pred_lstm = lstm_model.predict(X_test_lstm)<br><br># Evaluation<br>mae_lstm = mean_absolute_error(y_test_lstm, y_pred_lstm)<br>mse_lstm = mean_squared_error(y_test_lstm, y_pred_lstm)<br>print(f&#39;LSTM Model MAE: {mae_lstm}, MSE: {mse_lstm}&#39;)</pre><h4>6.3 Model Evaluation and Comparison</h4><pre>import matplotlib.pyplot as plt<br># Plotting predictions for both models<br>plt.figure(figsize=(12, 6))<br>plt.plot(y_test.values, label=&#39;Actual&#39;, color=&#39;black&#39;)<br>plt.plot(y_pred_lr, label=&#39;Linear Regression&#39;, linestyle=&#39;--&#39;, color=&#39;blue&#39;)<br>plt.plot(y_pred_lstm, label=&#39;LSTM&#39;, linestyle=&#39;--&#39;, color=&#39;green&#39;)<br>plt.xlabel(&#39;Samples&#39;)<br>plt.ylabel(&#39;Demand&#39;)<br>plt.title(&#39;Model Predictions Comparison&#39;)<br>plt.legend()<br>plt.show()</pre><p><strong>Explanation and Comparison</strong>:</p><ul><li><strong>Linear Regression</strong>: This model provides a straightforward and interpretable approach but may lack the ability to capture complex patterns, especially in time series data.</li><li><strong>LSTM</strong>: LSTM networks are particularly effective for time series forecasting as they can capture long-term dependencies in sequential data. In our comparison, LSTM provided lower MAE and MSE, indicating better performance.</li></ul><h3>7. Automation and Monitoring</h3><p>To maintain the reliability of the analytics system, it’s crucial to automate data pipelines and monitor system performance. Tools like Google Cloud Monitoring and logging services can help track system health and identify issues promptly.</p><h3>Automation and Monitoring Steps</h3><ol><li><strong>Automated Data Pipeline Deployment</strong>: Use CI/CD pipelines for deploying Dataflow jobs and ML models.</li><li><strong>Monitoring</strong>: Set up dashboards and alerts in Google Cloud Monitoring to track key metrics such as data processing times, model performance, and error rates.</li><li><strong>Error Handling</strong>: Implement retry mechanisms and data validation checks to handle errors gracefully.</li></ol><h3>8. Conclusion</h3><p>In this article, we explored a comprehensive real-time analytics solution for the retail industry using Google Cloud services and AI models. By leveraging Pub/Sub, Dataflow, BigQuery, and TensorFlow, retailers can gain valuable insights into customer behavior and market trends, optimize inventory levels, and enhance overall business performance. We compared two AI models — Linear Regression and LSTM — highlighting the strengths and weaknesses of each in demand forecasting.</p><p>This architecture serves as a robust framework for real-time analytics, enabling businesses to make data-driven decisions and stay ahead of market trends.</p><p>Are you interested in more in-depth guides on data analytics and machine learning? Follow me on <a href="https://medium.com/@nerukulla0719">Medium</a> or <a href="http://www.linkedin.com/in/naresh-erukulla-80529a121">LinkedIn</a> for the latest articles, and feel free to share your thoughts or questions in the comments below. If you found this article helpful, share it with your network and help others unlock the potential of real-time analytics in retail.</p><p>You might be interested in additional articles that I wrote here on Medium:</p><p><a href="https://medium.com/@nerukulla0719/transforming-xml-to-json-for-bigquery-integration-6e639110809a">Transforming XML to JSON for BigQuery Integration</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2766c9e9a4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming XML to JSON for BigQuery Integration]]></title>
            <link>https://medium.com/@nerukulla0719/transforming-xml-to-json-for-bigquery-integration-6e639110809a?source=rss-2ac42812f8fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e639110809a</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[dataflow]]></category>
            <dc:creator><![CDATA[Naresh Erukulla]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 15:28:01 GMT</pubDate>
            <atom:updated>2024-08-01T17:19:00.064Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Data Engineer, I often encounter challenges that require innovative solutions. Recently, I faced a problem where streaming data came in XML format, but our data processing pipeline, which uses Google Cloud Dataflow and BigQuery, requires data in JSON format. To address this, I developed a Python solution to convert incoming XML data to JSON, ensuring smooth integration with BigQuery. In this article, I’ll walk you through the solution, provide a sample implementation, and share some insights for professionals in the field.</p><h3>The Problem</h3><p>XML (Extensible Markup Language) is a widely used format for data interchange. However, BigQuery, a powerful data analytics platform, does not natively support XML. This necessitates a conversion to JSON (JavaScript Object Notation), which is a more compatible and lightweight data interchange format. The challenge was to design a system that listens to a Pub/Sub topic, processes XML messages, converts them to JSON, and then loads them into BigQuery.</p><h3>The Solution</h3><p>The solution involves a Python script that subscribes to a Google Cloud Pub/Sub topic, processes the XML messages, converts them to JSON, and prepares them for loading into BigQuery. The following is a detailed explanation of the implementation.</p><ul><li>Setting Up Pub/Sub Subscriber</li></ul><p>We start by setting up a Pub/Sub subscriber to listen for incoming messages:</p><pre>import json<br>import xml.etree.ElementTree as ET<br>from google.cloud import pubsub_v1<br>project_id = &quot;your-project-id&quot;<br>subscription_id = &quot;your-subscription-id&quot;<br>subscriber_client = pubsub_v1.SubscriberClient()<br>subscription_path = subscriber_client.subscription_path(project_id, subscription_id)</pre><ul><li>Parsing XML to JSON</li></ul><p>The core functionality involves parsing XML data into a dictionary format, which is then easily convertible to JSON. Here’s the function to parse XML:</p><pre>def get_local_name(tag):<br>    return tag.split(&#39;}&#39;)[-1]<br>def parse_xml_to_dict(elem):<br>    if not list(elem) and elem.text:<br>        return elem.text.strip()<br>    result = {}<br>    for child in elem:<br>        child_tag = get_local_name(child.tag)<br>        if not child.attrib:<br>            child_result = parse_xml_to_dict(child)<br>            if child_tag in result:<br>                if not isinstance(result[child_tag], list):<br>                    result[child_tag] = [result[child_tag]]<br>                result[child_tag].append(child_result)<br>            else:<br>                result[child_tag] = child_result<br>        else:<br>            child_result = parse_xml_to_dict(child)<br>            for key, value in child.attrib.items():<br>                attributes = {}<br>                attributes[&#39;id&#39;] = value<br>                attributes[&#39;value&#39;] = child_result<br>                if child_tag in result:<br>                    if not isinstance(result[child_tag], list):<br>                        result[child_tag] = [result[child_tag]]<br>                    result[child_tag].append(attributes)<br>                else:<br>                    result[child_tag] = attributes<br>    <br>    if elem.attrib:<br>        attributes = {get_local_name(key): value for key, value in elem.attrib.items()}<br>        result[&#39;@attributes&#39;] = attributes<br>    <br>    return result</pre><ul><li>Handling Messages and Conversion</li></ul><p>The callback function handles incoming messages, decodes the XML, converts it to JSON, and acknowledges the message:</p><pre>def callback(message):<br>    print(f&quot;Received message: {message}&quot;)<br>    try:<br>        xml_data = message.data.decode(&#39;utf-8&#39;)<br>        root = ET.fromstring(xml_data)<br>        <br>        body = root.find(&#39;.//{http://schemas.xmlsoap.org/soap/envelope/}Body&#39;)<br>        if body is None:<br>            raise ValueError(&quot;SOAP Body not found in the message&quot;)<br>        <br>        filename = &#39;converted_json_message.json&#39;<br>        with open(filename, &#39;w&#39;) as file:<br>            json_data = json.dumps(parse_xml_to_dict(body))<br>            file.write(json_data + &#39;\n&#39;)<br>        <br>        message.ack()<br>    except Exception as e:<br>        print(f&quot;Error processing message: {e}&quot;)<br>        message.nack()</pre><ul><li>Running the Subscriber</li></ul><p>Finally, the subscriber listens for incoming messages:</p><pre>streaming_pull_future = subscriber_client.subscribe(subscription_path, callback=callback)<br>print(f&quot;Listening for messages on {subscription_path}...&quot;)<br>try:<br>    streaming_pull_future.result()<br>except KeyboardInterrupt:<br>    streaming_pull_future.cancel()</pre><ul><li>Dummy Data Example</li></ul><p>To illustrate, let’s consider a sample XML message:</p><pre>&lt;Envelope xmlns=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;<br>    &lt;Body&gt;<br>        &lt;Message&gt;<br>            &lt;ID&gt;12345&lt;/ID&gt;<br>            &lt;Content&gt;Hello, world!&lt;/Content&gt;<br>        &lt;/Message&gt;<br>    &lt;/Body&gt;<br>&lt;/Envelope&gt;</pre><p>The script converts this to the following JSON:</p><pre>{<br>    &quot;Message&quot;: {<br>        &quot;ID&quot;: &quot;12345&quot;,<br>        &quot;Content&quot;: &quot;Hello, world!&quot;<br>    }<br>}</pre><h3>Conclusion</h3><p>This Python-based solution effectively transforms XML data into JSON format, enabling seamless integration with BigQuery. It demonstrates a practical approach to handling format conversion in data pipelines, crucial for real-time data processing.</p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/naresh-erukulla-80529a121">LinkedInConnect</a> or <a href="https://medium.com/@nerukulla0719">Medium</a> for more insights and updates. Sharing knowledge and learning from the community are vital parts of our growth as professionals. Let’s continue to innovate and solve challenges together!</p><p>I hope this article helps you understand the process of converting XML data to JSON for use in BigQuery using Python. If you have any questions or need further assistance, please leave a comment or reach out directly. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e639110809a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>