<?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 Rahul Madhani on Medium]]></title>
        <description><![CDATA[Stories by Rahul Madhani on Medium]]></description>
        <link>https://medium.com/@rahulmadhani20?source=rss-848ed590b97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7Bf3qfO3nA2D9G7jj5SEuQ.jpeg</url>
            <title>Stories by Rahul Madhani on Medium</title>
            <link>https://medium.com/@rahulmadhani20?source=rss-848ed590b97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:38:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulmadhani20/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[Send Python Logs Asynchronously to Logstash for Real-Time Insights]]></title>
            <link>https://blog.dataengineerthings.org/send-python-logs-asynchronously-to-logstash-for-real-time-insights-51de5c27c325?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/51de5c27c325</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 16:45:00 GMT</pubDate>
            <atom:updated>2024-11-11T16:45:00.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Implementation Guide for Asynchronous Log Shipping from Python or Pyspark (Databricks) to Logstash in the ELK Stack.</h4><h3>Introduction</h3><p>Real-time logging is essential for monitoring application health, identifying issues, and gaining insights as events happen. By sending logs to <strong>Logstash</strong> in the <a href="https://www.elastic.co/elastic-stack"><strong>ELK Stack</strong></a> (Elasticsearch, Logstash, and Kibana), teams can centralize and analyze log data for deeper visibility. However, sending logs synchronously can slow down applications, making <strong>asynchronous logging</strong> a better choice. Asynchronous logging lets applications send logs independently in the background, ensuring smooth performance without delays. This guide explores the importance of real-time, asynchronous logging to Logstash and provides a step-by-step setup for <a href="https://www.python.org/">Python </a>applications, enabling efficient and proactive monitoring.</p><figure><img alt="Send Python Logs to Logstash" src="https://cdn-images-1.medium.com/max/1024/1*dwliFAlHRCYzMPCRzxmrAQ.jpeg" /><figcaption>Send Python Logs to Logstash</figcaption></figure><h3>ELK Stack</h3><p>The <strong>ELK Stack, </strong>comprised of <strong>Elasticsearch, Logstash, and Kibana,</strong> is a powerful toolset for log and event data processing, analysis, and visualization. Each component has a specific role:</p><ol><li><strong>Elasticsearch</strong>: A distributed search and analytics engine, Elasticsearch stores and indexes large volumes of data, making it easy to search and analyze.</li><li><strong>Logstash</strong>: Acts as the data processing pipeline, collecting, transforming, and routing log or event data from multiple sources before sending it to Elasticsearch for indexing.</li><li><strong>Kibana</strong>: A visualization tool for Elasticsearch data, Kibana allows users to create interactive dashboards and perform real-time data analysis.</li></ol><p>The ELK Stack is commonly used for <strong>log management</strong>, <strong>real-time analytics</strong>, and <strong>monitoring</strong> applications, providing organizations with insights into system performance, security events, and operational trends.</p><h3>ELK Use cases</h3><h4>1. Log and Event Management</h4><p>ELK Stack is often deployed as a centralized logging solution, aggregating logs from various applications, servers, and devices. It allows users to search, filter, and analyze logs quickly, making it easier to troubleshoot issues, understand application behavior, and monitor events in real-time.</p><h4>2. Application Performance Monitoring (APM)</h4><p>By integrating with APM tools, ELK helps monitor application performance metrics, such as response times, transaction speeds, and error rates. This data helps developers and IT teams identify bottlenecks, monitor system health, and improve performance.</p><h4>3. Security and Threat Detection</h4><p>The ELK Stack is a common choice in SIEM (Security Information and Event Management) solutions, where it’s used to collect and analyze security-related data from firewalls, intrusion detection systems, and endpoint logs. It can detect patterns indicating potential security threats and generate alerts in real time.</p><h4>4. Business Intelligence and Analytics</h4><p>ELK is used to track and analyze business metrics by ingesting data such as user activity, sales trends, and website traffic. This data provides valuable insights into customer behavior and supports data-driven decision-making.</p><h4>5. IoT Data Analysis</h4><p>ELK can process and analyze data from IoT devices, aggregating sensor data, device logs, and metrics. This supports real-time monitoring of IoT networks and devices, helping with predictive maintenance, anomaly detection, and optimization of device performance.</p><h4>6. Compliance and Auditing</h4><p>ELK Stack can centralize and retain logs as per compliance requirements, making it easier to perform audits. It helps organizations meet data retention policies and facilitates forensic analysis by keeping an organized and searchable log history.</p><p>The ELK Stack’s flexibility and scalability make it suitable for any environment that requires log management, operational visibility, or real-time analytics.</p><h3>Synchronous Vs Asynchronous</h3><p>We need to send logs from our Python application to Logstash which takes care of the collecting of data (logs) from the sources. Now to send these logs we have two options we can either send logs in synchronous mode or asynchronous mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jmDFToSz08ldQKlq" /><figcaption>Photo by <a href="https://unsplash.com/@jonathanborba?utm_source=medium&amp;utm_medium=referral">Jonathan Borba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1. Synchronous Logging</h4><p>In synchronous logging, each logging operation is performed immediately in sequence. When a log event occurs, the <strong>application waits for the logging action to complete</strong> (e.g., writing to a file or sending data over the network) before moving to the next line of code.</p><p>This approach can slow down applications, especially if logging takes time, such as when logs are sent over a network. However, synchronous logging ensures that logs are written in real time and in the correct order.</p><h4>2. Asynchronous Logging</h4><p>With asynchronous logging, log entries are queued and processed independently, <strong>allowing the main application to continue executing without waiting for each log to be written</strong>. A separate thread or background worker handles the logging queue.</p><p>This method is generally more efficient for high-throughput applications since it reduces the time spent on logging. However, there may be a slight delay in log entries appearing in the output, and logs may not always appear in the exact order of execution.</p><h3>Python Logstash Asyn Package</h3><p>The python-logstash-async package is a Python logging handler specifically designed for sending log messages asynchronously to a Logstash server. It’s useful when integrating Python applications with the ELK stack for centralized logging and monitoring.</p><h4>Key Features</h4><ol><li><strong>Asynchronous Logging</strong>: Uses a background thread to send log messages to Logstash without blocking the main application flow.</li><li><strong>Reliability</strong>: It queues log messages and manages retries, ensuring logs are not lost if the Logstash server is temporarily unavailable.</li><li><strong>Protocol Support</strong>: Supports multiple protocols, such as TCP, UDP, and HTTP, for sending log data to Logstash.</li><li><strong>JSON Formatting</strong>: Formats logs as JSON, compatible with Logstash and Elasticsearch, making it easy to parse and index log entries.</li></ol><h3>Implementation</h3><h4>1. Install Package</h4><pre>pip install python-logstash-async==3.0.0</pre><h4>2. Import Modules</h4><pre>import logging<br>from logstash_async.handler import AsynchronousLogstashHandler, LogstashFormatter<br>from logstash_async.transport import HttpTransport</pre><h4>3. Configure Logger</h4><pre>def configure_logger() -&gt; logging.Logger:<br>  # Initialize variables<br>  app_name = &quot;logstash-logging&quot;<br>  logging_level = &quot;DEBUG&quot;<br><br>  # Define format<br>  logging_format = &quot;%(asctime)s.%(msecs)03d: %(name)s: %(filename)-40s: %(levelname)-10s: %(message)s&quot;<br>  logging.basicConfig(format=logging_format, datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>  # Create a logger<br>  logger = logging.getLogger(app_name)<br>  level = logging.getLevelName(logging_level)<br>  logger.setLevel(level)<br><br>  # Define parameters for logstash handler<br>  logstash_host = &quot;logstash_host_xxxx&quot;<br>  logstash_port = xxx<br>  logstash_logging_timeout = 5.0<br>  logstash_ssl_certificate = &quot;/Workspace/ssl_certificates/xxx.crt&quot;<br><br>  # Define HTTP Transport for Logstash Handler<br>  logstash_transport = HttpTransport(<br>      logstash_host,<br>      logstash_port,<br>      ssl_verify=logstash_ssl_certificate,<br>      timeout=logstash_logging_timeout,<br>  )<br><br>  # Define Logstash Handler<br>  logstash_handler = AsynchronousLogstashHandler(<br>      logstash_host,<br>      logstash_port,<br>      transport=logstash_transport,<br>      database_path=&quot;&quot;,<br>      ssl_verify=True,<br>  )<br><br>  # Set Logstash formatter<br>  logstash_formatter = LogstashFormatter(extra_prefix=None)<br>  logstash_handler.setFormatter(logstash_formatter)<br><br>  # Add the logstash handler to the logger<br>  logger.addHandler(logstash_handler)<br><br>  return logger</pre><h4>4. Shutdown Logging</h4><pre>def shutdown_logging(logger: logging.Logger):<br>  # Flush all the handlers<br>  for handler in logger.handlers:<br>      handler.flush()<br><br>  # Clean log handlers<br>  logger.handlers.clear()<br>  logging.shutdown()</pre><h4>5. Log messages</h4><pre># Configure logging<br>logger = configure_logger()<br><br># Log messages<br>logger.debug(&quot;This is a debug message&quot;, extra=extra)<br>logger.info(&quot;This is a info message&quot;, extra=extra)<br>logger.warning(&quot;This is a warning message&quot;, extra=extra)<br>logger.error(&quot;This is a error message&quot;, extra=extra)<br><br># Shutdown logging<br>shutdown_logging(logger)</pre><h3>Complete Solution</h3><pre>pip install python-logstash-async==3.0.0</pre><pre>import logging<br>from logstash_async.handler import AsynchronousLogstashHandler, LogstashFormatter<br>from logstash_async.transport import HttpTransport<br><br><br>def configure_logger() -&gt; logging.Logger:<br>  # Initialize variables<br>  app_name = &quot;logstash-logging&quot;<br>  logging_level = &quot;DEBUG&quot;<br><br>  # Define format<br>  logging_format = &quot;%(asctime)s.%(msecs)03d: %(name)s: %(filename)-40s: %(levelname)-10s: %(message)s&quot;<br>  logging.basicConfig(format=logging_format, datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>  # Create a logger<br>  logger = logging.getLogger(app_name)<br>  level = logging.getLevelName(logging_level)<br>  logger.setLevel(level)<br><br>  # Define parameters for logstash handler<br>  logstash_host = &quot;logstash_host_xxxx&quot;<br>  logstash_port = xxx<br>  logstash_logging_timeout = 5.0<br>  logstash_ssl_certificate = &quot;/Workspace/ssl_certificates/xxx.crt&quot;<br><br>  # Define HTTP Transport for Logstash Handler<br>  logstash_transport = HttpTransport(<br>      logstash_host,<br>      logstash_port,<br>      ssl_verify=logstash_ssl_certificate,<br>      timeout=logstash_logging_timeout,<br>  )<br><br>  # Define Logstash Handler<br>  logstash_handler = AsynchronousLogstashHandler(<br>      logstash_host,<br>      logstash_port,<br>      transport=logstash_transport,<br>      database_path=&quot;&quot;,<br>      ssl_verify=True,<br>  )<br><br>  # Set Logstash formatter<br>  logstash_formatter = LogstashFormatter(extra_prefix=None)<br>  logstash_handler.setFormatter(logstash_formatter)<br><br>  # Add the logstash handler to the logger<br>  logger.addHandler(logstash_handler)<br><br>  return logger<br><br><br>def shutdown_logging(logger: logging.Logger):<br>  # Flush all the handlers<br>  for handler in logger.handlers:<br>      handler.flush()<br><br>  # Clean log handlers<br>  logger.handlers.clear()<br>  logging.shutdown()<br><br><br># Configure logging<br>logger = configure_logger()<br><br># Log messages<br>logger.debug(&quot;This is a debug message&quot;, extra=extra)<br>logger.info(&quot;This is a info message&quot;, extra=extra)<br>logger.warning(&quot;This is a warning message&quot;, extra=extra)<br>logger.error(&quot;This is a error message&quot;, extra=extra)<br><br># Shutdown logging<br>shutdown_logging(logger)</pre><h3>Conclusion</h3><p>Incorporating real-time, asynchronous logging into your Python application with Logstash and the ELK Stack can transform the way you monitor, troubleshoot, and optimize. By sending logs asynchronously, you avoid performance bottlenecks, enabling your application to operate smoothly even during high log volumes. Logstash, coupled with Elasticsearch and Kibana, brings powerful real-time analytics and visualization to your logs, giving you critical insights into application performance, security, and user behavior.</p><p>With the setup covered in this guide, you can now efficiently route log data from your Python application to Logstash in near real-time, ensuring that every critical event is captured without compromising on application speed. Whether you’re monitoring for quick troubleshooting, performance optimization, or proactive issue prevention, this approach sets a strong foundation for robust, scalable log management. As your application grows, this asynchronous logging pipeline will continue to support your needs, making it a reliable solution for any high-performance, data-driven environment.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>Reference</h3><ul><li><a href="https://python-logstash-async.readthedocs.io/en/latest/">Python Logstash Async - python-logstash-async 3.0.0 documentation</a></li><li><a href="https://pypi.org/project/python-logstash-async/">python-logstash-async</a></li><li><a href="https://blog.det.life/how-to-store-python-apps-logs-in-dbfs-and-volumes-in-databricks-8d41e08bde46">How to Store Python Apps Logs in DBFS and Volumes in Databricks</a></li><li><a href="https://medium.com/azure-tutorials/a-deep-dive-into-python-logging-practical-examples-for-developers-ca45a072e709">Make Your Application Production-Ready With Python Logging</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51de5c27c325" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/send-python-logs-asynchronously-to-logstash-for-real-time-insights-51de5c27c325">Send Python Logs Asynchronously to Logstash for Real-Time Insights</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Store Python Apps Logs in Databricks DBFS]]></title>
            <link>https://blog.dataengineerthings.org/how-to-store-python-apps-logs-in-dbfs-and-volumes-in-databricks-8d41e08bde46?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d41e08bde46</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 14:25:05 GMT</pubDate>
            <atom:updated>2025-04-16T11:05:06.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>Detailed Steps to Store Python Application Logs in Databricks DBFS Using FileHandler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYDmWuFuHKNloeqr" /><figcaption>Photo by <a href="https://unsplash.com/@brucemars?utm_source=medium&amp;utm_medium=referral">bruce mars</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing Python-based applications or frameworks in <a href="https://www.databricks.com/">Databricks</a>, it’s often necessary to store logs in <a href="https://docs.databricks.com/en/dbfs/index.html">DBFS</a> for traceability and future analysis. This blog will show how to store logs from custom Python applications or frameworks in DBFS to meet these needs.</p><p>In this post, we’ll focus on storing logs from Databricks applications or frameworks in DBFS, though the same method can be applied to Python applications running on Windows, Mac, or Linux to save logs in local file systems.</p><p>The <a href="https://docs.python.org/3/howto/logging.html">Python logging</a> module, part of the Python Standard Library, offers a powerful and customizable solution for managing logs in Python applications. It is easy to use yet highly configurable, providing developers with the control needed for their logging requirements. We’ll use the FileHandler to store logs in a file.</p><p>While we won’t cover the basics of Python logging in this post, we’ll dive straight into how to save log files to the local file system. For a detailed introduction to Python logging, you can refer to this blog.</p><p><a href="https://medium.com/azure-tutorials/a-deep-dive-into-python-logging-practical-examples-for-developers-ca45a072e709">Make Your Application Production-Ready With Python Logging</a></p><h3>File Handler</h3><p>The <strong>File Handler</strong> in Python’s logging module allows log messages to be written to a file instead of, or in addition to, the console.</p><p>The log file can be written in two modes:</p><ul><li><strong>Append mode</strong> (default): It keeps adding log messages to the existing file.</li><li><strong>Write mode</strong>: It overwrites the log file each time the program runs.</li></ul><h3>Implementation</h3><h4>1. Import Modules</h4><p>First, let’s import the necessary Python modules.</p><pre># Import the modules<br>import logging<br>from datetime import datetime<br>import time</pre><h4>2. Configure Logging</h4><p>This function sets up logging and returns a logger that can be used to log messages.</p><pre>def configure_logging(app_name: str) -&gt; logging.Logger:<br>    &quot;&quot;&quot;<br>    Function to configure logging for the application<br>        @Param: app_name (str): Name of the application<br>        @return: logger (logging.Logger): Returns the created logger<br>    &quot;&quot;&quot;<br><br>    # Create directory to save log files<br>    dbutils.fs.mkdirs(&quot;dbfs:/FileStore/logs/Test/&quot;)<br><br>    # Define the name of the log file<br>    current_timestamp = datetime.now().strftime(&quot;%Y%m%d%H%M%S&quot;)<br>    log_file = f&quot;/dbfs/FileStore/logs/Test/{app_name}_{current_timestamp}.log&quot;<br><br>    # Configure logging<br>    logging_format = &#39;%(name)s:%(asctime)s:%(levelname)s:%(message)s&#39;<br>    logging.basicConfig(format=logging_format)<br>    logger=logging.getLogger(app_name)<br>    logger.setLevel(logging.INFO)<br><br>    # Create the file handler to save the log file<br>    log_file_handler = logging.FileHandler(log_file)<br>    <br>    # Create a formatter and add it to the file handler<br>    formatter = logging.Formatter(logging_format, datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    log_file_handler.setFormatter(formatter)<br><br>    # Add file handler to the logger<br>    logger.addHandler(log_file_handler)<br><br>    return logger</pre><h4>3. Shutdown Logging</h4><p>At the end of the application, we will use this function to remove handlers and shut down the logging system.</p><pre>def shutdown_logging(logger: logging.Logger):<br>    &quot;&quot;&quot;<br>    Function to clear log handlers and shutdown logging<br>        @return: None<br>    &quot;&quot;&quot;<br><br>    # Flush the log handlers<br>    for handler in logger.handlers:<br>        handler.flush()<br><br>    # Clear logger handlers<br>    logger.handlers.clear()<br><br>    # Shutdown logging<br>    logging.shutdown()</pre><h4>4. Custom Application</h4><p>Below is the sample application for demonstration purposes.</p><pre>def dummy_custom_application(logger: logging.Logger):<br>    # Test log messages<br>    logger.debug(&#39;This is a debug message&#39;)<br>    logger.info(&#39;This is an info message&#39;)<br>    logger.warning(&#39;This is a warning message&#39;)<br>    logger.error(&#39;This is an error message&#39;)<br>    logger.critical(&#39;This is a critical message&#39;)<br><br>    # Dummy application logic<br>    for i in range(1,6):<br>        logger.info(f&quot;This is a custom message {i}&quot;)<br>        time.sleep(10)</pre><h4>5. Run Application</h4><p>Now, let’s run the application.</p><pre># Configure logging<br>logger = configure_logging(&quot;Test_Application&quot;)<br><br>try:<br>    # Run the custom application<br>    dummy_custom_application(logger)<br><br>except Exception as e: <br>    # Handle any exceptions<br>    logger.exception(f&quot;Error occurred in the application execution. Error message: {e}&quot;)<br><br>finally:<br>    # Shutdown logging<br>    shutdown_logging(logger)</pre><h4>6. Log Messages</h4><p>Here are the log messages from the log file generated during the application’s execution.</p><pre>Test_Application:2024-10-11 11:28:28:INFO:This is an info message<br>Test_Application:2024-10-11 11:28:28:WARNING:This is a warning message<br>Test_Application:2024-10-11 11:28:28:ERROR:This is an error message<br>Test_Application:2024-10-11 11:28:28:CRITICAL:This is a critical message<br>Test_Application:2024-10-11 11:28:28:INFO:This is a custom message 1<br>Test_Application:2024-10-11 11:28:38:INFO:This is a custom message 2<br>Test_Application:2024-10-11 11:28:48:INFO:This is a custom message 3<br>Test_Application:2024-10-11 11:28:58:INFO:This is a custom message 4<br>Test_Application:2024-10-11 11:29:08:INFO:This is a custom message 5</pre><h4>Complete Solution</h4><pre># Import the modules<br>import logging<br>from datetime import datetime<br>import time<br><br><br>def configure_logging(app_name: str) -&gt; logging.Logger:<br>    &quot;&quot;&quot;<br>    Function to configure logging for the application<br>        @Param: app_name (str): Name of the application<br>        @return: logger (logging.Logger): Returns the created logger<br>    &quot;&quot;&quot;<br><br>    # Create directory to save log files<br>    dbutils.fs.mkdirs(&quot;dbfs:/FileStore/logs/Test/&quot;)<br><br>    # Define the name of the log file<br>    current_timestamp = datetime.now().strftime(&quot;%Y%m%d%H%M%S&quot;)<br>    log_file = f&quot;/dbfs/FileStore/logs/Test/{app_name}_{current_timestamp}.log&quot;<br><br>    # Configure logging<br>    logging_format = &#39;%(name)s:%(asctime)s:%(levelname)s:%(message)s&#39;<br>    logging.basicConfig(format=logging_format)<br>    logger=logging.getLogger(app_name)<br>    logger.setLevel(logging.INFO)<br><br>    # Create the file handler to save the log file<br>    log_file_handler = logging.FileHandler(log_file)<br>    <br>    # Create a formatter and add it to the file handler<br>    formatter = logging.Formatter(logging_format, datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    log_file_handler.setFormatter(formatter)<br><br>    # Add file handler to the logger<br>    logger.addHandler(log_file_handler)<br><br>    return logger<br><br><br>def shutdown_logging(logger: logging.Logger):<br>    &quot;&quot;&quot;<br>    Function to clear log handlers and shutdown logging<br>        @return: None<br>    &quot;&quot;&quot;<br><br>    # Flush the log handlers<br>    for handler in logger.handlers:<br>        handler.flush()<br><br>    # Clear logger handlers<br>    logger.handlers.clear()<br><br>    # Shutdown logging<br>    logging.shutdown()<br><br><br>def dummy_custom_application(logger: logging.Logger):<br>    # Test log messages<br>    logger.debug(&#39;This is a debug message&#39;)<br>    logger.info(&#39;This is an info message&#39;)<br>    logger.warning(&#39;This is a warning message&#39;)<br>    logger.error(&#39;This is an error message&#39;)<br>    logger.critical(&#39;This is a critical message&#39;)<br><br>    # Dummy application logic<br>    for i in range(1,6):<br>        logger.info(f&quot;This is a custom message {i}&quot;)<br>        time.sleep(10)<br><br><br># Configure logging<br>logger = configure_logging(&quot;Test_Application&quot;)<br><br>try:<br>    # Run the custom application<br>    dummy_custom_application(logger)<br><br>except Exception as e: <br>    # Handle any exceptions<br>    logger.exception(f&quot;Error occurred in the application execution. Error message: {e}&quot;)<br><br>finally:<br>    # Shutdown logging<br>    shutdown_logging(logger)</pre><h3>Conclusion</h3><p>Effectively managing log files is essential for monitoring and analyzing the performance of Python applications. In this blog, we explored how to store logs in DBFS in Databricks, providing a robust solution for traceability and future analysis. By utilizing the Python logging module and its FileHandler, we can easily configure logging to capture important events and errors within our applications. This practice not only enhances debugging but also contributes to better application maintenance and performance monitoring.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>Reference</h3><p><a href="https://medium.com/azure-tutorials/a-deep-dive-into-python-logging-practical-examples-for-developers-ca45a072e709">Make Your Application Production-Ready With Python Logging</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d41e08bde46" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/how-to-store-python-apps-logs-in-dbfs-and-volumes-in-databricks-8d41e08bde46">How to Store Python Apps Logs in Databricks DBFS</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trigger and Monitor Databricks Job Runs from Azure Data Factory]]></title>
            <link>https://blog.dataengineerthings.org/trigger-and-monitor-databricks-job-runs-from-azure-data-factory-9cd4207deda7?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd4207deda7</guid>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 15:00:52 GMT</pubDate>
            <atom:updated>2024-10-07T15:00:52.168Z</atom:updated>
            <content:encoded><![CDATA[<h4>Complete guide to triggering and monitoring a Databricks job run from Azure Data Factory (ADF) using the REST API, along with code examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6PCaFgmeWs0z7hUD" /><figcaption>Photo by <a href="https://unsplash.com/@shaikhulud?utm_source=medium&amp;utm_medium=referral">Maxim Tolchinskiy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog, we will see how to trigger a Databricks job from <a href="https://learn.microsoft.com/en-us/azure/data-factory/">Azure Data Factory</a> (ADF) using the <a href="https://docs.databricks.com/api/workspace/introduction">Databricks REST API</a>, and continuously monitor its status until the job is completed.</p><p>We’ll dive into the process of configuring ADF pipelines to initiate Databricks jobs by making REST API calls, setting up authentication, and handling responses.</p><p>Additionally, we’ll cover how to implement a loop in ADF to check the job status at regular intervals, ensuring the job’s progress is tracked in real time. For instance, you’ll learn how to trigger a Databricks job that processes large datasets and receive updates on whether it’s running, succeeded, or failed allowing for more efficient orchestration of complex workflows.</p><h3>Implementation</h3><p>The entire ADF pipeline can be divided into three key components:</p><ol><li>Trigger the Databricks job</li><li>Monitor the status of the Databricks job run</li><li>Fail the ADF pipeline if the Databricks job fails</li></ol><figure><img alt="ADF Pipeline to trigger and track Databricks Job Run" src="https://cdn-images-1.medium.com/max/1024/1*NlsOouVlKr1hHgCRq249ow.png" /><figcaption>ADF Pipeline to trigger and track Databricks Job Run</figcaption></figure><h4>1. Trigger Databricks Job</h4><p>To trigger a job run using the Databricks REST API, you have two options:</p><p><strong>I. </strong><a href="https://docs.databricks.com/api/workspace/jobs/runnow"><strong>Trigger a new job run</strong></a>: Execute an existing job that has already been defined in Databricks.</p><p><strong>II. </strong><a href="https://docs.databricks.com/api/workspace/jobs/submit"><strong>Create and trigger a one-time run</strong></a>: Submit a one-time task without creating a persistent job. These runs are not visible in the Databricks UI. To check the status, you can use the jobs/runs/get API. This endpoint allows you to track the run state after submission.</p><p>Both API options will return a <strong>Job Run ID</strong>, which is essential for monitoring the job’s progress.</p><p>Follow the steps below to trigger a new run of an existing job. The same process applies to creating and triggering a one-time run, with the only difference being the request body and API endpoint used.</p><p>a. Open Azure Data Factory Studio</p><p>b. Create a new Pipeline</p><p>c. Create the below Pipeline Parameters</p><figure><img alt="ADF Pipeline Parameters" src="https://cdn-images-1.medium.com/max/875/1*-vqoTq7SDcbKrwmvvKN-gA.png" /><figcaption>ADF Pipeline Parameters</figcaption></figure><p><strong>Parameter 1:</strong></p><ul><li><strong>Name: </strong>DatabricksHostName</li><li><strong>Type: </strong>String</li><li><strong>Default Value:</strong> <a href="https://adb-xxx.azuredatabricks.net/">https://adb-xxx.azuredatabricks.net</a></li></ul><p>You can obtain the Databricks Hostname from the Databricks workspace URL. Alternatively, you can navigate to the <a href="https://portal.azure.com/">Azure Portal</a>, open the Azure Databricks resource, and copy the value of the URL property.<br>Example: <strong>https://adb-xxx.azuredatabricks.net</strong></p><p><strong>Parameter 2:</strong></p><ul><li><strong>Name: </strong>DatabricksJobId</li><li><strong>Type: </strong>String</li><li><strong>Default Value:</strong> 801xxxxxxx011920</li></ul><p>The Databricks Job ID refers to the unique identifier of the Databricks job you want to trigger from ADF. If you don’t have a Databricks job set up yet, you’ll need to create one before proceeding. For guidance on creating a Databricks job, you can refer to this <a href="https://docs.databricks.com/en/jobs/create-run-jobs.html#create-a-job">link</a>.</p><p>d. Create the below Pipeline Variables</p><figure><img alt="ADF Pipeline Variables" src="https://cdn-images-1.medium.com/max/868/1*X_fV2AJjvSS496YQ8PxuBA.png" /><figcaption>ADF Pipeline Variables</figcaption></figure><p><strong>Variable 1:</strong></p><ul><li><strong>Name: </strong>JobStatus</li><li><strong>Type: </strong>String</li><li><strong>Default Value:</strong> Running</li></ul><p><strong>Variable 2:</strong></p><ul><li><strong>Name: </strong>ContentType</li><li><strong>Type: </strong>String</li><li><strong>Default Value:</strong> application/json</li></ul><p><strong>Variable 3:</strong></p><ul><li><strong>Name: </strong>WaitSeconds</li><li><strong>Type: </strong>Integer</li><li><strong>Default Value:</strong> 30</li></ul><p>e. Add a Web Activity Trigger Job Run</p><figure><img alt="ADF Web Activity" src="https://cdn-images-1.medium.com/max/328/1*Nosz1cy6TglwwVUv-LDNwQ.png" /><figcaption>ADF Web Activity to Trigger Job</figcaption></figure><p>f. Configure the basic settings in the <strong>General</strong> tab of the Web Activity.</p><figure><img alt="General tab of ADF Web Activity" src="https://cdn-images-1.medium.com/max/742/1*7tKD-Ux3oz4CaqpEwZBiQQ.png" /><figcaption>General tab of ADF Web Activity</figcaption></figure><p>g. In the <strong>Settings</strong> tab, several key properties need to be configured. These properties define how the job will be executed and managed, ensuring that the ADF pipeline interacts with Databricks as expected.</p><figure><img alt="Settings tab of ADF Web Activity" src="https://cdn-images-1.medium.com/max/816/1*eo8hVVlVHgDA76JSihYbww.png" /><figcaption>Settings tab of ADF Web Activity</figcaption></figure><ul><li><strong>URL:</strong> The URL will be a combination of the Databricks Hostname and the API endpoint. We will concatenate the pipeline parameter for the Databricks Hostname with the <a href="https://docs.databricks.com/api/workspace/jobs/runnow"><strong>Trigger a new job run</strong></a> API endpoint, which is /api/2.1/jobs/run-now.</li></ul><pre>@concat(<br>    pipeline().parameters.DatabricksHostName,<br>    &#39;/api/2.1/jobs/run-now&#39;<br>)</pre><ul><li><strong>Method:</strong> The method will be <strong>POST</strong>, as this is a POST request.</li><li><strong>Body:</strong> In the request body, you must include the <strong>Job ID</strong> of the Databricks job you wish to trigger, along with any necessary job parameters. For example, in this case, we have two parameters defined in the Databricks job start_period_job and end_period_job. The values for these parameters are passed within the request body to ensure they are properly executed during the job run.</li></ul><pre>{<br>  &quot;job_id&quot;: &quot;@{pipeline().parameters.DatabricksJobId}&quot;,<br>  &quot;job_parameters&quot;: {<br>    &quot;start_period_job&quot;: &quot;20240301&quot;,<br>    &quot;end_period_job&quot;: &quot;20240331&quot;<br>  }<br>}</pre><ul><li><strong>Authentication:</strong> There are several authentication options available, with <strong>System-Assigned Managed Identity</strong> being the recommended approach. For this option, you need to assign the <strong>Contributor</strong> role to the ADF-managed identity on the Azure Databricks resource.<br>To do this:<br>‣ Open the <strong>Azure Databricks</strong> resource in the Azure Portal.<br>‣ Navigate to <strong>Access Control (IAM)</strong>.<br>‣ Click on <strong>Add Role Assignment</strong> and assign the <strong>Contributor</strong> role to the Azure Data Factory’s managed identity.</li></ul><figure><img alt="ADF Web Activity Authentication Options" src="https://cdn-images-1.medium.com/max/261/0*TSk75DA8UOu3pI1B.png" /><figcaption>ADF Web Activity Authentication Options</figcaption></figure><ul><li><strong>Resource:</strong> Provide the unique resource ID for the Azure Databricks service: 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d. This ID serves as the identifier for the Azure Databricks resource across all tenants and customers in Azure.</li><li><strong>Integration Runtime:</strong> Select an Integration Runtime that has the necessary access to the Databricks resource, ensuring that the API call can be executed successfully without any permission issues.</li></ul><h4>2. Monitor the status of the Databricks job run</h4><p>We will use an <strong>Until</strong> activity with three inner activities to continuously track the status of the triggered Databricks job run. This ensures that the pipeline monitors the job’s progress until it completes, allowing for real-time tracking and handling of the job’s final state.</p><figure><img alt="Until Activity to track Job run status" src="https://cdn-images-1.medium.com/max/545/1*_OPngHhNDM7G9tQqUhi1qg.png" /><figcaption>Until Activity to track Job run status</figcaption></figure><p>The three inner activities are:</p><ol><li><strong>Sleep Task</strong>: Pauses the pipeline for 30 seconds to allow time between status checks.</li><li><strong>Check Job Run Status</strong>: Uses the Databricks REST API to check the current status of the job run.</li><li><strong>Set Job Run Status</strong>: Updates a pipeline variable with the current job run status.</li></ol><p>We won’t go into detail about the <strong>Sleep Task</strong> and <strong>Set Job Run Status</strong> activities, as they are straightforward and can be easily created using the full ADF pipeline JSON provided below.</p><p>Let’s focus on the <strong>Check Job Run Status</strong> activity. This activity is crucial for making API calls to track the job’s progress and determine if the job is still running, has succeeded, or has failed.</p><figure><img alt="ADF Web Activity to Check Job Status" src="https://cdn-images-1.medium.com/max/256/1*1yPEuig9Xr4cIbhixmH6lQ.png" /><figcaption>ADF Web Activity to Check Job Status</figcaption></figure><p>In the <strong>Settings</strong> tab, we need to configure several key properties for the <strong>Check Job Run Status</strong> activity. These configurations will determine how the activity interacts with the Databricks REST API and retrieves the job status.</p><figure><img alt="Settings tab of ADF Web Activity" src="https://cdn-images-1.medium.com/max/578/1*Rt4CXvtlhGFnuAjZkTarXQ.png" /><figcaption>Settings tab of ADF Web Activity</figcaption></figure><ul><li><strong>URL</strong>: The URL for the API call will be constructed by combining the Databricks hostname with the API endpoint. We will concatenate the pipeline parameter for the Databricks hostname with the <a href="https://docs.databricks.com/api/workspace/jobs/getrun"><strong>Get a Single Job Run</strong></a> API endpoint, which is /api/2.1/jobs/runs/get. In the request, we will also include the job run ID obtained from the response of the <strong>Trigger Job Run</strong> API request as a query parameter.</li></ul><pre>@concat(<br>    pipeline().parameters.DatabricksHostName,<br>    &#39;/api/2.1/jobs/runs/get?run_id=&#39;,<br>    activity(&#39;Trigger Job Run&#39;).output.run_id<br>)</pre><ul><li><strong>Method</strong>: Set the method to <strong>GET</strong>, as this is a retrieval request for the job run status.</li><li><strong>Authentication</strong>: Use the same authentication method as specified in the <strong>Trigger Job Run</strong> request.</li><li><strong>Resource</strong>: This should also match the resource used in the <strong>Trigger Job Run</strong> request.</li><li><strong>Integration Runtime</strong>: Select an Integration Runtime that has the necessary access to the Databricks resource, ensuring that the API call can be executed successfully without any permission issues.</li></ul><h4>3. Fail the ADF pipeline if the Databricks job fails</h4><p>We will utilize an <strong>If Condition</strong> activity to terminate the pipeline if the job run fails. The <strong>Until</strong> activity will complete once the job run is finished, at which point the status of the job run (either Success or Fail) will be stored in a pipeline variable.</p><p>If the job run status is not <strong>Success</strong>, the inner <strong>Fail</strong> activity will be triggered. Executing this <strong>Fail</strong> activity will result in the failure of the ADF pipeline, allowing for proper error handling and notification based on the job’s outcome.</p><figure><img alt="If Condition activity to Fail the pipeline" src="https://cdn-images-1.medium.com/max/263/1*rxSnN1NDU_ZbsClX5eUS3g.png" /><figcaption>If Condition activity to Fail the pipeline</figcaption></figure><h3>Pipeline Code</h3><pre>{<br>    &quot;name&quot;: &quot;PL_Trigger_Track_Databricks_Job&quot;,<br>    &quot;properties&quot;: {<br>        &quot;description&quot;: &quot;Pipeline to trigger and track Databricks Job Run&quot;,<br>        &quot;activities&quot;: [<br>            {<br>                &quot;name&quot;: &quot;Wait Until Job Completes&quot;,<br>                &quot;description&quot;: &quot;Check job status in loop&quot;,<br>                &quot;type&quot;: &quot;Until&quot;,<br>                &quot;dependsOn&quot;: [<br>                    {<br>                        &quot;activity&quot;: &quot;Trigger Job Run&quot;,<br>                        &quot;dependencyConditions&quot;: [<br>                            &quot;Succeeded&quot;<br>                        ]<br>                    }<br>                ],<br>                &quot;userProperties&quot;: [],<br>                &quot;typeProperties&quot;: {<br>                    &quot;expression&quot;: {<br>                        &quot;value&quot;: &quot;@not(equals(variables(&#39;JobStatus&#39;),&#39;Running&#39;))&quot;,<br>                        &quot;type&quot;: &quot;Expression&quot;<br>                    },<br>                    &quot;activities&quot;: [<br>                        {<br>                            &quot;name&quot;: &quot;Check Job Run Status&quot;,<br>                            &quot;description&quot;: &quot;Check status of the Job run using Databricks Job API&quot;,<br>                            &quot;type&quot;: &quot;WebActivity&quot;,<br>                            &quot;dependsOn&quot;: [<br>                                {<br>                                    &quot;activity&quot;: &quot;Sleep task&quot;,<br>                                    &quot;dependencyConditions&quot;: [<br>                                        &quot;Succeeded&quot;<br>                                    ]<br>                                }<br>                            ],<br>                            &quot;policy&quot;: {<br>                                &quot;timeout&quot;: &quot;0.00:30:00&quot;,<br>                                &quot;retry&quot;: 3,<br>                                &quot;retryIntervalInSeconds&quot;: 30,<br>                                &quot;secureOutput&quot;: false,<br>                                &quot;secureInput&quot;: false<br>                            },<br>                            &quot;userProperties&quot;: [],<br>                            &quot;typeProperties&quot;: {<br>                                &quot;method&quot;: &quot;GET&quot;,<br>                                &quot;url&quot;: {<br>                                    &quot;value&quot;: &quot;@concat(pipeline().parameters.DatabricksHostName,&#39;/api/2.1/jobs/runs/get?run_id=&#39;,activity(&#39;Trigger Job Run&#39;).output.run_id)&quot;,<br>                                    &quot;type&quot;: &quot;Expression&quot;<br>                                },<br>                                &quot;connectVia&quot;: {<br>                                    &quot;referenceName&quot;: &quot;ir-sh-xxxx&quot;,<br>                                    &quot;type&quot;: &quot;IntegrationRuntimeReference&quot;<br>                                },<br>                                &quot;authentication&quot;: {<br>                                    &quot;type&quot;: &quot;MSI&quot;,<br>                                    &quot;resource&quot;: &quot;2ff814a6-3304-4ab8-85cb-cd0e6f879c1d&quot;<br>                                }<br>                            }<br>                        },<br>                        {<br>                            &quot;name&quot;: &quot;Set Job Run Status&quot;,<br>                            &quot;description&quot;: &quot;Set status of the Job run in a variable&quot;,<br>                            &quot;type&quot;: &quot;SetVariable&quot;,<br>                            &quot;dependsOn&quot;: [<br>                                {<br>                                    &quot;activity&quot;: &quot;Check Job Run Status&quot;,<br>                                    &quot;dependencyConditions&quot;: [<br>                                        &quot;Succeeded&quot;<br>                                    ]<br>                                }<br>                            ],<br>                            &quot;policy&quot;: {<br>                                &quot;secureOutput&quot;: false,<br>                                &quot;secureInput&quot;: false<br>                            },<br>                            &quot;userProperties&quot;: [],<br>                            &quot;typeProperties&quot;: {<br>                                &quot;variableName&quot;: &quot;JobStatus&quot;,<br>                                &quot;value&quot;: {<br>                                    &quot;value&quot;: &quot;@if(\nor(\nequals(activity(&#39;Check Job Run Status&#39;).output.state.life_cycle_state, &#39;PENDING&#39;), equals(activity(&#39;Check Job Run Status&#39;).output.state.life_cycle_state, &#39;RUNNING&#39;)\n),\n&#39;Running&#39;,\nactivity(&#39;Check Job Run Status&#39;).output.state.result_state\n)&quot;,<br>                                    &quot;type&quot;: &quot;Expression&quot;<br>                                }<br>                            }<br>                        },<br>                        {<br>                            &quot;name&quot;: &quot;Sleep task&quot;,<br>                            &quot;description&quot;: &quot;Sleep task&quot;,<br>                            &quot;type&quot;: &quot;Wait&quot;,<br>                            &quot;dependsOn&quot;: [],<br>                            &quot;userProperties&quot;: [],<br>                            &quot;typeProperties&quot;: {<br>                                &quot;waitTimeInSeconds&quot;: {<br>                                    &quot;value&quot;: &quot;@variables(&#39;WaitSeconds&#39;)&quot;,<br>                                    &quot;type&quot;: &quot;Expression&quot;<br>                                }<br>                            }<br>                        }<br>                    ],<br>                    &quot;timeout&quot;: &quot;0.12:00:00&quot;<br>                }<br>            },<br>            {<br>                &quot;name&quot;: &quot;Trigger Job Run&quot;,<br>                &quot;description&quot;: &quot;Trigger Databricks Job Run&quot;,<br>                &quot;type&quot;: &quot;WebActivity&quot;,<br>                &quot;dependsOn&quot;: [],<br>                &quot;policy&quot;: {<br>                    &quot;timeout&quot;: &quot;0.12:00:00&quot;,<br>                    &quot;retry&quot;: 3,<br>                    &quot;retryIntervalInSeconds&quot;: 30,<br>                    &quot;secureOutput&quot;: false,<br>                    &quot;secureInput&quot;: false<br>                },<br>                &quot;userProperties&quot;: [],<br>                &quot;typeProperties&quot;: {<br>                    &quot;method&quot;: &quot;POST&quot;,<br>                    &quot;headers&quot;: {<br>                        &quot;Content-Type&quot;: {<br>                            &quot;value&quot;: &quot;@variables(&#39;ContentType&#39;)&quot;,<br>                            &quot;type&quot;: &quot;Expression&quot;<br>                        }<br>                    },<br>                    &quot;url&quot;: {<br>                        &quot;value&quot;: &quot;@concat(\n    pipeline().parameters.DatabricksHostName,\n    &#39;/api/2.1/jobs/run-now&#39;\n)&quot;,<br>                        &quot;type&quot;: &quot;Expression&quot;<br>                    },<br>                    &quot;connectVia&quot;: {<br>                        &quot;referenceName&quot;: &quot;ir-sh-xxxx&quot;,<br>                        &quot;type&quot;: &quot;IntegrationRuntimeReference&quot;<br>                    },<br>                    &quot;body&quot;: {<br>                        &quot;value&quot;: &quot;{\n  \&quot;job_id\&quot;: \&quot;@{pipeline().parameters.DatabricksJobId}\&quot;,\n  \&quot;job_parameters\&quot;: {\n    \&quot;start_period_job\&quot;: \&quot;20240301\&quot;,\n    \&quot;end_period_job\&quot;: \&quot;20240331\&quot;\n  }\n}&quot;,<br>                        &quot;type&quot;: &quot;Expression&quot;<br>                    },<br>                    &quot;authentication&quot;: {<br>                        &quot;type&quot;: &quot;MSI&quot;,<br>                        &quot;resource&quot;: &quot;2ff814a6-3304-4ab8-85cb-cd0e6f879c1d&quot;<br>                    }<br>                }<br>            },<br>            {<br>                &quot;name&quot;: &quot;Check Final Job Status&quot;,<br>                &quot;description&quot;: &quot;Once job is complete check its final status to see if it failed&quot;,<br>                &quot;type&quot;: &quot;IfCondition&quot;,<br>                &quot;dependsOn&quot;: [<br>                    {<br>                        &quot;activity&quot;: &quot;Wait Until Job Completes&quot;,<br>                        &quot;dependencyConditions&quot;: [<br>                            &quot;Succeeded&quot;<br>                        ]<br>                    }<br>                ],<br>                &quot;userProperties&quot;: [],<br>                &quot;typeProperties&quot;: {<br>                    &quot;expression&quot;: {<br>                        &quot;value&quot;: &quot;@equals(variables(&#39;JobStatus&#39;) ,&#39;SUCCESS&#39;)&quot;,<br>                        &quot;type&quot;: &quot;Expression&quot;<br>                    },<br>                    &quot;ifFalseActivities&quot;: [<br>                        {<br>                            &quot;name&quot;: &quot;Fail Pipeline&quot;,<br>                            &quot;description&quot;: &quot;Fail the pipeline if job failed&quot;,<br>                            &quot;type&quot;: &quot;Fail&quot;,<br>                            &quot;dependsOn&quot;: [],<br>                            &quot;userProperties&quot;: [],<br>                            &quot;typeProperties&quot;: {<br>                                &quot;message&quot;: {<br>                                    &quot;value&quot;: &quot;@concat(&#39;Execution of the framework job failed. Job Run URL: &#39;, activity(&#39;Check Job Run Status&#39;).output.run_page_url)&quot;,<br>                                    &quot;type&quot;: &quot;Expression&quot;<br>                                },<br>                                &quot;errorCode&quot;: &quot;1&quot;<br>                            }<br>                        }<br>                    ]<br>                }<br>            }<br>        ],<br>        &quot;parameters&quot;: {<br>            &quot;DatabricksHostName&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;defaultValue&quot;: &quot;https://adb-xxx.azuredatabricks.net&quot;<br>            },<br>            &quot;DatabricksJobId&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;defaultValue&quot;: &quot;801xxxxxxx011920&quot;<br>            }<br>        },<br>        &quot;variables&quot;: {<br>            &quot;JobStatus&quot;: {<br>                &quot;type&quot;: &quot;String&quot;,<br>                &quot;defaultValue&quot;: &quot;Running&quot;<br>            },<br>            &quot;ContentType&quot;: {<br>                &quot;type&quot;: &quot;String&quot;,<br>                &quot;defaultValue&quot;: &quot;application/json&quot;<br>            },<br>            &quot;WaitSeconds&quot;: {<br>                &quot;type&quot;: &quot;Integer&quot;,<br>                &quot;defaultValue&quot;: 30<br>            }<br>        },<br>        &quot;folder&quot;: {<br>            &quot;name&quot;: &quot;Databricks&quot;<br>        },<br>        &quot;annotations&quot;: [],<br>        &quot;lastPublishTime&quot;: &quot;2024-09-24T15:31:59Z&quot;<br>    },<br>    &quot;type&quot;: &quot;Microsoft.DataFactory/factories/pipelines&quot;<br>}</pre><h3>Conclusion</h3><p>Integrating Azure Data Factory (ADF) with Databricks enables efficient orchestration of data workflows by allowing users to trigger and monitor job runs seamlessly. By utilizing the Databricks REST API, we can easily initiate jobs and track their progress in real-time. Through the implementation of various ADF activities, such as the <strong>Until</strong> and <strong>If Condition</strong> activities, we can ensure that our pipelines handle job statuses effectively, allowing for proper error management and ensuring data processing reliability. This approach not only enhances the flexibility of data pipelines but also streamlines data processing tasks, making it easier to manage and scale analytics workloads.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>Reference</h3><ul><li><a href="https://blog.det.life/why-would-someone-execute-databricks-api-from-azure-data-factory-ffcf9e2e7990">Why Would Someone Execute Databricks API From Azure Data Factory?</a></li><li><a href="https://docs.databricks.com/api/azure/workspace/jobs">Databricks REST API reference</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd4207deda7" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/trigger-and-monitor-databricks-job-runs-from-azure-data-factory-9cd4207deda7">Trigger and Monitor Databricks Job Runs from Azure Data Factory</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Multiple Activities Be Executed in Parallel in Spark Rather Than Sequentially?]]></title>
            <link>https://blog.dataengineerthings.org/can-multiple-activities-be-executed-in-parallel-in-spark-rather-than-sequentially-e7e74861938f?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7e74861938f</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 14:06:05 GMT</pubDate>
            <atom:updated>2024-09-30T14:06:05.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scenarios Highlighting the Benefits of Executing Activities in Parallel in Spark, Along with Implementation Details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lScOvSoT1X7SIOLj" /><figcaption>Photo by <a href="https://unsplash.com/@bashton?utm_source=medium&amp;utm_medium=referral">Benjamin Ashton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While <a href="https://spark.apache.org/">Spark</a> is known for its ability to perform distributed computing, there are cases where we need to run multiple activities simultaneously. Typically, Spark will execute each activity in parallel (distributed computing), but sometimes we also want the activities themselves to run concurrently. <strong>This means multiple activities run in parallel (concurrently), and each activity executes its operations in parallel (distributed computing).</strong></p><p>For instance, let’s take a hypothetical example, suppose we need to copy data from the last 10 days, fetching the data for each day separately. This results in 10 activities. Normally, we would run these activities sequentially using a loop, tracking the completion status of each one individually.</p><p>In addition to this, there are <strong>other scenarios where multiple activities are required for a job</strong>:</p><ul><li><strong>Data processing jobs</strong> where we process different partitions of a dataset independently.</li><li><strong>ETL pipelines</strong> that need to extract data from multiple sources, transform it, and load it to different destinations in parallel.</li><li><strong>Machine learning workflows</strong>, where we need to train different models on different data splits or parameter sets concurrently.</li></ul><p>Although each activity is distributed across different executors within the cluster and runs in parallel, the overall job only finishes once all activities are completed sequentially. In other words, each activity must be completed before the next one starts. <strong>If each date’s data ingestion takes an average of 3 minutes, the entire job would take about 30 minutes to finish.</strong></p><p>Is there a more efficient way to run these activities? Yes! <strong>By running them concurrently, we can significantly reduce the total time and complete the job faster.</strong> We will be using <a href="https://spark.apache.org/docs/latest/api/python/index.html">PySpark</a> for this. PySpark is the Python API for Apache Spark</p><h3>Requirements</h3><p>Here’s a breakdown of the goals we aim to accomplish:</p><ul><li>Execute multiple activities concurrently instead of sequentially.</li><li>Manage and control the number of activities running in parallel.</li><li>Monitor and log the status of each activity.</li><li>Ensure the job fails if any individual activity fails.</li><li>Minimize overall job execution time.</li></ul><h3>Parallel Processing Options in Python</h3><p>Python offers various options for parallel processing to optimize tasks that can be divided across multiple processors or threads. Below are some of the key libraries and techniques:</p><ul><li><strong>multiprocessing Module</strong>: Enables parallelism by creating multiple processes, each with its own memory space.</li><li><strong>threading Module</strong>: Ideal for I/O-bound tasks, utilizing threads to run tasks concurrently within the same memory space.</li><li><strong>concurrent.futures Module</strong>: Provides high-level interfaces for managing threads and processes, simplifying parallel execution.</li><li><strong>asyncio for Asynchronous I/O</strong>: Facilitates concurrency for I/O-bound tasks using asynchronous programming techniques.</li><li><strong>joblib Package</strong>: Efficient library for parallelizing loops and tasks, especially useful in machine learning and data processing.</li></ul><h3>Best Approach</h3><h4>Using ThreadPool from the multiprocessing.pool module</h4><p>The ThreadPool class from the multiprocessing.pool module in Python is a tool used to manage a pool of worker threads to execute tasks concurrently. It allows you to parallelize tasks that are I/O-bound by leveraging multiple threads, which can work on multiple tasks simultaneously without blocking the main program.</p><h4>Key Features of ThreadPool:</h4><ul><li><strong>Thread-based Parallelism</strong>: Unlike multiprocessing.Pool, which uses processes, ThreadPool uses threads, sharing the same memory space. It’s ideal for I/O-bound tasks (e.g., network requests, file I/O) but not suitable for CPU-bound tasks due to Python’s Global Interpreter Lock (GIL).</li><li><strong>Efficient Task Execution</strong>: ThreadPool allows you to execute functions in parallel across a fixed number of threads, reducing the overhead of creating new threads repeatedly.</li><li><strong>Thread Management</strong>: You can define the number of threads in the pool, and it will distribute tasks to them. Once a task is finished, the thread becomes available to process the next one.</li></ul><h4>Common Methods in ThreadPool:</h4><ol><li><strong>apply()</strong>: Calls the function passed to it and blocks until the result is available.</li><li><strong>apply_async()</strong>: Calls the function asynchronously and allows other tasks to be executed while waiting for the result.</li><li><strong>map()</strong>: Maps the function to an iterable, distributing the elements across threads.</li><li><strong>map_async()</strong>: The asynchronous version of map(), which does not block the execution of other code.</li><li><strong>close()</strong>: Prevents any more tasks from being submitted to the pool.</li><li><strong>join()</strong>: Ensures that all threads finish executing before proceeding.</li></ol><h3>Implementation</h3><p>The following example demonstrates how to parallelize an ingestion activity, but the same logic can be applied to any other Spark operation.</p><pre>import sys<br>import traceback<br>import logging<br>from multiprocessing.pool import ThreadPool<br><br># Configure the logging<br>logging.basicConfig(level=logging.DEBUG)<br><br># Create a logger<br>logger = logging.getLogger(&#39;Ingest Data&#39;)<br><br># Here we have example of Data Ingestion but this function can perform any Spark operation<br>def ingest_data(<br>    table_name: str,<br>    partition_column: str,<br>    partition_date: str<br>) -&gt; (str, str):<br>    &quot;&quot;&quot;<br>    Function to ingest data of a passed partition date from the source using Spark<br>        @Param table_name (str) - Table name<br>        @Param: partition_column (str): Name of the partition column<br>        @Param: partition_date(str): Partition date to be ingested<br>        @return: (str, str): Table name, Partition date<br>    &quot;&quot;&quot;<br>    <br>    # Call log message<br>    logger.info(f&quot;Ingesting Data table_name={table_name} partition_date={partition_date}&quot;)<br><br>    ###################################################################<br>    #<br>    # Implement Spark data ingestion or anyother Spark operation here<br>    # as per your project requirement<br>    #<br>    ###################################################################<br>    <br>    # Call log message<br>    logger.info(f&quot;Ingested Data table_name={table_name} partition_date={partition_date}&quot;)<br><br>    return table_name, partition_date<br><br># Initialize variables for parallel ingestion threads<br>ingestion_threads = {}<br>ingestion_exceptions = []<br>ingestion_exception_msg = &quot;&quot;<br><br># Control number of parallel ingestion<br>max_parallel_ingestion=3<br><br># Set Thread Pool based on value of max_parallel_ingestion param<br>pool = ThreadPool(processes=max_parallel_ingestion)<br>logger.info(f&quot;Number of parallel ingestion: {str(max_parallel_ingestion)}&quot;)<br><br># Define partition dates to be ingested<br>partition_dates = [&quot;2024-01-01&quot;, &quot;2024-01-02&quot;, &quot;2024-01-03&quot;, &quot;2024-01-04&quot;, &quot;2024-01-05&quot;, &quot;2024-01-06&quot;, &quot;2024-01-07&quot;, &quot;2024-01-08&quot;, &quot;2024-01-09&quot;, &quot;2024-01-10&quot;]<br><br># Define other variables for ingestion<br>table_name=&quot;Orders&quot;<br>partition_column=&quot;Order_Date&quot;<br><br># Loop through partitions and ingest partitions parallelly using Thread Pool<br>for partition_date in partition_dates:<br>    ingestion_args = (<br>        table_name,<br>        partition_column,<br>        partition_date<br>    )<br><br>    # Run ingest_data function asynchronously using ThreadPool<br>    ingestion_thread = pool.apply_async(ingest_data, ingestion_args)<br><br>    # Save passed arguments while creating ingestion thread<br>    ingestion_threads[ingestion_thread] = ingestion_args<br><br># Close Pool<br>pool.close()<br><br># Wait for all the pool threads to finish<br>pool.join()<br><br># Loop through each ingestion thread and check it&#39;s status and capture exceptions<br>logger.info(&quot;Ingestion process is complete, checking the execution status&quot;)<br>for ingestion_thread, ingestion_args in ingestion_threads.items():<br><br>    try:<br>        table_name, partition_date = ingestion_thread.get()<br>        logger.info(f&quot;Successfully ingested: table_name={table_name} partition_date={partition_date}&quot;)<br><br>    except Exception as exc:<br>        # Capture exception details<br>        ex_type, ex_value, _ = sys.exc_info()<br>        stack_trace = traceback.format_exc()<br><br>        ingestion_exception_msg += f&quot;\nException occurred for arguments:  table_name={ingestion_args[0]} partition_date={ingestion_args[1]}\n&quot;<br>        ingestion_exception_msg += f&quot;Exception type: {ex_type.__name__}\n&quot;<br>        ingestion_exception_msg += f&quot;Exception message: {ex_value}\n&quot;<br>        ingestion_exception_msg += f&quot;Stack_trace: {stack_trace}\n&quot;<br>        ingestion_exceptions.append(exc)<br><br># If any exception occurred during the ingestion then raise it<br>if len(ingestion_exceptions) &gt; 0:<br>    logger.error(ingestion_exception_msg)<br>    raise Exception(ingestion_exceptions)<br></pre><h3>Conclusion</h3><p>Executing multiple activities in parallel in Spark, rather than sequentially, can significantly reduce job execution time and improve overall efficiency. By leveraging the ThreadPool from the multiprocessing.pool module, we were able to implement a solution that not only allows for parallel execution but also provides control over the number of concurrent activities. This approach is especially beneficial for I/O-bound tasks, such as data ingestion, but can be adapted to any Spark operation that requires enhanced performance and scalability.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e74861938f" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/can-multiple-activities-be-executed-in-parallel-in-spark-rather-than-sequentially-e7e74861938f">Can Multiple Activities Be Executed in Parallel in Spark Rather Than Sequentially?</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never Make This Mistake When Overwriting a Spark Partition Table]]></title>
            <link>https://blog.dataengineerthings.org/never-make-this-mistake-when-overwriting-a-spark-partition-table-700a6c05f8f9?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/700a6c05f8f9</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 14:56:44 GMT</pubDate>
            <atom:updated>2024-09-25T14:56:44.623Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about partition overwrite modes to prevent costly mistakes that could lead to data loss</h4><h3>Introduction</h3><p>Choosing the wrong or default partition overwrite mode could result in a massive data loss, costing you significant time and resources to recover. Did you know there are two different modes when overwriting a <a href="https://spark.apache.org/">Spark</a> partition table? Understanding these can save you from a costly mistake.</p><p><em>Let’s explore the two modes for overwriting partitions:</em></p><h3><strong>1. Static Partition Overwrite Mode:</strong></h3><ul><li>In Static mode, Spark replaces all partitions with the new data when overwriting.</li><li>This means that all existing data in the partitions will be deleted, even if the new data only pertains to some of those partitions.</li><li>By <strong>default</strong>, the Static partition overwrite mode is applied if no specific mode is mentioned for partition overwrite.</li><li>Suppose you have a table partitioned by year and month, with data for each month of 2023 from January to December. If you want to reprocess the data for December 2023 then using the Static partition overwrite mode would delete all the existing partitions. The table would only contain data for December 2023 after the overwrite.</li></ul><h3><strong>2. Dynamic Partition Overwrite Mode</strong></h3><ul><li>In Dynamic mode, Spark overwrites only the partitions corresponding to the incoming data, leaving the other partitions unaffected.</li><li>This mode is useful when you want to overwrite specific partitions while keeping the rest intact.</li><li>Consider the same table partitioned by year and month, with data for all 12 months of 2023. If you reprocess data for December 2023 and use the dynamic partition overwrite mode, only the data for December will be replaced, while the data for January to November remains unchanged.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j1eIuppJqXahMfV4" /><figcaption>Photo by <a href="https://unsplash.com/@elisa_ventur?utm_source=medium&amp;utm_medium=referral">Elisa Ventur</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Example</h3><h4>Prepare Table and Data</h4><p><strong>1. Create a Partition Table</strong></p><p>Create a partitioned table named <strong>Orders</strong> with the partition columns <strong>Order_Year</strong> and <strong>Order_Month</strong></p><pre>CREATE TABLE test.Orders<br>(<br>  Order_ID INT,<br>  Customer_ID INT,<br>  Order_Amount DECIMAL(10, 2),<br>  Order_Year INT,<br>  Order_Month INT,<br>  Order_Day INT<br>)<br>PARTITIONED BY (Order_Year, Order_Month);</pre><p><strong>2. Insert Sample Records</strong></p><p>Insert 5 records for each month of the year 2023</p><pre>INSERT INTO test.Orders<br>VALUES<br><br>-- Jan 2023<br>(1, 101, 250.50, 2023, 1, 15),<br>(2, 102, 300.75, 2023, 1, 22),<br>(3, 103, 450.00, 2023, 1, 10),<br>(4, 104, 120.00, 2023, 1, 5),<br>(5, 105, 99.99, 2023, 1, 28),<br><br>-- Feb 2023<br>(6, 106, 200.00, 2023, 2, 7),<br>(7, 107, 320.50, 2023, 2, 13),<br>(8, 108, 210.00, 2023, 2, 24),<br>(9, 109, 150.75, 2023, 2, 16),<br>(10, 110, 425.90, 2023, 2, 28),<br><br>-- Mar 2023<br>(11, 111, 275.00, 2023, 3, 5),<br>(12, 112, 340.75, 2023, 3, 12),<br>(13, 113, 410.20, 2023, 3, 20),<br>(14, 114, 600.50, 2023, 3, 25),<br>(15, 115, 250.30, 2023, 3, 30),<br><br>-- Apr 2023<br>(16, 116, 195.00, 2023, 4, 1),<br>(17, 117, 305.75, 2023, 4, 11),<br>(18, 118, 400.40, 2023, 4, 19),<br>(19, 119, 525.80, 2023, 4, 23),<br>(20, 120, 149.99, 2023, 4, 29),<br><br>-- May 2023<br>(21, 121, 310.50, 2023, 5, 6),<br>(22, 122, 410.75, 2023, 5, 15),<br>(23, 123, 230.20, 2023, 5, 18),<br>(24, 124, 355.90, 2023, 5, 21),<br>(25, 125, 199.00, 2023, 5, 27),<br><br>-- Jun 2023<br>(26, 126, 250.50, 2023, 6, 3),<br>(27, 127, 300.75, 2023, 6, 10),<br>(28, 128, 450.00, 2023, 6, 15),<br>(29, 129, 120.00, 2023, 6, 18),<br>(30, 130, 99.99, 2023, 6, 24),<br><br>-- Jul 2023<br>(31, 131, 275.00, 2023, 7, 2),<br>(32, 132, 340.75, 2023, 7, 9),<br>(33, 133, 410.20, 2023, 7, 14),<br>(34, 134, 600.50, 2023, 7, 21),<br>(35, 135, 250.30, 2023, 7, 28),<br><br>-- Aug 2023<br>(36, 136, 295.00, 2023, 8, 4),<br>(37, 137, 420.75, 2023, 8, 12),<br>(38, 138, 410.60, 2023, 8, 18),<br>(39, 139, 500.90, 2023, 8, 23),<br>(40, 140, 189.50, 2023, 8, 29),<br><br>-- Sep 2023<br>(41, 141, 230.00, 2023, 9, 1),<br>(42, 142, 380.75, 2023, 9, 9),<br>(43, 143, 460.80, 2023, 9, 17),<br>(44, 144, 515.90, 2023, 9, 24),<br>(45, 145, 255.00, 2023, 9, 30),<br><br>-- Oct 2023<br>(46, 146, 275.40, 2023, 10, 4),<br>(47, 147, 365.50, 2023, 10, 13),<br>(48, 148, 510.00, 2023, 10, 19),<br>(49, 149, 605.90, 2023, 10, 24),<br>(50, 150, 299.99, 2023, 10, 29),<br><br>-- Nov 2023<br>(51, 151, 270.50, 2023, 11, 3),<br>(52, 152, 380.75, 2023, 11, 14),<br>(53, 153, 455.00, 2023, 11, 18),<br>(54, 154, 505.80, 2023, 11, 22),<br>(55, 155, 150.00, 2023, 11, 27),<br><br>-- Dec 2023<br>(56, 156, 260.50, 2023, 12, 2),<br>(57, 157, 370.75, 2023, 12, 8),<br>(58, 158, 425.00, 2023, 12, 17),<br>(59, 159, 575.90, 2023, 12, 23),<br>(60, 160, 120.99, 2023, 12, 30);</pre><p><strong>3. Query the Table for Sample Records</strong></p><p>Query the <strong>Orders</strong> table to retrieve the record count for each month of 2023</p><pre>select Order_Year, Order_Month, count(*) as `Record Count` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="Retrieve the Record Count" src="https://cdn-images-1.medium.com/max/476/1*Ogb1ADWpoefG-goZk5gPHQ.png" /><figcaption>Retrieve the Record Count</figcaption></figure><p>Query the <strong>Orders</strong> table to calculate the total order amount for each month of 2023</p><pre>select Order_Year, Order_Month, sum(Order_Amount) as `Sum of Order Amount` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="Retrieve the Sum of Order Amount" src="https://cdn-images-1.medium.com/max/528/1*ve31Mli5Gua6-j8rZ-7BRQ.png" /><figcaption>Retrieve the Sum of Order Amount</figcaption></figure><p><strong>4. Prepare New Data</strong></p><p>Assume we have received new data for December 2023</p><pre>from pyspark.sql.types import StructType, StructField, IntegerType, DecimalType, DateType<br>from decimal import Decimal<br><br># Define the schema<br>schema = StructType([<br>    StructField(&quot;Order_ID&quot;, IntegerType(), True),<br>    StructField(&quot;Customer_ID&quot;, IntegerType(), True),<br>    StructField(&quot;Order_Amount&quot;, DecimalType(10, 2), True),<br>    StructField(&quot;Order_Year&quot;, IntegerType(), True),<br>    StructField(&quot;Order_Month&quot;, IntegerType(), True),<br>    StructField(&quot;Order_Day&quot;, IntegerType(), True)<br>])<br><br># 6 new records for December 2023<br>data = [<br>    (61, 161, Decimal(&#39;299.99&#39;), 2023, 12, 3),<br>    (62, 162, Decimal(&#39;459.50&#39;), 2023, 12, 9),<br>    (63, 163, Decimal(&#39;210.00&#39;), 2023, 12, 15),<br>    (64, 164, Decimal(&#39;600.25&#39;), 2023, 12, 20),<br>    (65, 165, Decimal(&#39;189.99&#39;), 2023, 12, 25),<br>    (66, 166, Decimal(&#39;325.75&#39;), 2023, 12, 31)<br>]<br><br># Create DataFrame<br>df = spark.createDataFrame(data, schema)<br><br># Show the DataFrame<br>display(df)</pre><figure><img alt="New data for December 2023" src="https://cdn-images-1.medium.com/max/915/1*B-vj-S8TJfVLTK6H9p86rg.png" /><figcaption>New data for December 2023</figcaption></figure><h4>Static Mode</h4><ol><li><strong>Overwrite the Table in Static Mode</strong></li></ol><p>Write the DataFrame to the <strong>Orders</strong> table using Static Partition Overwrite mode</p><pre>df.write \<br>  .mode(&quot;overwrite&quot;) \<br>  .format(&quot;delta&quot;) \<br>  .option(&quot;partitionOverwriteMode&quot;, &quot;static&quot;) \<br>  .insertInto(&quot;test.Orders&quot;)<br><br># It&#39;s fine not to specify the Partition Overwrite Mode, <br># as Static is the default mode.</pre><p><strong>2. Query the Table After Static Overwrite</strong></p><p>Query the <strong>Orders</strong> table to retrieve the record count for each month of 2023 after Static Overwrite</p><pre>select Order_Year, Order_Month, count(*) as `Record Count` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="Retrieve the Record Count" src="https://cdn-images-1.medium.com/max/470/1*R3LoUCeKbLjLBlTSMy3S4g.png" /><figcaption>Retrieve the Record Count</figcaption></figure><p>Query the <strong>Orders</strong> table to calculate the total order amount for each month of 2023 after Static Overwrite</p><pre>select Order_Year, Order_Month, sum(Order_Amount) as `Sum of Order Amount` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="Retrieve the Sum of Order Amount" src="https://cdn-images-1.medium.com/max/525/1*q8n-_g4ZnADCvpKXs85nLg.png" /><figcaption>Retrieve the Sum of Order Amount</figcaption></figure><h4>Dynamic Mode</h4><p><strong>1. Overwrite the Table in Dynamic Mode</strong></p><p>The <strong>Orders</strong> table contains 5 records for each month of 2023, after which we write the DataFrame to the table using <strong>Dynamic </strong>Partition Overwrite mode.</p><pre>df.write \<br>  .mode(&quot;overwrite&quot;) \<br>  .format(&quot;delta&quot;) \<br>  .option(&quot;partitionOverwriteMode&quot;, &quot;dynamic&quot;) \<br>  .insertInto(&quot;test.Orders&quot;)</pre><p><strong>2. Query the Table After Dynamic Overwrite</strong></p><p>Query the <strong>Orders</strong> table to retrieve the record count for each month of 2023 after Dynamic Overwrite</p><pre>select Order_Year, Order_Month, count(*) as `Record Count` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="Retrieve the Record Count" src="https://cdn-images-1.medium.com/max/532/1*fJoTWOA975FfRWLyXFTncw.png" /><figcaption>Retrieve the Record Count</figcaption></figure><p>Query the <strong>Orders</strong> table to calculate the total order amount for each month of 2023 after Dynamic Overwrite</p><pre>select Order_Year, Order_Month, sum(Order_Amount) as `Sum of Order Amount` from test.Orders<br>group by Order_Year, Order_Month<br>order by Order_Year, Order_Month</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*mGQI6UPDd4nND6aaUI3lhg.png" /></figure><h3>Configuration</h3><p>Let’s explore different ways to set the Partition Overwrite property:</p><p><strong>1. Python (Setting Spark Configuration):</strong></p><pre># Set partition overwrite mode to &#39;static&#39;<br>spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;, &quot;dynamic&quot;)<br><br># Write the DataFrame to the table with mode = &#39;Overwrite&#39;<br>df.write \<br>  .mode(&quot;overwrite&quot;) \<br>  .format(&quot;delta&quot;) \<br>  .insertInto(&quot;test.Orders&quot;)</pre><p><strong>2. Python (Setting DataFrame Write Option)</strong>:</p><pre>df.write \<br>  .mode(&quot;overwrite&quot;) \<br>  .format(&quot;delta&quot;) \<br>  .option(&quot;partitionOverwriteMode&quot;, &quot;dynamic&quot;) \<br>  .insertInto(&quot;test.Orders&quot;)</pre><p><strong>3. Using SQL</strong>:</p><pre>SET spark.sql.sources.partitionOverwriteMode=dynamic;<br>INSERT OVERWRITE TABLE test.Orders SELECT * FROM moreOrders;</pre><p><strong>4. Scala:</strong></p><pre>df.write<br>  .mode(&quot;overwrite&quot;)<br>  .option(&quot;partitionOverwriteMode&quot;, &quot;dynamic&quot;)<br>  .saveAsTable(&quot;default.people10m&quot;)</pre><h3>Conclusion</h3><p>Understanding and properly configuring partition overwrite modes in Spark is crucial to prevent costly mistakes, such as unintended data loss. The <strong>Static</strong> mode, being the default, ensures that all partitions are overwritten with new data, while the <strong>Dynamic</strong> mode allows greater flexibility by overwriting all matching partitions based on incoming data. Being aware of these modes and choosing the appropriate one for your use case will help you safeguard your data and avoid unnecessary complications in managing your partitioned tables.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/databricks/delta/selective-overwrite">Selectively overwrite data with Delta Lake - Azure Databricks</a></li><li><a href="https://spark.apache.org/docs/3.4.0/configuration.html#spark-sql">Spark Configuration</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=700a6c05f8f9" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/never-make-this-mistake-when-overwriting-a-spark-partition-table-700a6c05f8f9">Never Make This Mistake When Overwriting a Spark Partition Table</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Unique Ways to Create Spark DataFrames]]></title>
            <link>https://blog.dataengineerthings.org/12-unique-ways-to-create-spark-dataframes-094201df0dc0?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/094201df0dc0</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 14:55:28 GMT</pubDate>
            <atom:updated>2024-09-26T06:32:00.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>12 Unique Ways to Create Spark DataFrames (You Won’t Believe the 10th Option!)</h3><h4>Discover 12 Unique Ways to Create Spark DataFrames with Practical Examples and Insights.</h4><h3>Introduction</h3><p>Since you’re here, it’s safe to assume you’re familiar with <a href="https://spark.apache.org/">Spark</a> and Spark DataFrames. Spark offers extensive support for various file formats like CSV, JSON, Parquet, Delta, Avro, and more. It can also connect to multiple databases and includes robust SQL support. As a result, there are numerous ways to create a DataFrame from data.</p><p>In this blog, we’ll explore <strong>12 distinct ways to create a </strong><a href="https://spark.apache.org/docs/latest/api/python/index.html"><strong>PySpark</strong></a><strong> DataFrame</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z5t80zJ2PDtwXMGn" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Spark DataFrame</h3><p>A Spark DataFrame is a <strong>distributed collection of data</strong> organized into named columns, similar to a table in a relational database. It is built on Apache Spark and allows large-scale <strong>parallel data processing</strong> across multiple machines. Spark DataFrames offer <strong>powerful operations for data manipulation</strong>, including filtering, aggregating, and transforming data, while optimizing performance through lazy evaluation and Catalyst optimizer.</p><p>Let’s start exploring different ways to create Spark DataFrame.</p><h3>1. From RDD using toDF() function</h3><p>In the first two ways, we will be creating DataFrame from RDD. <strong>RDD (Resilient Distributed Dataset)</strong> is the fundamental data structure of Apache Spark, designed for fault-tolerant, distributed processing of large datasets across multiple nodes. An RDD is an immutable collection of objects that can be processed in parallel.</p><p>The toDF() function in PySpark is a convenient method for converting an existing collection, such as an RDD or a list, into a DataFrame. This function is typically used to create DataFrames from data that is already in a Python format, allowing you to specify column names and types. By leveraging toDF(), you can seamlessly integrate data into Spark’s DataFrame API.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Define Data<br>data = [(&quot;Raj&quot;, 1800), (&quot;Priya&quot;, 2000), (&quot;Suresh&quot;, 1500)]<br><br># Create RDD from the data<br>rdd = spark.sparkContext.parallelize(data)<br><br># Create DF from RDD without schema<br>df1 = rdd.toDF()<br>df1.show()<br><br># Create DF from RDD with column names<br>columns = [&quot;Name&quot;, &quot;Salary&quot;]<br>df2 = rdd.toDF(columns)<br>df2.show()</pre><h3>2. From RDD using createDataFrame() function</h3><p>The createDataFrame() function in PySpark is used to convert various types of data structures into a Spark DataFrame. This function is highly versatile, allowing you to create DataFrames from a variety of sources, such as lists, pandas DataFrames, RDDs, and structured data formats. By specifying the schema or letting Spark infer it, createDataFrame() provides a straightforward way to bring data into Spark’s DataFrame API, facilitating efficient data processing and analysis.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType<br> <br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br> <br># Define Data<br>data = [(&quot;Raj&quot;, 1800), (&quot;Priya&quot;, 2000), (&quot;Suresh&quot;, 1500)]<br> <br># Create RDD from the data<br>rdd = spark.sparkContext.parallelize(data)<br> <br># Create DF from RDD without schema<br>df1= spark.createDataFrame(rdd)<br>df1.show()<br> <br># Create DF from RDD with column names<br>columns = [&quot;Name&quot;, &quot;Salary&quot;]<br>df2 = spark.createDataFrame(rdd).toDF(*columns)<br>df2.show()<br> <br># Create DF from RDD with schema<br>schema = StructType([<br>    StructField(&quot;Name&quot;, StringType(), True),<br>    StructField(&quot;Salary&quot;, IntegerType(), True)<br>])<br>df3 = spark.createDataFrame(rdd, schema)<br>df3.show()</pre><h3>3. From List</h3><pre># Import required modules<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Define Data<br>data = [<br>    (&#39;Robert  Williams&#39;, &#39;42114&#39;, &#39;M&#39;, 4000),<br>    (&#39;James  Smith&#39;, &#39;36636&#39;, &#39;M&#39;, 3000),<br>    (&#39;Maria Anne Jones&#39;, &#39;39192&#39;, &#39;F&#39;, 4000),<br>    (&#39;Michael Rose&#39;, &#39;40288&#39;, &#39;M&#39;, 4000)<br>]<br><br># Create DF from List without schema<br>df1 = spark.createDataFrame(data=data)<br>df1.show()<br><br># Create DF from List with column names<br>columns = [&quot;Name&quot;,&quot;Employee_ID&quot;, &quot;Gender&quot;, &quot;Salary&quot;]<br>df2 = spark.createDataFrame(data=data,schema=columns)<br>df2.show()<br><br># Define Schema<br>schema = StructType([ \<br>    StructField(&quot;Name&quot;,StringType(),True), \<br>    StructField(&quot;Employee_ID&quot;, StringType(), True), \<br>    StructField(&quot;Gender&quot;, StringType(), True), \<br>    StructField(&quot;Salary&quot;, IntegerType(), True) \<br>  ])<br><br># Create DF from List with schema<br>df3 = spark.createDataFrame(data=data,schema=schema)<br>df3.show()</pre><h3>4. From Rows</h3><p>In PySpark, a <strong>Row</strong> is a fundamental data structure that represents a single record in a DataFrame. It is similar to a named tuple, allowing you to access fields either by position or by name. Rows are used to store data in Spark SQL and help create structured data within a DataFrame. You can manually create Rows using Row() and they are often used when building DataFrames from lists or RDDs, making them an essential part of PySpark&#39;s data handling and processing capabilities.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br>from pyspark.sql import Row<br>from datetime import date, datetime<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType, DateType, TimestampType<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Define Data Rows<br>data = [ <br>    Row(a=1, b=4., c=&#39;GFG1&#39;, d=date(2000, 8, 1), <br>        e=datetime(2000, 8, 1, 12, 0)), <br>    <br>    Row(a=2, b=8., c=&#39;GFG2&#39;, d=date(2000, 6, 2),  <br>        e=datetime(2000, 6, 2, 12, 0)), <br>    <br>    Row(a=4, b=5., c=&#39;GFG3&#39;, d=date(2000, 5, 3), <br>        e=datetime(2000, 5, 3, 12, 0)) <br>]<br><br># Create DF from Rows with column names<br>df1 = spark.createDataFrame(data=data)<br>df1.show()<br><br># Define Schema<br>schema = StructType([ \<br>    StructField(&quot;a&quot;, IntegerType(),True), \<br>    StructField(&quot;b&quot;, DoubleType(), True), \<br>    StructField(&quot;c&quot;, StringType(), True), \<br>    StructField(&quot;d&quot;, DateType(), True), \<br>    StructField(&quot;e&quot;, TimestampType(), True) \<br>  ])<br><br># Create DF from Rows with schema<br>df2 = spark.createDataFrame(data=data,schema=schema)<br>df2.show()</pre><h3>5. From Dictionary</h3><pre># Import required modules<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType, DateType, TimestampType<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Define Data<br>data = {&quot;John&quot;: 100, &quot;Doe&quot;: 200, &quot;Jane&quot;: 300, &quot;Jose&quot;: 400}<br><br># Create DF from Dictionary<br>df1 = spark.createDataFrame(list(data.items()))<br>df1.show()<br><br># Define Schema<br>schema = StructType([ \<br>    StructField(&quot;name&quot;, StringType(), True), \<br>    StructField(&quot;id&quot;, StringType(),True) \<br>    <br>  ])<br><br># Create DF from Dictionary with schema<br>df2 = spark.createDataFrame(data=list(data.items()),schema=schema)<br>df2.show()</pre><h3>6. From Data sources (CSV, Text, JSON, XML, Parquet, etc.)</h3><p>In PySpark, the spark.read.fileformat() method is a flexible way to load data from various file formats into a DataFrame. The spark.read.csv() function in PySpark is used to load CSV (Comma-Separated Values) files into a DataFrame.</p><p>Similar to spark.read.csv(), it supports reading from formats such as JSON, Parquet, Avro, ORC, and more. Each method (e.g., spark.read.json(), spark.read.parquet()) allows you to specify options for schema inference, data parsing, and file handling.</p><p>This functionality enables easy integration of different data formats into Spark&#39;s DataFrame API, supporting diverse big data workflows across various file systems like HDFS, S3, or local storage.</p><p>Each file format offers various options for reading data. You can explore the full list of available options <a href="https://spark.apache.org/docs/latest/sql-data-sources.html">here</a>.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Reading a CSV file with custom options using the .options() method<br>df = spark.read.options(<br>    sep=&quot;;&quot;,           # Specify delimiter<br>    inferSchema=True,  # Infer the schema automatically<br>    header=True        # Use the first row as header<br>).csv(&quot;path/to/file.csv&quot;)  # Replace with your file path<br><br>df.show()<br><br># Similarly, we have can read json file using below command<br>df2 = spark.read.json(&quot;/src/resources/file.json&quot;)<br>df2.show()<br><br><br># Parquet files can be read using below command<br>df3 = spark.read.parquet(&quot;/src/resources/&quot;)<br>df3.show()<br><br># In a similar way, we can read files from all other supported formats, <br># such as XML, text, Avro, Delta, and others. <br># Each format has its own set of options that can be configured <br># for reading the data efficiently.</pre><h3>7. Using Pandas</h3><p>Pandas and Spark DataFrames both provide powerful tools for data manipulation but differ significantly in their capabilities and use cases.</p><p><strong>Pandas DataFrame</strong> is designed for in-memory data processing, making it ideal for small to medium-sized datasets that fit on a single machine. It provides a rich API for data analysis but struggles with large-scale or distributed data.</p><p><strong>Spark DataFrame</strong>, on the other hand, is built for distributed, large-scale data processing across multiple machines. It can handle much larger datasets and is optimized for big data workflows, though its API is slightly less flexible than Pandas for small-scale tasks.</p><p>In summary, Pandas is best for single-machine, in-memory operations, while Spark excels at the distributed processing of massive datasets.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType, DateType, TimestampType<br>from datetime import date, datetime<br>import pandas as pd<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Create Pandas DataFrame<br>pandas_df = pd.DataFrame({ <br>    &#39;a&#39;: [1, 2, 3], <br>    &#39;b&#39;: [4., 8., 5.], <br>    &#39;c&#39;: [&#39;GFG1&#39;, &#39;GFG2&#39;, &#39;GFG3&#39;], <br>    &#39;d&#39;: [date(2000, 8, 1), date(2000, 6, 2), <br>          date(2000, 5, 3)], <br>    &#39;e&#39;: [datetime(2000, 8, 1, 12, 0),  <br>          datetime(2000, 6, 2, 12, 0),  <br>          datetime(2000, 5, 3, 12, 0)] <br>}) <br>  <br># Create Spark DataFrame from Pandas DataFrame with column names<br>df1 = spark.createDataFrame(pandas_df)<br>df1.show()<br><br># Define Schema<br>schema = StructType([ \<br>    StructField(&quot;a&quot;, IntegerType(),True), \<br>    StructField(&quot;b&quot;, DoubleType(), True), \<br>    StructField(&quot;c&quot;, StringType(), True), \<br>    StructField(&quot;d&quot;, DateType(), True), \<br>    StructField(&quot;e&quot;, TimestampType(), True) \<br>  ])<br><br># Create Spark DataFrame from Pandas DataFrame with schema<br>df2 = spark.createDataFrame(data=pandas_df,schema=schema)<br>df2.show()</pre><h3>8. From an RDBMS Database using a JDBC Connector</h3><p>The spark.read.format(&quot;jdbc&quot;) method in Apache Spark is used to read data from a relational database using JDBC (Java Database Connectivity). This approach allows you to connect to various databases like MySQL, PostgreSQL, Oracle, or SQL Server and load data into a Spark DataFrame for processing.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Read MySQL data using JDBC Connector<br>df = spark.read\<br> .format(&#39;jdbc&#39;)\<br> .option(&#39;url&#39;, &#39;jdbc:mysql://localhost:3306/db&#39;)\<br> .option(&#39;driver&#39;, &#39;com.mysql.jdbc.Driver&#39;)\<br> .option(&#39;dbtable&#39;,&#39;new_table&#39;)\<br> .option(&#39;user&#39;,&#39;root&#39;)\<br> .load()<br><br>df.show()</pre><h3>9. Using Spark SQL with a query on a table</h3><p>In PySpark, you can create a DataFrame using the spark.sql() method by executing SQL queries on temporary views or tables registered with Spark. This approach allows you to leverage SQL syntax for data manipulation and querying within a Spark session.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Create DataFrame using SQL query<br>df = spark.sql(&quot;select * from table_name&quot;)<br>df.show()</pre><h3>10. Using Spark SQL with a query on data files</h3><p>In PySpark, you can query data directly from files using Spark SQL. Using SQL queries, you can easily interact with files stored in local or cloud storage systems.</p><blockquote><strong>Instead of relying solely on read APIs to load data files into a DataFrame, you can also query the files directly to create one. Surprisingly, this powerful feature is still underutilized by many.</strong></blockquote><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Create DataFrame using SQL query<br>df = spark.sql(&quot;SELECT * FROM parquet.`abfss://container@storage-account.dfs.core.windows.net/path/to/data`&quot;)<br>df.show()<br><br># In a similar way, we can read files from all other supported formats, <br># such as XML, text, Avro, Delta, and others.</pre><h3>11. Using Spark Table</h3><p>In PySpark, the spark.table() method allows you to create a DataFrame by referencing an existing table or view within your Spark session. This method is particularly useful when you have already registered a table or view in Spark SQL and want to access it as a DataFrame for further processing.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Create DataFrame from a existing Spark table<br>df = spark.table(&quot;table_name&quot;)<br>df.show()</pre><h3>12. Using Spark Range</h3><p>In PySpark, the spark.range() method is a convenient way to create a DataFrame with a range of integer values. This method is useful for generating sequential data quickly, which can be handy for testing, simulations, or as a starting point for more complex data transformations.</p><pre># Import required modules<br>from pyspark.sql import SparkSession<br><br># Create a Spark Session<br>spark = SparkSession.builder.appName(&#39;Exploration&#39;).getOrCreate()<br><br># Create DataFrame using range function<br>df = spark.range(start_range, end_range, increment)<br>df = spark.range(1, 100, 2)<br>df.show()</pre><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li></ul><h3>Conclusion</h3><p>Spark DataFrames offer immense flexibility for data processing, and knowing various methods to create them can significantly enhance your data engineering capabilities. Whether you’re loading data from files, querying SQL databases, or generating data programmatically, each approach has its advantages and use cases. By exploring these 12 methods, you’ve gained a broader understanding of how to harness Spark’s power to handle diverse data scenarios effectively. Keep experimenting with these techniques to find the best fit for your data workflows and continue to refine your Spark skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=094201df0dc0" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/12-unique-ways-to-create-spark-dataframes-094201df0dc0">12 Unique Ways to Create Spark DataFrames</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Looking to Enhance Your Data Quality? This is for You]]></title>
            <link>https://blog.dataengineerthings.org/looking-to-enhance-your-data-quality-this-is-for-you-a34c44ce117e?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34c44ce117e</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 18:09:26 GMT</pubDate>
            <atom:updated>2024-09-11T18:09:26.969Z</atom:updated>
            <content:encoded><![CDATA[<h4>Practical techniques to implement data verification and validation processes for your data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tsDk_dv49j9MzzlB" /><figcaption>Photo by <a href="https://unsplash.com/@silverkblack?utm_source=medium&amp;utm_medium=referral">Vitaly Gariev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In today’s data-driven world, data is undoubtedly one of the most valuable assets. However, having poor-quality data is often worse than having no data. Poor quality data can lead to misguided business decisions, which can significantly negatively impact operations, strategy, and customer satisfaction. For example, inaccurate customer data might result in ineffective marketing campaigns, and erroneous sales data could skew revenue forecasting. Therefore, ensuring high-quality data is critical, arguably even more so than merely collecting and using data.</p><p>In this blog, we’ll explore practical techniques to implement data verification and validation processes for your data by leveraging the powerful capabilities of the <a href="https://github.com/great-expectations/great_expectations"><strong>Great Expectations</strong></a> (GX) framework. By doing so, we can ensure that our data meets predefined quality standards, enabling more accurate and reliable business insights.</p><p>Before we delve into the specifics of Great Expectations (GX), let’s first get a grasp of the fundamentals.</p><h3>Table of Contents</h3><ol><li><a href="#5bc1">Basics</a><br> ∘ <a href="#1b80">Great Expectations</a><br> ∘ <a href="#fa15">Expectation</a></li><li><a href="#a4ec">Integration</a></li><li><a href="#cacd">GX Workflows</a></li><li><a href="#b2eb">Implementation</a><br> ∘ <a href="#034a">a. Pre-requisites</a><br> ∘ <a href="#489f">b. Set up a GX environment</a><br> ∘ <a href="#e3f1">c. Connect to Data</a><br> ∘ <a href="#1e52">d. Define Expectations</a><br> ∘ <a href="#b99f">e. Run Validations</a></li><li><a href="#14d0">End-to-End Code</a></li><li><a href="#9774">Reusing the configuration</a></li><li><a href="#662d">Data Docs</a></li><li><a href="#6d6d">Conclusion</a></li><li><a href="#4e4e">Reference</a></li></ol><h3>Basics</h3><h4>Great Expectations</h4><p>Great Expectations is an <strong>open-source</strong> data validation framework designed to define, test, and document the expectations for your data. It helps maintain data quality by ensuring that data meets specific criteria before it is processed or analyzed.</p><p>With Great Expectations, users can create rules (expectations) for their data, run validation tests, and <strong>generate comprehensive reports</strong> on data quality. The framework integrates seamlessly with a variety of data storage and processing tools, including SQL databases, Apache Spark, and Pandas, making it a versatile solution for different data environments.</p><h4>Expectation</h4><p>An expectation is essentially a declarative statement or assertion about the data, outlining how the data should look or behave. These expectations serve to validate the quality, consistency, and accuracy of the data. If the data fails to meet these expectations, it may indicate a potential issue that needs to be resolved.</p><p><strong>Examples:</strong></p><ul><li>expect_column_values_to_be_between: Ensures that all values in a specified column fall within a defined range.</li><li>expect_column_values_to_be_unique: Checks that all values in a column are unique.</li></ul><p>You can find a catalog of these Expectations in the <a href="https://greatexpectations.io/expectations/">Expectation Gallery</a>.</p><h3>Integration</h3><p>Great Expectations <strong>seamlessly integrates with a wide variety of tech stacks</strong>, making it a versatile choice for data quality management across different platforms.</p><p>Below are some of the most commonly used integrations:</p><ul><li><strong>Apache Airflow</strong>: Incorporate data quality checks directly into your data workflows.</li><li><strong>Amazon S3</strong>: Profile, validate, and document your file-based data.</li><li><strong>Databricks</strong>: Manage, check, and document data in your Lakehouse environment.</li><li><strong>Google Cloud Platform</strong>: Validate, profile, and document file-based data on GCP.</li><li><strong>Microsoft Azure Blob Storage</strong>: Validate, profile, and document file-based data on Azure.</li><li><strong>PostgreSQL</strong>: Profile, validate, and document your structured database data.</li><li><strong>Snowflake</strong>: Ensure data quality by profiling, validating, and documenting your data warehouse contents.</li></ul><p>In addition to the above, Great Expectations can be integrated with other platforms like Amazon Athena, AWS Glue, AWS Redshift, Google BigQuery, MySQL, Pandas, Apache Spark, SQLite, and many more. For a complete list of integrations, check out the official documentation <a href="https://greatexpectations.io/integrations">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LlOXCnMHwYV5Yo8Y" /><figcaption>Photo by <a href="https://unsplash.com/@tateisimikito?utm_source=medium&amp;utm_medium=referral">Jukan Tateisi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>GX Workflows</h3><p>GX Workflows refers to a series of processes and best practices within the Great Expectations (GX) framework that guide users through implementing and managing data quality checks. These workflows are designed to streamline the development, deployment, and monitoring of data validation activities, making it easier to ensure data quality consistently.</p><h4>GX workflow pattern</h4><figure><img alt="Great Expectations (GX) Workflow Steps" src="https://cdn-images-1.medium.com/max/940/1*XCV0H7hkS9mZVY3TYsd80Q.png" /><figcaption>Source <a href="https://greatexpectations.io/">https://greatexpectations.io/</a></figcaption></figure><p>All GX workflows follow a common pattern:</p><ol><li><strong>Set Up a GX Environment</strong>: Initialize and configure the Great Expectations environment.</li><li><strong>Connect to Data</strong>: Establish a connection to your data sources, whether they are databases, data lakes, or file-based data.</li><li><strong>Define Expectations</strong>: Create specific expectations that outline the criteria your data should meet.</li><li><strong>Run Validations</strong>: Validate your data against the defined expectations to check for quality, consistency, and accuracy.</li></ol><p>Different GX components are defined and utilized at each step of the workflow. This section introduces the key GX Core components necessary for building a comprehensive data validation workflow.</p><h3>Implementation</h3><h4>a. Pre-requisites</h4><p>Install the Great Expectations Python package and import the necessary modules. The code in this blog is compatible with <strong>version 1.0.0</strong> of the GX Python package.</p><pre># Install GX package<br>pip install great-expectations==1.0.0</pre><pre># Import modules<br>import great_expectations as gx</pre><h4>b. Set up a GX environment</h4><p>A Data Context manages the storage of metadata, including configurations for Data Sources, Expectation Suites, Checkpoints, and Data Docs. It also houses Validation Results and the associated metrics.</p><p>You can create <strong>any one type</strong> of Data Context:</p><ul><li><strong>File Data Context</strong>: A persistent Data Context that saves metadata and configuration information as YAML files. This type is useful for storing and reusing metadata and configurations related to expectations, allowing you to apply the same expectations to your data repeatedly. It is suitable for scenarios where you need to maintain persistent configurations.</li></ul><pre># Create a File Data Context<br>project_root_dir=&quot;/dbfs/FileStore/great_expectations/&quot;<br>context = gx.get_context(mode=&quot;file&quot;, project_root_dir=project_root_dir)</pre><ul><li><strong>Ephemeral Data Context</strong>: A temporary Data Context that holds metadata and configuration information in memory only for the duration of the current Python session. This means that metadata and configurations will not persist beyond the session, and you won’t be able to reuse them in future sessions. This type is ideal for one-time or transient data validation tasks.</li></ul><pre># Create an Ephemeral Data Context<br>project_root_dir = &quot;/dbfs/FileStore/great_expectations/&quot;<br>context = gx.get_context(mode=&quot;ephemeral&quot;)</pre><h4>c. Connect to Data</h4><ul><li><strong>Data Source</strong>: A Data Source in Great Expectations (GX) represents a connection to your data. It defines how GX should connect to various types of data stores, including databases, schemas, and data files in cloud object storage.</li><li><strong>Data Asset</strong>: A Data Asset is a collection of records within a Data Source. For example, if a Data Source is like a relational database, then a Data Asset can be thought of as a table within that database or the results from a query on a table.</li><li><strong>Batch Definition</strong>: A Batch Definition specifies how to organize the records within a Data Asset. It is a Python object that allows you to retrieve a Batch, or a collection of records from a Data Asset, for validation during runtime.</li><li><strong>Batch</strong>: A Data Asset can be validated as a single Batch or divided into multiple Batches, each of which can be validated separately.</li></ul><pre># Read data to be validated in a dataframe<br>df = spark.sql(&quot;select * from schema_name.table_name&quot;)<br><br># Create a Data Source<br>dataframe_datasource = context.data_sources.add_or_update_spark(name=&quot;gx_datasource&quot;)<br><br># Create a Data Asset<br>dataframe_asset = dataframe_datasource.add_dataframe_asset(name=&quot;test_df&quot;)<br><br># Create a Batch definition<br>batch_definition = dataframe_asset.add_batch_definition_whole_dataframe(name=&quot;gx_batch_definition&quot;)<br><br># Create Batch parameters<br>batch_parameters = {&quot;dataframe&quot;: df}</pre><h4>d. Define Expectations</h4><ul><li><strong>Expectation</strong>: An Expectation is a verifiable assertion about data, similar to assertions used in traditional Python unit tests. Expectations offer a flexible, declarative way to specify what qualities you expect from your data. They can be applied to validate a Batch of data.<br>For a comprehensive list of available Expectations, refer to the <a href="https://greatexpectations.io/expectations/">Expectation Gallery</a>.</li><li><strong>Expectation Suite</strong>: An Expectation Suite is a collection of Expectations. By grouping multiple Expectations, Expectation Suites allow you to validate a Batch of data against several criteria at once, making the validation process more efficient. You can create multiple Expectation Suites for the same data to address different scenarios, and the same Expectation Suite can be applied to different Batches.</li></ul><pre># Create an expectations suite<br>expectation_suite_name = &quot;gx_expectation_suite&quot;<br>expectation_suite = gx.ExpectationSuite(name=expectation_suite_name)<br>expectation_suite = context.suites.add(expectation_suite)<br> <br># Add expectation in the expectations suite<br>expectation_suite.add_expectation(<br>    gx.expectations.ExpectColumnMaxToBeBetween(<br>        column=&quot;RSIZPOINT&quot;, min_value=0, max_value=1000<br>    )<br>)<br> <br># Add one more expectation in the expectations suite<br>expectation_suite.add_expectation(<br>    gx.expectations.ExpectColumnValuesToNotBeNull(<br>        column=&quot;sap_metadata&quot;<br>    )<br>)</pre><h4>e. Run Validations</h4><ul><li><strong>Validation Definition</strong>: A Validation Definition explicitly associates a Batch Definition to an Expectation Suite, defining what data should be validated against which Expectations.</li><li><strong>Validation Result</strong>: A Validation Result is returned by GX after data validation. The Validation Results tell you how your data corresponds to what you expected of it.</li><li><strong>Checkpoint</strong>: A Checkpoint is the primary means for validating data in a production deployment of GX. Checkpoints enable you to run a list of Validation Definitions with shared parameters. Checkpoints can be configured to run Actions and can pass Validation Results to a list of predefined Actions for processing.</li><li><strong>Actions</strong>: Actions provide a mechanism to integrate Checkpoints into your data pipeline infrastructure by automatically processing Validation Results. Typical use cases include sending email alerts, Slack messages, or custom notifications based on the result of data validation.</li><li><strong>Data Docs</strong>: Data Docs are HTML documentation generated by GX that hosts your Expectation Suite definitions and Validation Results. Using Checkpoints and Actions, you can configure your GX workflow to automatically write Validation Results to a chosen Data Docs site.</li></ul><pre># Create a Validation Definition<br>definition_name = &quot;gx_validation_definition&quot;<br>validation_definition = gx.ValidationDefinition(<br>    data=batch_definition, suite=expectation_suite, name=definition_name<br>)<br>validation_definition = context.validation_definitions.add(validation_definition)<br><br># Create Data Docs Site Configuration<br>base_directory = f&quot;{project_root_dir}/gx/data_docs/local_site/&quot;<br>site_config = {<br>    &quot;class_name&quot;: &quot;SiteBuilder&quot;,<br>    &quot;site_index_builder&quot;: {&quot;class_name&quot;: &quot;DefaultSiteIndexBuilder&quot;},<br>    &quot;store_backend&quot;: {<br>        &quot;class_name&quot;: &quot;TupleFilesystemStoreBackend&quot;,<br>        &quot;base_directory&quot;: base_directory,<br>    },<br>}<br><br># Create a Data Docs Site<br>site_name = &quot;gx_data_docs_site&quot;<br>context.add_data_docs_site(site_name=site_name, site_config=site_config)<br><br># Create Checkpoint Actions<br>actions = [<br>    gx.checkpoint.actions.UpdateDataDocsAction(<br>        name=&quot;update_my_site&quot;, site_names=[site_name]<br>    )<br>]<br><br># Create a Checkpoint<br>checkpoint_name = &quot;gx_checkpoint&quot;<br>checkpoint = gx.Checkpoint(<br>        name=checkpoint_name,<br>        validation_definitions=[validation_definition],<br>        actions=actions,<br>    )<br>checkpoint = context.checkpoints.add(<br>    checkpoint<br>)<br><br># Validate Data by running the checkpoint<br>checkpoint_result = checkpoint.run(batch_parameters=batch_parameters)<br>print(checkpoint_result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xESnxrO1aVQbMbXH" /><figcaption>Photo by <a href="https://unsplash.com/@schmidy?utm_source=medium&amp;utm_medium=referral">Austin Schmid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>End-to-End Code</h3><pre># Install GX package<br>pip install great-expectations==1.0.0</pre><pre># 1<br># Import modules<br>import great_expectations as gx<br><br><br># 2<br># Create File Data Context OR Ephemeral Data Context<br># File Data Context<br>project_root_dir=&quot;/dbfs/FileStore/great_expectations/&quot;<br>context = gx.get_context(mode=&quot;file&quot;, project_root_dir=project_root_dir)<br><br># Ephemeral Data Context<br>project_root_dir = &quot;/dbfs/FileStore/great_expectations/&quot;<br>context = gx.get_context(mode=&quot;ephemeral&quot;)<br><br><br># 3<br># Read data to be validated in a dataframe<br>df = spark.sql(&quot;select * from schema_name.table_name&quot;)<br><br># Create a Data Source<br>dataframe_datasource = context.data_sources.add_or_update_spark(name=&quot;gx_datasource&quot;)<br><br># Create a Data Asset<br>dataframe_asset = dataframe_datasource.add_dataframe_asset(name=&quot;test_df&quot;)<br><br># Create a Batch definition<br>batch_definition = dataframe_asset.add_batch_definition_whole_dataframe(name=&quot;gx_batch_definition&quot;)<br><br># Create Batch parameters<br>batch_parameters = {&quot;dataframe&quot;: df}<br><br><br># 4<br># Create an expectations suite<br>expectation_suite_name = &quot;gx_expectation_suite&quot;<br>expectation_suite = gx.ExpectationSuite(name=expectation_suite_name)<br>expectation_suite = context.suites.add(expectation_suite)<br> <br># Add expectation in the expectations suite<br>expectation_suite.add_expectation(<br>    gx.expectations.ExpectColumnMaxToBeBetween(<br>        column=&quot;RSIZPOINT&quot;, min_value=0, max_value=1000<br>    )<br>)<br> <br># Add one more expectation in the expectations suite<br>expectation_suite.add_expectation(<br>    gx.expectations.ExpectColumnValuesToNotBeNull(<br>        column=&quot;sap_metadata&quot;<br>    )<br>)<br><br># 5<br># Create a Validation Definition<br>definition_name = &quot;gx_validation_definition&quot;<br>validation_definition = gx.ValidationDefinition(<br>    data=batch_definition, suite=expectation_suite, name=definition_name<br>)<br>validation_definition = context.validation_definitions.add(validation_definition)<br><br># Create Data Docs Site Configuration<br>base_directory = f&quot;{project_root_dir}/gx/data_docs/local_site/&quot;<br>site_config = {<br>    &quot;class_name&quot;: &quot;SiteBuilder&quot;,<br>    &quot;site_index_builder&quot;: {&quot;class_name&quot;: &quot;DefaultSiteIndexBuilder&quot;},<br>    &quot;store_backend&quot;: {<br>        &quot;class_name&quot;: &quot;TupleFilesystemStoreBackend&quot;,<br>        &quot;base_directory&quot;: base_directory,<br>    },<br>}<br><br># Create a Data Docs Site<br>site_name = &quot;gx_data_docs_site&quot;<br>context.add_data_docs_site(site_name=site_name, site_config=site_config)<br><br># Create Checkpoint Actions<br>actions = [<br>    gx.checkpoint.actions.UpdateDataDocsAction(<br>        name=&quot;update_my_site&quot;, site_names=[site_name]<br>    )<br>]<br><br># Create a Checkpoint<br>checkpoint_name = &quot;gx_checkpoint&quot;<br>checkpoint = gx.Checkpoint(<br>        name=checkpoint_name,<br>        validation_definitions=[validation_definition],<br>        actions=actions,<br>    )<br>checkpoint = context.checkpoints.add(<br>    checkpoint<br>)<br><br># Validate Data by running the checkpoint<br>checkpoint_result = checkpoint.run(batch_parameters=batch_parameters)<br>print(checkpoint_result)</pre><h3>Reusing the configuration</h3><p>For a File Data Context, metadata and configuration are stored in the project directory. We can create a file context pointing to this same location, allowing us to perform data validation without needing to reconfigure everything. In the example below, we create a file context from an existing configuration and proceed to validate the data.</p><pre># Install GX package<br>pip install great-expectations==1.0.0</pre><pre># Import modules<br>import great_expectations as gx<br><br># Initialize File Data Context<br>project_root_dir=&quot;/dbfs/FileStore/great_expectations/&quot;<br>context = gx.get_context(mode=&quot;file&quot;, project_root_dir=project_root_dir)<br><br># Read data to be validated in a dataframe<br>df = spark.sql(&quot;select * from schema_name.table_name&quot;)<br><br># Create Batch parameters<br>batch_parameters = {&quot;dataframe&quot;: df}<br><br># Get existing checkpoint from context<br>checkpoint_name = &quot;gx_checkpoint&quot;<br>checkpoint = context.checkpoints.get(checkpoint_name)<br><br># Validate Data by running the checkpoint<br>checkpoint_result = checkpoint.run(batch_parameters=batch_parameters)<br>print(checkpoint_result)</pre><h3>Data Docs</h3><p>Data Docs are human-readable HTML files generated by GX that display your Expectation Suite definitions and Validation Results. They can be configured to save on your local filesystem, Amazon S3, Azure Blob Storage, or Google Cloud Service. For more information about Data Docs, click <a href="https://docs.greatexpectations.io/docs/core/configure_project_settings/configure_data_docs/">here</a>. Below are some snapshots of the Data Docs files generated by GX.</p><figure><img alt="Great Expectations (GX) Data Docs Image 1" src="https://cdn-images-1.medium.com/max/1024/1*J03EnVOUOyoctEbmsrw6VA.png" /><figcaption>Great Expectations (GX) Data Docs Image 1</figcaption></figure><figure><img alt="Great Expectations (GX) Data Docs Image 2" src="https://cdn-images-1.medium.com/max/1024/1*D4wEbIJzT52yjyZCLjX5_g.png" /><figcaption>Great Expectations (GX) Data Docs Image 2</figcaption></figure><h3>Conclusion</h3><p>Maintaining high-quality data is essential for making accurate and informed business decisions. By implementing data verification and validation processes using frameworks like Great Expectations (GX), organizations can ensure their data meets predefined quality standards. This leads to more reliable insights, improved operations, and enhanced customer satisfaction. Prioritizing data quality not only mitigates the risks associated with poor data but also empowers businesses to thrive in a data-driven world.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>Reference</h3><ul><li><a href="https://greatexpectations.io/">Great Expectations: have confidence in your data, no matter what</a></li><li><a href="https://pypi.org/project/great-expectations/">great-expectations</a></li><li><a href="https://github.com/great-expectations/great_expectations">GitHub - great-expectations/great_expectations: Always know what to expect from your data.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34c44ce117e" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/looking-to-enhance-your-data-quality-this-is-for-you-a34c44ce117e">Looking to Enhance Your Data Quality? This is for You</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Would Someone Execute Databricks API From Azure Data Factory?]]></title>
            <link>https://blog.dataengineerthings.org/why-would-someone-execute-databricks-api-from-azure-data-factory-ffcf9e2e7990?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcf9e2e7990</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 18:05:49 GMT</pubDate>
            <atom:updated>2024-09-11T18:05:49.919Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explained scenarios where leveraging the Databricks REST API from ADF is essential to perform specific tasks with implementation</h4><h3>Introduction</h3><p>Azure Databricks is commonly used for data processing and transformation in many Azure-based projects, while Azure Data Factory (ADF) handles orchestration. Although ADF integrates with Azure Databricks to run notebooks and Python scripts, there are instances where using the Databricks API becomes necessary due to its broader range of supported operations.</p><p>Here are <strong>a few scenarios where leveraging the Databricks API from ADF is essential</strong> to perform specific tasks:</p><ul><li>Triggering Databricks jobs from ADF</li><li>Creating or updating Databricks jobs</li><li>Monitoring job status</li><li>Managing Databricks clusters</li><li>Handling secrets in the Databricks-backed secret scope</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ha265ShYgJRcOv3h" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog, we will focus on executing Databricks APIs from Azure Data Factory (ADF). For information on other methods to execute Databricks APIs, be sure to check out the below-related blog.</p><p><a href="https://medium.com/towards-data-engineering/4-ways-to-execute-databricks-api-916cc23796f8">4 Ways to Execute Any REST API, Including Databricks REST API</a></p><h3>Table of Contents</h3><ol><li><a href="#87ee">Introduction</a></li><li><a href="#05a7">Implementation</a><br> ∘ <a href="#9c43">Common Initial Setup</a><br> ∘ <a href="#e04f">GET Request</a><br> ∘ <a href="#6c0c">GET Request with Query parameters</a><br> ∘ <a href="#812b">GET Request with Path Parameters</a><br> ∘ <a href="#6058">POST Request</a><br> ∘ <a href="#4354">PUT/PATCH/DELETE Request</a></li><li><a href="#71e1">Conclusion</a></li><li><a href="#fde8">Reference</a></li></ol><h3>Implementation</h3><h4>Common Initial Setup</h4><p>a. Open Azure Data Factory Studio</p><p>b. Create a new Pipeline</p><p>c. Add a Web Activity</p><figure><img alt="ADF Pipeline with Web Activity" src="https://cdn-images-1.medium.com/max/960/1*zuFmqQVo_PEY-k5kRdpJMQ.png" /><figcaption>ADF Pipeline with Web Activity</figcaption></figure><p>d. Create a pipeline variable with the following details:</p><ul><li><strong>Name: </strong>DatabricksHostName</li><li><strong>Type: </strong>String</li><li><strong>Default Value:</strong> https://adb-xxx.azuredatabricks.net</li></ul><figure><img alt="ADF Pipeline Variable" src="https://cdn-images-1.medium.com/max/960/1*cE7tVC-R8VoCYHEAWh0ChA.png" /><figcaption>ADF Pipeline Variable</figcaption></figure><p>You can obtain the Databricks Hostname from the Databricks workspace URL. Alternatively, you can navigate to the <a href="https://portal.azure.com/">Azure Portal</a>, open the Azure Databricks resource, and copy the value of the URL property.<br>Example: <strong>https://adb-xxx.azuredatabricks.net</strong>.</p><p>e. Configure the basic settings in the <strong>General</strong> tab of the Web Activity.</p><figure><img alt="General Settings of Web Activity" src="https://cdn-images-1.medium.com/max/792/1*eYDEY8G5f2Yyyi1naUAj5g.png" /><figcaption>General Settings of Web Activity</figcaption></figure><p>f. There’s no need to configure anything in the <strong>User properties</strong> tab of the Web Activity.</p><p>g. In the <strong>Settings</strong> tab, there are two types of configurations: some are common for all Databricks API requests, and others depend on the specific type of API request (GET/POST/etc.). In this section, we will cover the common settings, followed by the API request-specific settings in the upcoming sections of the blog.</p><p>h. <strong>Common settings </strong>in the Settings tab<strong>:</strong></p><ul><li><strong>Authentication:</strong> There are several authentication options available, with <strong>System-Assigned Managed Identity</strong> being the recommended approach. For this option, you need to assign the <strong>Contributor</strong> role to the ADF-managed identity on the Azure Databricks resource.<br>To do this:<br>‣ Open the <strong>Azure Databricks</strong> resource in the Azure Portal.<br>‣ Navigate to <strong>Access Control (IAM)</strong>.<br>‣ Click on <strong>Add Role Assignment</strong> and assign the <strong>Contributor</strong> role to the Azure Data Factory’s managed identity.</li></ul><figure><img alt="Web Activity Authentication options" src="https://cdn-images-1.medium.com/max/261/1*8Cw6_R7N-B9K3iofTJ5PPA.png" /><figcaption>Web Activity Authentication Options</figcaption></figure><ul><li><strong>Resource:</strong> Provide the unique resource ID for the Azure Databricks service: 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d. This ID serves as the identifier for the Azure Databricks resource across all tenants and customers in Azure.</li><li><strong>Integration Runtime:</strong> Choose an Integration Runtime that has access to the Databricks resource.</li></ul><p>i. The API type-specific settings will be covered in the following sections, with details provided for each type of API request.</p><h4>GET Request</h4><p>Let’s execute one of Databricks’ GET API requests. In this blog, we will focus on executing a <a href="https://docs.databricks.com/api/workspace/clusters/list"><strong>List Clusters</strong></a> GET request.</p><figure><img alt="GET API Request" src="https://cdn-images-1.medium.com/max/711/1*S1z8aXWV3xrlbgvI_mESyA.png" /><figcaption>GET API Request</figcaption></figure><ul><li><strong>URL:</strong> The URL will be a combination of the Databricks Hostname and the API endpoint. We will concatenate the pipeline variable for the Databricks Hostname with the <a href="https://docs.databricks.com/api/workspace/clusters/list">List Clusters</a> API endpoint, which is /api/2.1/clusters/list.</li></ul><pre>@concat(<br>    variables(&#39;DatabricksHostname&#39;), <br>    &#39;/api/2.1/clusters/list&#39;<br>)</pre><ul><li><strong>Method:</strong> The method will be <strong>GET</strong>, as this is a GET request.</li></ul><h4>GET Request with Query parameters</h4><p>Some GET requests require one or more query parameters. For example, the <a href="https://docs.databricks.com/api/workspace/secrets/getsecret"><strong>Get a Secret</strong></a> request needs two query parameters: <strong>scope</strong> and <strong>key</strong>. When making this request, you must provide the values for the <strong>Secret scope name</strong> and <strong>Secret key</strong>.</p><ul><li><strong>URL:</strong> The URL will be a combination of the Databricks Hostname, the API endpoint, and the query parameters. We will concatenate the pipeline variable for the Databricks Hostname with the <a href="https://docs.databricks.com/api/workspace/secrets/getsecret"><strong>Get a Secret</strong></a> API endpoint, which is <strong>/api/2.0/secrets/get</strong>, and append the query parameters. If there are multiple query parameters, use <strong>&amp;</strong> to separate them.</li></ul><pre>@concat(<br>    variables(&#39;DatabricksHostname&#39;), <br>    &#39;/api/2.0/secrets/get?scope=scope_value&amp;key=key_value&#39;<br>)</pre><ul><li><strong>Method:</strong> The method will be <strong>GET</strong>, as this is a GET request.</li></ul><h4>GET Request with Path Parameters</h4><p>Some GET requests require one or more path parameters to be included in the API endpoint. For instance, the <a href="https://docs.databricks.com/api/workspace/clusters/getpermissions"><strong>Get Cluster Permissions</strong></a> request requires a path parameter: <strong>cluster_id</strong>.</p><ul><li><strong>URL:</strong> The URL will combine the Databricks Hostname with the API endpoint, including the value for the path parameter. We will concatenate the pipeline variable for the Databricks Hostname with the <a href="https://docs.databricks.com/api/workspace/clusters/getpermissions"><strong>Get Cluster Permissions</strong></a> endpoint, incorporating the <strong>cluster_id</strong> path parameter, resulting in a URL like <strong>/api/2.0/permissions/clusters/0410-xxxxxx-xxxxxxxx</strong>.</li></ul><pre>@concat(<br>    variables(&#39;DatabricksHostname&#39;), <br>    &#39;/api/2.0/permissions/clusters/0410-xxxxxx-xxxxxxxx&#39;<br>)</pre><ul><li><strong>Method:</strong> The method will be <strong>GET</strong>, as this is a GET request.</li></ul><h4>POST Request</h4><p>Let’s look at an example of a POST request. We will execute a <a href="https://docs.databricks.com/api/workspace/clusters/start#cluster_id"><strong>Start Terminated Cluster</strong></a> POST request.</p><figure><img alt="POST API Request" src="https://cdn-images-1.medium.com/max/592/1*B1U_mz6baeFtz4Sj_faZfQ.png" /><figcaption>POST API Request</figcaption></figure><ul><li><strong>URL:</strong> The URL will be a combination of the Databricks Hostname and the API endpoint. We will concatenate the pipeline variable for the Databricks Hostname with the <a href="https://docs.databricks.com/api/workspace/clusters/start#cluster_id"><strong>Start Terminated Cluster</strong></a> API endpoint, which is <strong>/api/2.1/clusters/start</strong>.</li></ul><pre>@concat(<br>    variables(&#39;DatabricksHostname&#39;), <br>    &#39;/api/2.1/clusters/start&#39;<br>)</pre><ul><li><strong>Method:</strong> The method will be <strong>POST</strong>, as this is a POST request.<br><strong>Body:</strong> In the request body, you need to include the <strong>cluster ID</strong> for the cluster you want to start.</li></ul><pre>{<br>  &quot;cluster_id&quot;: &quot;0410-xxxxxx-xxxxxxxx&quot;<br>}</pre><h4>PUT/PATCH/DELETE Request</h4><p>Similar to the above, <strong>PUT</strong>, <strong>PATCH</strong>, and <strong>DELETE</strong> requests can also be executed. These requests may require inputs in the request body, query parameters, path parameters, or a combination of these.</p><ul><li>For the <strong>request body</strong>, you can refer to the <a href="#6058">POST Request</a> example.</li><li>For <strong>query parameters</strong>, you can refer to the <a href="#6c0c">GET Request with Query parameters</a> example.</li><li>For <strong>path parameters</strong>, you can refer to the <a href="#812b">GET Request with Path Parameters</a> example.</li></ul><h3>Conclusion</h3><p>In conclusion, executing Databricks APIs from Azure Data Factory (ADF) provides significant benefits for data management and orchestration. It enables seamless integration between data processing and orchestration platforms, allowing you to trigger jobs, manage clusters, and handle secrets directly within your ADF pipelines. This integration enhances automation, improves operational efficiency, and streamlines complex data workflows. By leveraging Databricks APIs through ADF, you can achieve more precise control over your data processes and optimize your overall data engineering strategy.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>Reference</h3><p><a href="https://medium.com/towards-data-engineering/4-ways-to-execute-databricks-api-916cc23796f8">4 Ways to Execute Any REST API, Including Databricks REST API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcf9e2e7990" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/why-would-someone-execute-databricks-api-from-azure-data-factory-ffcf9e2e7990">Why Would Someone Execute Databricks API From Azure Data Factory?</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Steps to Create Your Own PyPi (Python) Package]]></title>
            <link>https://medium.com/pythoneers/the-ultimate-guide-for-creating-and-uploading-python-packages-to-pypi-aea1ffada7fe?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea1ffada7fe</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[packaging]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 19:21:17 GMT</pubDate>
            <atom:updated>2024-09-05T14:18:40.974Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive guide on creating and publishing an open-source or private Python package to PyPi (Python Package Index) using GitHub Actions</h4><p>When I embarked on the journey of creating my first Python package, I encountered several challenges:</p><ol><li><strong>Transforming Code into a Reusable Package</strong>: I needed to figure out how to convert my Python functions and modules into a package that others could reuse.</li><li><strong>Uploading to PyPi</strong>: Once the package was ready, the next hurdle was understanding how to upload it to <a href="https://pypi.org/">PyPi</a>, making it accessible to the wider community.</li><li><strong>Integrating with Source Control</strong>: After publishing the package, I faced the challenge of linking it to my source code repository (on <a href="https://github.com/">GitHub</a>, whether open or closed) so that I could easily manage updates and new versions.</li></ol><p>Unfortunately, a comprehensive, step-by-step guide for these tasks was hard to come by. Having navigated these challenges and found solutions, I’ve decided to create this guide to assist other new Python developers facing similar hurdles.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQF4XR4wMqdBynN3Sto%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffallontonight-problems-chef-jos-andrs-QF4XR4wMqdBynN3Sto&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZTFvYnR4ZnVubm1vNmE4OTJoeG11ZWtqbGhybGo0Y2s3ZTR5ZzU0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FQF4XR4wMqdBynN3Sto%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="311" frameborder="0" scrolling="no"><a href="https://medium.com/media/425baaf36c7c4218a5fbfcb6970758d5/href">https://medium.com/media/425baaf36c7c4218a5fbfcb6970758d5/href</a></iframe><h3>Table of Contents</h3><ol><li><a href="#eb4b">Basics of Python Package</a><br> ∘ <a href="#f899">Python Module</a><br> ∘ <a href="#d6e9">Python Package</a></li><li><a href="#ad42">Source Code Repository</a></li><li><a href="#d773">Source Code</a></li><li><a href="#2893">Packaging Files</a><br> ∘ <a href="#b605">License File</a><br> ∘ <a href="#63d5">Setup.py File</a><br> ∘ <a href="#a586">README.md File</a></li><li><a href="#7f28">Build the Package</a></li><li><a href="#e4ad">Upload Package to Test PyPi</a></li><li><a href="#cb69">Upload Package to PyPi</a><br> ∘ <a href="#6552">Manually</a><br> ∘ <a href="#4a8e">GitHub Actions</a></li><li><a href="#f989">Conclusion</a></li><li><a href="#6369">Reference</a></li></ol><h3>Basics of Python Package</h3><p>In Python, <strong>modules</strong> and <strong>packages</strong> are two ways to organize and structure your code. Understanding the difference between them is crucial for managing larger projects.</p><h4>Python Module</h4><p>A module is simply a single Python file that contains Python code. It can include functions, classes, variables, and runnable code. Modules help you organize your code by grouping related functions and classes in one file. You can import a module in another Python file to use its functions and classes.</p><p>Consider a math_operations.py with the following content:</p><pre># math_operations.py<br><br>def add(a, b):<br>    return a + b<br><br>def subtract(a, b):<br>    return a - b</pre><p>You can import and use this module in another Python file:</p><pre># main.py<br><br>import math_operations<br><br>result = math_operations.add(5, 3)<br>print(result)  # Output: 8</pre><h4>Python Package</h4><p>A package is a collection of modules organized in directories that also contain a special file called __init__.py. The presence of __init__.py indicates that the directory is a Python package, and it can be imported as a package. Packages are used to structure large codebases by grouping related modules into a directory structure. This helps in organizing and managing code more effectively, especially in larger projects.</p><p>Consider you have the following directory structure for a package:</p><pre>my_package/<br>    __init__.py<br>    arithmetic.py<br>    geometry.py</pre><ul><li>__init__.py (could be empty or contain initialization code for the package).</li><li>arithmetic.py could have functions like add and subtract.</li><li>geometry.py could have functions like area_of_circle and perimeter_of_square.</li></ul><p>Below is an example of how you could use this package:</p><pre># main.py<br><br>from my_package import arithmetic, geometry<br><br>result = arithmetic.add(10, 5)<br>print(result)  # Output: 15<br><br>area = geometry.area_of_circle(3)<br>print(area)</pre><p>In summary:</p><ul><li><strong>Module</strong>: A single file containing Python code (.py file).</li><li><strong>Package</strong>: A directory that contains multiple modules and an __init__.py file, making it importable as a collection of modules.</li></ul><p>Now that we understand the basics of Python package, let’s delve into the steps to create a Python package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zKahA9LR3BQ-6pBd" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum?utm_source=medium&amp;utm_medium=referral">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Source Code Repository</h3><ul><li>Create a code repository to host the source code of your package.</li><li>If available, select the option to auto-generate a .gitignore file for the Python project when creating the repository.</li><li>The repository can be either private or public.</li><li>The repository&#39;s name does not need to match the name of your package.</li><li>For this blog, I am using <a href="https://github.com/">GitHub</a> as a code repository.</li></ul><h3>Source Code</h3><ul><li>Clone the repository to your local machine.</li><li>Create a folder in the root of your repository with the same name as your Python package. For example, if your package name is databricks-filesystem then create a root folder named databricks_filesystem. Remember to replace hyphens with underscores in the folder name.</li><li>Place all your package codes inside this package folder.</li><li>Inside the package folder (and any subfolders), create a __init__.py file. This file can be empty or contain initialization code, but it&#39;s necessary for the folder to be recognized as a package or subpackage.</li><li>You can follow the structure outlined below for your package:</li></ul><pre>my_package/<br>    __init__.py<br>    arithmetic.py<br>    geometry.py</pre><ul><li>If your code is complex and needs better organization, you can group your modules (.py files) into sub-packages. For example, in the structure below, the sub-packages arithmetic and geometry are used:</li></ul><pre>my_package/<br>    __init__.py<br>    arithmetic<br>        __init__.py<br>        sum.py<br>        subtract.py<br>    geometry<br>        __init__.py<br>        area_of_circle.py<br>        perimeter_of_square.py</pre><ul><li>You can organize your source code by following the above structures.</li></ul><h3>Packaging Files</h3><ul><li>Once your source code is ready, you’ll need to create some essential packaging files: LICENSE, README.md, and setup.py.</li><li>These files should be placed in the root directory of your repository as shown below:</li></ul><pre><br>LICENSE<br>README.md<br>setup.py<br>my_package/<br>    __init__.py<br>    arithmetic.py<br>    geometry.py</pre><h4>License File</h4><p>Creating a license file for a Python package is essential as it defines how others can use, modify, and distribute your code.</p><p>Here is how you can create a Python license file:</p><p>1. <strong>Choose a License:</strong><br>First, decide which license you want to use. Some popular options include:</p><ul><li>MIT License: A permissive license allows others to do almost anything with your code, as long as they include the original copyright notice.</li><li>GNU General Public License (GPL): Requires that any derivative works also be open source and distributed under the same license.</li><li>Apache License 2.0: Similar to the MIT License, but with explicit provisions related to patents.</li><li>BSD License: A permissive license with fewer restrictions than GPL but with similar goals.</li><li>Creative Commons Zero (CC0): A public domain dedication allowing anyone to use your code for any purpose without any conditions.</li></ul><p>2. <strong>Generate the License Text:</strong><br>You can manually write the license text or use an online service like <a href="https://choosealicense.com/">Choose a License</a> or <a href="https://github.com/github/choosealicense.com">GitHub’s license templates</a> to generate the license text based on your choice.</p><p>3. <strong>Create a LICENSE File:</strong><br>Once you’ve selected your license, you need to create a file named LICENSE (without any file extension) in the root directory of your project.</p><p>An example MIT license is available <a href="https://github.com/madhanir/databricks_filesystem/blob/main/LICENSE">here</a>.</p><p>4. <strong>Save the File:</strong><br>Save this file in the root of your project directory. When others view your project, they will see the LICENSE file and understand how they can use your code.</p><h4>Setup.py File</h4><p>In the root of your project directory create a file named setup.py. This file will contain the configuration for your package. Here is a sample setup.py file:</p><pre>from setuptools import setup, find_packages<br><br>setup(<br>    name=&quot;my_package&quot;,              # Required: Name of the package<br>    version=&quot;0.0.1&quot;,                  # Required: Version of the package<br>    author=&quot;Your Name&quot;,             # Optional: Author&#39;s name<br>    author_email=&quot;your.email@example.com&quot;,  # Optional: Author&#39;s email<br>    description=&quot;A short description of the package&quot;,  # Optional: Brief description<br>    long_description=open(&quot;README.md&quot;).read(),  # Optional: Long description from README<br>    long_description_content_type=&quot;text/markdown&quot;,  # Optional: Content type of long description<br>    url=&quot;https://github.com/yourusername/my_package&quot;,  # Optional: Project URL<br>    packages=find_packages(),        # Required: Automatically find packages<br>    install_requires=[               # Optional: List of dependencies<br>        &quot;numpy&quot;,<br>        &quot;requests&quot;,<br>    ],<br>    classifiers=[                    # Optional: Additional metadata<br>        &quot;Programming Language :: Python :: 3&quot;,<br>        &quot;License :: OSI Approved :: MIT License&quot;,<br>        &quot;Operating System :: OS Independent&quot;,<br>    ],<br>    python_requires=&#39;&gt;=3.6&#39;,         # Optional: Python version compatibility<br>    project_urls={                   # Optional: Information about the source code of the package. If you want to open-source your package. You can create a public repository and add its link here.<br>        &quot;Documentation&quot;: &quot;project documentation&quot;,<br>        &quot;Source&quot;: &quot;https://github.com/yourusername/my_package,<br>    },<br>)</pre><h4>README.md File</h4><p>Creating a README.md file for your Python package is an important step in documenting your project. This file serves as the first point of contact for users, providing them with an overview of your package, installation instructions, usage examples, and other relevant information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XTIKSx_eOCGULpwz" /><figcaption>Photo by <a href="https://unsplash.com/@domenicoloia?utm_source=medium&amp;utm_medium=referral">Domenico Loia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Build the Package</h3><p>With the source code and packaging files in place, we can now build the package and generate a wheel file. A wheel file is a binary distribution format for Python packages, designed to make installation faster and more efficient. Follow these steps to generate the wheel file:</p><ul><li>Install the necessary Python libraries for creating a package using the following command:<br>python -m pip install -U pip setuptools wheel</li><li>Generate the wheel file for your package with the command:<br>python setup.py bdist_wheel</li><li>Install the package in your local environment using this command: <br>pip install .</li><li>Finally, test the package to ensure everything is working correctly.</li></ul><h3>Upload Package to Test PyPi</h3><ul><li>Before publishing your package on <a href="https://pypi.org/">PyPi</a>, it’s a good idea to first upload it to <a href="https://test.pypi.org/">Test PyPi</a>. Test PyPi is a separate instance of the Python Package Index used for testing and experimenting with package uploads.</li><li>This allows you to practice and ensure everything works correctly without impacting the main PyPi repository.</li><li>Go to <a href="https://test.pypi.org/">Test PyPi</a> and perform below initial steps below:<br>‣ Create an account on Test PyPi.<br>‣ Verify your email address.<br>‣ Set up two-factor authentication for added security.<br>‣ Generate an API token for authentication.<br>‣ Copy the generated API token.</li><li>Next, install or upgrade Twine, a utility for securely uploading Python packages to repositories like PyPi or Test PyPi:<br>python -m pip install --user --upgrade twine</li><li>To publish your package on Test PyPi, use the following command:<br>python -m twine upload --repository testpypi dist/*</li><li>When prompted for a username, enter __token__. For the password, paste the API token you copied earlier.</li><li>To install the package from Test PyPi, use this command:<br>pip install --index-url <a href="https://test.pypi.org/simple/">https://test.pypi.org/simple/</a> package-name</li><li>Finally, test the installed package to ensure everything is functioning as expected.</li></ul><h3>Upload Package to PyPi</h3><p>To upload your package to <a href="https://pypi.org/">PyPi</a>, you have two options:</p><ol><li><strong>Manual Upload</strong> (similar to what we did for Test PyPi).</li><li><strong>Using GitHub Actions</strong> for automated deployment.</li></ol><p>For both methods, you’ll first need to create an account on <a href="https://pypi.org/">PyPi</a> by following these steps:<br>‣ Create an account on <a href="https://pypi.org/">PyPi</a>.<br>‣ Verify your email address.<br>‣ Set up two-factor authentication for added security.<br>‣ Generate an API token.<br>‣ Copy the API token for use in your uploads.</p><h4>Manually</h4><ul><li>Publish the package to PyPi using the below command:<br>python -m twine upload dist/*</li><li>When prompted for a username, enter __token__. For the password, paste the API token you copied earlier.</li><li>To install the package from PyPi, use this command:<br>pip install package-name</li><li>Finally, test the installed package to ensure everything is functioning as expected.</li></ul><h4><strong>GitHub Actions</strong></h4><ul><li>Push your code files to the <a href="https://github.com/">GitHub</a> repository.</li><li>Navigate to GitHub &gt; Actions &gt; Click on &quot;Publish Python Package&quot; &gt; Commit the YAML workflow file.</li><li>Add your PyPi token in GitHub to enable the action to publish the package.</li><li>To do this, go to GitHub &gt; Settings &gt; Security &gt; Secrets and Variables &gt; Actions &gt; Repository secrets &gt; New Repository Secret.<br>Secret name: PYPI_API_TOKEN<br>Value: Paste the copied API TOKEN</li><li>Go to PyPi. For an existing project/package, navigate to Projects &gt; Manage &gt; Publishing. For a new project/package, go to User &gt; Account Settings &gt; Publishing.</li><li>Select GitHub as the publishing method and fill in all the required details as shown in the image below.</li></ul><figure><img alt="GitHub Action to Publish Python Package" src="https://cdn-images-1.medium.com/max/730/1*omMPTSYHo_YcVkVwzoNvzw.png" /><figcaption>GitHub Action to Publish Python Package</figcaption></figure><ul><li>Once your code changes are ready on GitHub, follow these steps to publish the package.</li><li>Create a Release:<br>‣ Navigate to GitHub -&gt; Releases and create a new release.<br>‣ Add a release description, assign a tag, and click Publish Release.</li><li>Monitor the Release:<br>‣ Go to GitHub Actions to track the progress of the release.</li><li>Verify Publication:<br>‣ Check PyPi to confirm that the package has been published.</li><li>Test the Package:<br>‣ Install the package from PyPi and test it to ensure everything is functioning correctly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lQ6lz7lWRQCQk1Qr" /><figcaption>Photo by <a href="https://unsplash.com/@alejandroescamilla?utm_source=medium&amp;utm_medium=referral">Alejandro Escamilla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Conclusion</h3><p>In this comprehensive guide, we’ve walked through every step of creating and uploading a Python package to PyPI, from setting up your project to automating the release process with GitHub Actions. Whether you’re releasing an open-source library or a private package, these steps will help you streamline the packaging and distribution process. By following this guide, you should now be equipped with the knowledge to confidently build, test, and publish your Python packages, making them easily accessible to the Python community. Happy coding and packaging!</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow <a href="https://medium.com/pythoneers">The Pythoneers</a> publication for more stories like this one.</li></ul><h3>Reference</h3><p><a href="https://towardsdatascience.com/how-to-publish-a-python-package-to-pypi-7be9dd5d6dcd">How to publish a Python Package to PyPi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea1ffada7fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pythoneers/the-ultimate-guide-for-creating-and-uploading-python-packages-to-pypi-aea1ffada7fe">7 Steps to Create Your Own PyPi (Python) Package</a> was originally published in <a href="https://medium.com/pythoneers">The Pythoneers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can We Use Databricks CLI Without Installing It? You Will Be Amazed Like Me]]></title>
            <link>https://blog.dataengineerthings.org/can-we-use-databricks-cli-without-installing-it-you-will-be-amazed-like-me-943c73d3418e?source=rss-848ed590b97------2</link>
            <guid isPermaLink="false">https://medium.com/p/943c73d3418e</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-architect]]></category>
            <dc:creator><![CDATA[Rahul Madhani]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 16:07:42 GMT</pubDate>
            <atom:updated>2024-09-05T14:19:16.237Z</atom:updated>
            <content:encoded><![CDATA[<h4>I was amazed to discover a way to use the Databricks CLI without needing to install any executable files on my machine</h4><h3>How is it possible?</h3><p>Yes, it is possible with the Python package <a href="https://pypi.org/project/databricks-cli/">databricks-cli</a>. With this approach, there’s no need to download or install any executable files. You just need to install the databricks-cli Python package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X2iBP4yRKU2VNbj2" /><figcaption>Photo by <a href="https://unsplash.com/@krakenimages?utm_source=medium&amp;utm_medium=referral">krakenimages</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog will explore how to use the Databricks CLI without installing it. If you prefer to install the CLI, you can check out my other blog to learn how to install and use the Databricks CLI.</p><p><a href="https://medium.com/towards-data-engineering/easy-guide-to-configure-and-use-databricks-command-line-interface-cli-079721a7bab8">4 Steps to Use Databricks Command-Line Interface (CLI)</a></p><p>Before diving into the solution, let’s take a moment to understand the Databricks CLI.</p><h3>Table of contents</h3><ol><li><a href="#7548">What is Databricks CLI?</a></li><li><a href="#c327">When to use Databricks CLI Python Package</a></li><li><a href="#5c1e">Install and configure the Databricks CLI package</a></li><li><a href="#00d5">Cluster API Example</a></li><li><a href="#8cb5">DBFS API Example</a></li><li><a href="#28e4">Secret API Example</a></li><li><a href="#e1b9">Other APIs</a></li><li><a href="#5f69">Conclusion</a></li><li><a href="#2acf">References</a></li></ol><h3>What is Databricks CLI?</h3><p>The Databricks command-line interface (or the Databricks CLI) utility provides an easy-to-use interface to automate the Databricks platform from your terminal/command prompt. For example, you can start/stop or deploy a new cluster, create a new job, run/monitor an existing databricks job, and deploy files/libraries from the local system to DBFS. It also helps to automate Databricks tasks.</p><p>The Databricks CLI wraps the Databricks REST API, an application programming interface (API) that uses a REST perspective to automate Databricks account and workspace resources and data.</p><p>If you want to install the Databricks CLI on your machine to use it, then you can read <a href="https://medium.com/towards-data-engineering/easy-guide-to-configure-and-use-databricks-command-line-interface-cli-079721a7bab8#066d">this</a> article.</p><h3>When to use Databricks CLI Python Package</h3><p>Below are a few scenarios where it would be better to use the Databricks CLI Python Package rather than installing the Databricks CLI software</p><ol><li>You often don’t have permission to install software on the company’s machine and installation can be done by raising a service request/ticket. This could result in a wait time for the software to be installed.</li></ol><p>2. You are more familiar with Python and hence want to leverage the Python package to execute Databricks CLI commands.</p><p>Let’s then start with Databricks CLI using the Python package.</p><p>Below are a few scenarios where it would be better to use the Databricks CLI Python package rather than installing the Databricks CLI software:</p><ol><li><strong>Restricted Permissions</strong>: Often, you may not have permission to install software on your company’s machine, and installation can only be done by raising a service request or ticket. This could result in a wait time for the software to be installed.</li><li><strong>Python Familiarity</strong>: If you are more familiar with Python, you can leverage the Python package to execute Databricks CLI commands.</li></ol><p>Let’s then start with using the Databricks CLI through the Python package.</p><h3>Install and configure the Databricks CLI package</h3><h4>Installation</h4><pre># Install the databricks-cli Python package<br>pip install databricks-cli</pre><h4>Pre-setup</h4><p>To connect to Databricks workspace from Databricks CLI you need <strong>Databricks Hostname</strong> and <strong>Databricks Personal access token (PAT)</strong>.</p><p>Let’s get Databricks Hostname and Databricks Personal Access Token.</p><ol><li>Databricks Hostname: Databricks Hostname is the same as the workspace URL. Example: <a href="https://adb-xxx.azuredatabricks.net/">https://adb-xxx.azuredatabricks.net</a></li><li>Databricks Personal Access Token: Follow the below steps to generate a Databricks Personal Access Token</li></ol><ul><li>Login to Databricks Workspace</li><li>Click on your user name at the right-top corner</li><li>Click on User Settings</li><li>Browse to Settings &gt; Developer settings &gt; Access Tokens</li><li>Click on Generate new token</li><li>Provide your comment ‘Access Token for Databricks CLI’ and provide a Lifetime for the token in days.</li><li>Copy the token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*ETSdgvcZBARhObRc.png" /><figcaption>Generate Databricks Personal Access Token</figcaption></figure><p><strong>Note:</strong> The token will expire after the Lifetime days. You can generate a new token and use it.</p><h4>Configuration:</h4><pre>from databricks_cli.sdk.api_client import ApiClient<br> <br>api_client = ApiClient(<br>    host = &quot;https://adb-526817968400323.3.azuredatabricks.net/&quot;,<br>    token = &quot;dapi326b606a48dadfa7c3865f0598173b7d-2&quot;<br>)</pre><h3>Cluster API Example</h3><p>The Cluster API can be used to perform various cluster operations such as creating clusters, editing clusters, starting clusters, retrieving cluster information, and much more. You can learn more about the Cluster API <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/clusters/api.py">here</a>.</p><p>Below are examples of Cluster API:</p><pre># Import Cluster API module<br>from databricks_cli.clusters.api import ClusterApi<br><br># Configure Cluster API<br>cluster_api = ClusterApi(api_client)<br><br># Example 1: List clusters<br>clusters_list = cluster_api.list_clusters()<br><br># Print cluster name and cluster ID <br>for cluster in clusters_list[&#39;clusters&#39;]:<br>    print(f&quot;{cluster[&#39;cluster_name&#39;]}, {cluster[&#39;cluster_id&#39;]}&quot;)<br><br># Example 2: Get cluster using cluster ID<br>cluster_config = cluster_api.get_cluster(cluster_id=&quot;xxx&quot;)<br><br># Print cluster config<br>print(cluster_config) </pre><h3>DBFS API Example</h3><p>The DBFS API can be used to perform various DBFS operations such as listing files, copying files, deleting files, retrieving files, and much more. You can learn more about the DBFS API <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/dbfs/api.py">here</a>.</p><p>Below are examples of DBFS API:</p><pre># Import DBFS API module<br>from databricks_cli.dbfs.api import DbfsApi<br><br># Configure DBFS API<br>dbfs_api = DbfsApi(api_client)<br><br># Import DBFS Path module<br>from databricks_cli.dbfs.dbfs_path import DbfsPath<br><br># Configure DBFS Path<br>dbfs_path = DbfsPath(&quot;dbfs:/FileStore/test&quot;)<br><br># Example 1: List files in DBFS path<br>dbfs_files = dbfs_api.list_files(dbfs_path=dbfs_path)<br><br># Print files<br>for dbfs_file in dbfs_files:<br>    print(dbfs_file.dbfs_path)<br><br># Example 2: Copy files from DBFS to Local<br>dbfs_api.cp(recursive=True, overwrite=True, src=&quot;dbfs:/FileStore/test&quot;, dst=&quot;C:\\Users\\xxx\\test\\&quot;)<br><br># Example 3:Copy files from Local to DBFS<br>dbfs_api.cp(recursive=True, overwrite=True, src=&quot;C:\\Users\\xxx\\test\\&quot;, dst=&quot;dbfs:/FileStore/test&quot;)</pre><h3>Secret API Example</h3><p>The Secret API offers functionalities for secret operations, including creating scopes, deleting scopes, listing scopes, listing secrets, and more. For further details, you can explore the Secret API <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/secrets/api.py">here</a>.</p><p>Below are examples of Secret API:</p><pre># Import Secret API module<br>from databricks_cli.secrets.api import SecretApi<br><br># Configure SecretAPI<br>secret_api = SecretApi(api_client)<br><br># Example 1: List secret scopes<br>secret_scopes = secret_api.list_scopes()<br><br># Print secret scopes<br>for secret_scope in secret_scopes[&#39;scopes&#39;]:<br>    print(f&quot;{secret_scope[&#39;name&#39;]}&quot;)</pre><h3>Other APIs</h3><p>There are many other APIs available that can be utilized, such as the <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/workspace/api.py">Workspace API</a> for workspace-related operations, the <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/pipelines/api.py">Job API</a> for managing jobs, the <a href="https://github.com/databricks/databricks-cli/blob/main/databricks_cli/pipelines/api.py">Pipelines API</a> for managing pipelines, and the Libraries API for managing libraries, among <a href="https://github.com/databricks/databricks-cli/tree/main/databricks_cli">others</a>. Each of these APIs provides specific functionalities to streamline various aspects of working with Databricks.</p><h3>Conclusion</h3><p>Leveraging the Python package databricks-cli presents a streamlined and efficient approach to managing Databricks environments. This method eliminates the need for downloading and installing any executable files, thereby simplifying the setup process.</p><p>By merely installing the databricks-cli Python package, users can access a robust set of tools and functionalities to interact with Databricks, making it a convenient and powerful solution for data engineers and analysts.</p><p><strong>Thank you for reading!</strong> If you enjoyed this post and want to show your support, here’s how you can help:</p><ul><li>Clap 👏 and share your thoughts 💬 in the comments below.</li><li>Follow me on <a href="https://rahulmadhani20.medium.com/">Medium</a> for more content.</li><li>Follow me on <a href="https://www.linkedin.com/in/rahulmadhani/">LinkedIn</a>.</li><li>Join my <a href="https://rahulmadhani20.medium.com/subscribe">email list</a> to ensure you never miss an article.</li><li>Follow the <a href="https://blog.det.life/">Data Engineer Things</a> publication for more stories like this one.</li></ul><h3>References</h3><ul><li><a href="https://medium.com/towards-data-engineering/easy-guide-to-configure-and-use-databricks-command-line-interface-cli-079721a7bab8">Easy guide to configure and use Databricks command-line interface (CLI)</a></li><li><a href="https://github.com/databricks/databricks-cli/tree/main/databricks_cli">databricks-cli/databricks_cli at main · databricks/databricks-cli</a></li><li><a href="https://pypi.org/project/databricks-cli/">databricks-cli</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=943c73d3418e" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/can-we-use-databricks-cli-without-installing-it-you-will-be-amazed-like-me-943c73d3418e">Can We Use Databricks CLI Without Installing It? You Will Be Amazed Like Me</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>