<?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 Luis Miguel Miranda on Medium]]></title>
        <description><![CDATA[Stories by Luis Miguel Miranda on Medium]]></description>
        <link>https://medium.com/@lmirandad27?source=rss-b69755d413a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-70UIzmW-VpcZ6Iv7Bi4kA@2x.jpeg</url>
            <title>Stories by Luis Miguel Miranda on Medium</title>
            <link>https://medium.com/@lmirandad27?source=rss-b69755d413a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:39:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lmirandad27/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[Exploring Analytics Engineering: Insights from a Former Data Engineer]]></title>
            <link>https://blog.devgenius.io/exploring-analytics-engineering-insights-from-a-former-data-engineer-c37a371a5136?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37a371a5136</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 18:10:55 GMT</pubDate>
            <atom:updated>2024-02-21T05:16:26.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuJCbjivC6EuMRJqadRDHg.jpeg" /><figcaption>Photo from <a href="https://unsplash.com/photos/man-wearing-white-shirt-siting-on-bridge-overlooking-at-mountain-BReigPd7XnQ">Alex Azabache</a> (Unsplash)</figcaption></figure><h3>What’s the Buzz About Analytics Engineering?</h3><p>In recent years, Analytics Engineering has emerged as a buzzing topic in the tech world, capturing the attention of many professionals. But what exactly is stirring up so much interest in this field? At its core, Analytics Engineering bridges the gap between data collection and data utilization, ensuring that the vast streams of data are not only stored but also primed for insightful analysis. This role is pivotal in transforming raw data into a format that is easily accessible and interpretable for businesses, thereby enabling informed decision-making.</p><p>While Data Engineering focuses on the infrastructure and pipelines necessary for data collection and storage, Analytics Engineering takes this a step further. It’s about refining that data into a treasure trove of insights that can guide strategic business moves.</p><h3>First things first, what is Data Engineering?</h3><p>Joe Reis, in his book <a href="https://www.oreilly.com/library/view/fundamentals-of-data/9781098108298/"><em>Fundamentals of Data Engineering</em></a>, states:</p><blockquote>Data engineering is the development, implementation, and maintenance of systems and processes that take in raw data and produce high-quality, consistent information that supports downstream use cases, such as analysis and machine learning.</blockquote><p>It’s important to know where this role sits in the organization, alongside Software Engineers, Data Analysts/Scientists and others. I believe this graph can help to clarify that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ICORuqg8myYdGPoC21YmA.png" /><figcaption>The role of a Data Engineer (graph from <a href="https://blog.pragmaticengineer.com/what-is-data-engineering/">pragmaticengineer.com</a>). By the way, we can put the ML Engineers close to them, but that’s another story.</figcaption></figure><p>Previously, as a Data Engineer, my main duties revolved around the implementation and deployment of ETL processes or pipelines. Although I didn’t have the opportunity to create event-based pipelines (data streaming) in a professional setting, I undertook many similar projects in my personal portfolio. Even I had the chance to interact with different data-centric roles such as Data Modelers, Data Architect and Data Custodians (besides Data Scientist and Data Analyst), so I believe this graph is very accurate.</p><p>Understanding Data Engineering is crucial before delving into Analytics Engineering, as it lays the groundwork for initial data handling. Data Engineers are responsible for collecting, cleaning, and organizing data, ensuring it is prepared for more in-depth analysis. This foundational work is vital for Analytics Engineers to generate insights that drive informed business decisions.</p><h3>What Sparked My Interest in Analytics Engineering?</h3><p>My journey into Analytics Engineering was ignited by years of experience in Data Engineering, where I mastered the art of managing and preparing data. Over time, I developed a deep appreciation for the potential that data holds, not just in its collection but in its power to drive transformational business decisions. What truly sparked my interest in Analytics Engineering was the realization that through this role, I could elevate my impact on the business by turning data into a narrative. It was the prospect of moving beyond the infrastructure and plumbing of data systems to playing a pivotal role in shaping strategy and guiding decisions with insightful analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiwjuU0QoDuVeg_Kdzlo3w.jpeg" /><figcaption>Always stay curious — Photo by <a href="https://unsplash.com/photos/black-and-white-trying-to-climb-the-window-BovnwxDCing">Bing Han</a> (Unsplash)</figcaption></figure><p>Analytics Engineering offered a connection between the technical world of data management and the dynamic realm of business intelligence. It was an opportunity to not just work with data, but to tell its story, influence outcomes, and be at the heart of decision-making processes. My passion for making data understandable and actionable for everyone in the organization has been the driving force behind my shift to Analytics Engineering. It’s this journey of transformation — from handling the bits and bytes to unveiling the stories they tell — that has been incredibly rewarding and continues to fuel my passion for the field.</p><h3>Okay Okay… but What is an Analytics Engineer?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6SwK6bO-pUznxAPvxFdYg.jpeg" /><figcaption>Just kidding…</figcaption></figure><p>Saira Barles, Analytics Engineer at Hubspot, creatively characterizes the role:</p><blockquote>Data engineers build the cupboard, they gather together the wood and the tools and put it together. The Analytics Engineers open the cupboard and start putting in the plates, mugs, bowls, and arrange them in a certain order. This could be arranging them into particular colours, shapes or sizes. Data analysts then go into the cupboard and they know where everything lives as it is arranged nicely. They can then grab the small blue mug they were looking for and go make a cup of tea!</blockquote><p>Interesting…</p><h4>A bridge between roles</h4><p>Based on my experience, an Analytics Engineer indeed acts as a vital link between Data Engineers and Data Analysts. This distinctive role enables us to grasp both the complexities of data engineering — the collection, cleaning, and organization of data — and the critical thinking and analytical prowess required for data analysis. Being positioned at the intersection of these two areas, an Analytics Engineer serves not only as a mediator but also as a <strong>synthesizer</strong> of data and insights, capable of crafting superior data products. Our dual expertise allows us to develop systems and processes that efficiently manage data while transforming it into meaningful insights. This ensures that our final products are not just technically robust but also highly relevant and actionable for business strategies. Essentially, I believe an Analytics Engineer must understand the subtleties of both Data Engineers and Data Analysts’ work, empowering us to create better, more informed data solutions that facilitate significant change</p><h4>A role with Software Engineering practices</h4><p>As you dive into your analytics workflows — a key aspect of this role focused on converting raw data into actionable insights — you’ll begin to engage with coding. A point of debate often arises regarding the coding approach for these analytics solutions: whether it should be an individual effort or a collaborative one. Tristan Handy of dbt Labs has outlined five essential practices that analytics teams can borrow from the realm of software engineering:</p><blockquote>Analytics code should be <strong>version controlled</strong></blockquote><blockquote>Analytics code should have <strong>quality assurance</strong></blockquote><blockquote>Analytics code should be modular</blockquote><blockquote>Analytics should use environments</blockquote><blockquote>Analytics code should be designed for maintainability</blockquote><h4>Main Duties</h4><p>Integrating these practices in a data-centric manner outlines the primary duties of an Analytics Engineer:</p><p><strong>1 Data Modeling:</strong> Design and develop data models for analytics and business intelligence.</p><p><strong>2 Data Transformation:</strong> Clean, transform, and prepare data for analysis.</p><p><strong>3 ETL/ELT Implementations:</strong> Build and maintain data pipelines for efficient data flow.</p><p><strong>4 Data Quality:</strong> Ensure data quality and integrity through rigorous testing and validation.</p><p><strong>5 Documentation:</strong> Create and maintain documentation for data models, data flow processes, and analytics reports.</p><h4>Data Stack for an Analytics Engineer</h4><p>The tools employed by an Analytics Engineer closely mirror those used by Data Engineers and Data Analysts. Here&#39;s an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuBm17hGGgQWDUXJY91Qeg.png" /></figure><p><strong>What about SQL and Python?</strong> Analytics Engineers are SQL wizards! and Python would be a plus for this role.</p><p>Incidentally, <strong>dbt</strong> is a widely recognized tool deeply associated with the field of Analytics Engineering, with dbt Labs being at the forefront of its development. I highly recommend exploring this tool if you’re keen on pursuing a career in Analytics Engineering.</p><p>My first experience with dbt was in an interesting Udemy course bootcamp; I highly recommend this one:</p><p><a href="https://www.udemy.com/course/complete-dbt-data-build-tool-bootcamp-zero-to-hero-learn-dbt/">https://www.udemy.com/course/complete-dbt-data-build-tool-bootcamp-zero-to-hero-learn-dbt/</a></p><h3>One last thing</h3><p>As a Data Engineer, I gained extensive knowledge in data modeling, data pipelines, and various technologies. I think transitioning to Analytics Engineering could be expedited, as it largely involves delving into the analytical aspects of our thinking. For Data Analysts or anyone else aspiring to become an Analytics Engineer, the journey might present challenges (or perhaps not), but possessing the skill to convert data into insights offers a significant advantage.</p><p><em>Now working as an Analytics Engineer at </em><a href="https://www.aterio.io/"><em>Aterio</em></a>, I’ve really seen how the work I talked about before is used in real life. My past experience as a Data Engineer helps me every day. At Aterio, what I used to just learn about or think about, I now do for real. This has shown me how important Analytics Engineering is for making smart business choices.</p><h4>Maintaining enthusiasm and passion will make the journey incredible!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bn3BpnEbD05ybv1eygMKoQ.jpeg" /><figcaption>Photo from <a href="https://unsplash.com/photos/person-in-red-hoodie-standing-on-snowy-mountain-during-daytime--87JyMb9ZfU">Joshua Earle</a> (Unsplash)</figcaption></figure><h3>Conclusions</h3><p>In the fast-paced world of technology, the role of an Analytics Engineer has become increasingly vital, acting as the keystone between raw data and strategic insights. My journey from Data Engineering to Analytics Engineering has been both challenging and rewarding, providing me with the unique opportunity to transform data into narratives that drive business success. As we look towards the future, the blend of technical skills, creative thinking, and the ability to communicate complex information in simple terms will continue to be crucial. Whether you’re just starting out or looking to pivot your career, the field of Analytics Engineering offers a rewarding path for those eager to make a significant impact in the way organizations leverage data.</p><h3>References</h3><ul><li><a href="https://blog.pragmaticengineer.com/what-is-data-engineering/">https://blog.pragmaticengineer.com/what-is-data-engineering/</a></li><li><a href="https://handbook.gitlab.com/job-families/finance/analytics-engineer/">https://handbook.gitlab.com/job-families/finance/analytics-engineer/</a></li><li><a href="https://www.altexsoft.com/blog/analytics-engineer/">https://www.altexsoft.com/blog/analytics-engineer/</a></li><li><a href="https://www.getdbt.com/analytics-engineering/why">https://www.getdbt.com/analytics-engineering/why</a></li><li><a href="https://dataform.co/blog/what-do-analytics-engineers-do">https://dataform.co/blog/what-do-analytics-engineers-do</a></li><li><a href="https://www.advancinganalytics.co.uk/blog/2022/11/30/introduction-to-analytics-engineering">https://www.advancinganalytics.co.uk/blog/2022/11/30/introduction-to-analytics-engineering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37a371a5136" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/exploring-analytics-engineering-insights-from-a-former-data-engineer-c37a371a5136">Exploring Analytics Engineering: Insights from a Former Data Engineer</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GeoPandas, GeoJSON, and MapBox: Unleashing the Power of Geospatial Data for Web Developers]]></title>
            <link>https://blog.devgenius.io/geopandas-geojson-and-mapbox-unleashing-the-power-of-geospatial-data-for-web-developers-bc7ee1f8cc25?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc7ee1f8cc25</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 19:18:55 GMT</pubDate>
            <atom:updated>2024-02-01T19:18:55.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5amK7GNUubaek-Y_5swiEQ.jpeg" /><figcaption>Photo from <a href="https://unsplash.com/photos/view-of-earth-and-satellite-yZygONrUBe8">NASA</a></figcaption></figure><h3>Introduction</h3><p>Recently, the combination of GeoJSON files and MapBox has become key in creating interactive maps for websites and apps. GeoJSON is a simple format that lets us show geographical details and data clearly. When used with MapBox, it opens up new ways to display maps that are both informative and engaging.</p><p>This article will guide you through updating GeoJSON files with new data and integrating them into MapBox. Our goal is to make this process easy for everyone, whether you’re just starting or have some experience. By the end, you’ll know how to use GeoJSON and MapBox together to make your maps more dynamic and interactive. Let’s dive in and discover how to enhance your mapping projects with these powerful tools.</p><h3>What is a GeoJson File</h3><p>GeoJSON is a format for storing geographical information in a way that’s easy to understand and use. It’s based on JSON, which is a common format for exchanging data on the web. GeoJSON lets you describe places on the earth, like cities, roads, or areas, and add details about those places. You can use it to make maps more interactive and informative by showing different locations and the data related to them. It’s a popular choice for web developers and map creators because it’s simple to work with and supported by many mapping tools, including MapBox.</p><p>Here is a basic example:</p><pre>{<br>  &quot;type&quot;: &quot;Feature&quot;,<br>  &quot;properties&quot;: {<br>    &quot;name&quot;: &quot;Best Coffee Shop&quot;,<br>    &quot;amenity&quot;: &quot;Coffee Shop&quot;,<br>    &quot;popupContent&quot;: &quot;This is where you get the best coffee!&quot;<br>  },<br>  &quot;geometry&quot;: {<br>    &quot;type&quot;: &quot;Point&quot;,<br>    &quot;coordinates&quot;: [-90.0715323, 29.951065]<br>  }<br>}</pre><p>Where:</p><ul><li><strong>&quot;type&quot;: &quot;Feature&quot;</strong> tells us that this GeoJSON object is a single geographic feature.</li><li><strong>&quot;properties&quot;</strong> contains information about the feature; here, we have the name of the coffee shop, its type (amenity), and content for a popup.</li><li><strong>&quot;geometry&quot;</strong> describes the feature&#39;s shape and location. In this case, it&#39;s a <strong>&quot;Point&quot;</strong> with specific longitude and latitude coordinates</li></ul><h3>What is GeoPandas</h3><p>GeoPandas is an open-source Python library that simplifies working with geospatial data by extending the popular pandas library to support geographic operations. It introduces the GeoDataFrame, a powerful tool for handling geospatial data similar to pandas’ DataFrame but optimized for geographic information. This includes support for points, lines, polygons, and more complex shapes representing real-world features.</p><p>With GeoPandas, users can easily perform tasks such as loading, analyzing, and visualizing spatial data, conducting spatial joins, manipulating geometries, and even creating maps directly from data. It integrates well with other geospatial libraries, making it a go-to choice for data scientists and geographers looking to conduct comprehensive geospatial analyses and visualizations in Python.</p><h3>Demo!</h3><p>In this demo, I will use a geospatial file publicly available in <a href="http://census.org/">Census.org</a> website. Unfortunately, I couldn’t find the GeoJSON file directly from this page. However, I will use some libraries to format the file into a GeoJSON format.</p><p>Additionally, I’ll use some data about COVID-19 statistics and add those as part of the properties of each region with GeoPandas!</p><p>Finally, I’ll use the GeoJSON file with MapBox and integrate it on a simple website with NodeJS.</p><p>Let’s start!</p><h4>Getting a GeoJson files from Census</h4><p>US Census provides a set of cartographic boundary files from their geographic database called MAF/TIGER. I downloaded the files that can give me the boundaries for all the US states.</p><p><strong>Link:</strong> <a href="https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html">https://www.census.gov/geographies/mapping-files/time-series/geo/carto-boundary-file.html</a></p><p>After I downloaded, I got different files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RtfxUY_mNycFFVam0iv_A.png" /></figure><p>Let’s review some things about the files:</p><p><strong>Resolution (Detail Level):</strong></p><ul><li>The <strong>500k</strong>, <strong>5m</strong>, and <strong>20m</strong> in the file names refer to the level of detail or resolution of the geographic data.</li><li><strong>500k</strong> (500,000 scale) files have the highest level of detail, suitable for detailed analysis and mapping.</li><li><strong>5m</strong> (5,000,000 scale) files have a medium level of detail, useful for less detailed applications and larger scale maps.</li><li><strong>20m</strong> (20,000,000 scale) files have the lowest level of detail, suitable for overview maps or applications where detailed geographic information is not critical.</li></ul><p><strong>File Formats:</strong></p><p><strong>.shp — Shape Format File: </strong>This is the primary file that stores the geometry of all features (like points, lines, and polygons). In this case, it contains the geometric boundaries of U.S. states.</p><p><strong>.shx — Shape Index File: </strong>This file acts as an index for the <strong>.shp</strong> file. It allows GIS software to quickly find the position of each feature within the <strong>.shp</strong> file. This is crucial for efficiently accessing and rendering the geographic data.</p><p><strong>.dbf — dBASE Table: </strong>This file contains attribute data for each shape in the <strong>.shp</strong> file. It&#39;s essentially a table where each row corresponds to a shape and each column represents an attribute (like the name of a state, population, etc.).</p><p><strong>.prj — Projection File: </strong>This file contains information about the coordinate system and projection parameters used for the shape data. It ensures that the geographic data aligns correctly with other spatial data layers in a GIS.</p><p><strong>.cpg — Code Page File: </strong>This file specifies the character encoding used in the <strong>.dbf</strong> file. It&#39;s important for correctly displaying text that might include special characters (like accents or characters from non-English alphabets).</p><p><strong>.shp.ea.iso.xml and .shp.iso.xml — Metadata Files: </strong>These XML files contain metadata about the Shapefile. Metadata can include information like the data’s origin, coordinate system, scale, resolution, and other relevant data descriptions. The <strong>.ea.iso.xml</strong> and <strong>.shp.iso.xml</strong> might have slightly different formats or adhere to different metadata standards.</p><h4>Converting Shape Format to GeoJson:</h4><p>You can convert shape files (.shp) to GeoJSON using the GDAL library in your terminal.</p><p>From its documentation, <em>GDAL is a translator library for raster and vector geospatial data formats that is released under an MIT style Open Source </em><a href="https://gdal.org/license.html#license"><em>License</em></a><em> by the </em><a href="http://www.osgeo.org/"><em>Open Source Geospatial Foundation</em></a><em>.</em></p><p>Let’s install it!</p><pre>brew install gdal</pre><p>Once GDAL has been installed, we can use the command ogr2ogr</p><pre>ogr2ogr -f &quot;GeoJSON&quot; cb_2018_us_state_20m.geojson cb_2018_us_state_20m.shp</pre><p>A new GeoJSON file cb_2018_us_state_20m.geojsonis created.</p><h4>Reading a GeoJSON file in Python with GeoPandas library</h4><p>In your Python virtual environment install the GeoPandas library</p><pre>pip3 install geopandas</pre><p>For instance, you can make a simple test to display the first 10 records.</p><pre>import geopandas as gpd<br><br># Read the GeoJson file into a DataFrame variable<br>df_geojson = gpd.read_file(&#39;cb_2018_us_state_20m.geojson&#39;,driver=&#39;GeoJSON&#39;)<br><br># Show the first 10 records<br>print(df_geojson.head(10))</pre><p>The data will look like this:</p><pre>STATEFP   STATENS     AFFGEOID GEOID STUSPS          NAME LSAD         ALAND       AWATER                                           geometry<br>0      24  01714934  0400000US24    24     MD      Maryland   00   25151100280   6979966958  MULTIPOLYGON (((-76.04621 38.02553, -76.00734 ...<br>1      19  01779785  0400000US19    19     IA          Iowa   00  144661267977   1084180812  POLYGON ((-96.62188 42.77925, -96.57794 42.827...<br>2      10  01779781  0400000US10    10     DE      Delaware   00    5045925646   1399985648  POLYGON ((-75.77379 39.72220, -75.75323 39.757...<br>3      39  01085497  0400000US39    39     OH          Ohio   00  105828882568  10268850702  MULTIPOLYGON (((-82.86334 41.69369, -82.82572 ...<br>4      42  01779798  0400000US42    42     PA  Pennsylvania   00  115884442321   3394589990  POLYGON ((-80.51989 40.90666, -80.51964 40.987...<br>5      31  01779792  0400000US31    31     NE      Nebraska   00  198956658395   1371829134  POLYGON ((-104.05314 41.11446, -104.05245 41.2...<br>6      53  01779804  0400000US53    53     WA    Washington   00  172112588220  12559278850  MULTIPOLYGON (((-123.23715 48.68347, -123.0704...<br>7      72  01779808  0400000US72    72     PR   Puerto Rico   00    8868896030   4922382562  MULTIPOLYGON (((-65.34207 18.34529, -65.25593 ...<br>8      01  01779775  0400000US01    01     AL       Alabama   00  131174048583   4593327154  POLYGON ((-88.46866 31.89386, -88.46866 31.933...<br>9      05  00068085  0400000US05    05     AR      Arkansas   00  134768872727   2962859592  POLYGON ((-94.61792 36.49941, -94.36120 36.499...</pre><p>Cool! Now we can update the external data (columns into our DataFrame).</p><h4>Adding new data to GeoJson</h4><p>For this example, I found a dataset on Kaggle containing COVID-19 statistics for all US states, including total cases and tests (Link: <a href="https://www.kaggle.com/datasets/anandhuh/usa-statewise-latest-covid19-data?select=USA+Covid+Data.csv">here</a>).</p><p>The next step, is to read the data (csv file) into a pandas DataFrame and join the data into the GeoPandas DataFrame. The following code contains the full process: reading GeoJson and csv external data and creating a new GeoJson file with the new data.</p><pre>import sys<br>import geopandas as gpd<br>import pandas as pd<br><br># Parameters<br>filename_geojson_input = &#39;cb_2018_us_state_20m.geojson&#39;<br>filename_data = &#39;covid_data_states.csv&#39;<br>filename_geojson_output = &#39;cb_2018_us_state_20m_covid.geojson&#39;<br><br># Read the GeoJson file into a DataFrame variable<br>df_geojson = gpd.read_file(filename_geojson_input,driver=&#39;GeoJSON&#39;)<br><br># Read the Datasets downloaded from Kaggle<br>df_state_data = pd.read_csv(filename_data)<br>column_data_mapping = {<br>    &#39;USA State&#39;:&#39;STATE_NAME&#39;,<br>    &#39;Total Cases&#39;:&#39;TOTAL_CASES&#39;,<br>    &#39;Total Deaths&#39;:&#39;TOTAL_DEATHS&#39;,<br>    &#39;Total Recovered&#39;:&#39;TOTAL_RECOVERED&#39;,<br>    &#39;Active Cases&#39;:&#39;ACTIVE_CASES&#39;,<br>    &#39;Tot Cases/ 1M pop&#39;:&#39;TOTAL_CASES_BY_1M_POP&#39;,<br>    &#39;Deaths/ 1M pop&#39;:&#39;TOTAL_DEATHS_BY_1M_POP&#39;,<br>    &#39;Total Tests&#39;:&#39;TOTAL_TESTS&#39;,<br>    &#39;Tests/ 1M pop&#39;:&#39;TOTAL_TESTS_BY_1M_POP&#39;,<br>    &#39;Population&#39;: &#39;POPULATION&#39;<br>}<br>df_state_data.rename(columns=column_data_mapping, inplace=True)<br><br># Add the state variables into the geojson dataframe<br>columns_chosen = [&#39;TOTAL_CASES&#39;,&#39;TOTAL_DEATHS&#39;,&#39;TOTAL_RECOVERED&#39;,&#39;ACTIVE_CASES&#39;,&#39;TOTAL_CASES_BY_1M_POP&#39;,&#39;TOTAL_DEATHS_BY_1M_POP&#39;,&#39;TOTAL_TESTS&#39;,&#39;TOTAL_TESTS_BY_1M_POP&#39;,&#39;STATE_NAME&#39;]<br>df_geojson_merged = df_geojson.merge(df_state_data[columns_chosen], how=&#39;left&#39;, left_on=&#39;NAME&#39;, right_on=&#39;STATE_NAME&#39;)<br><br># Export dataframe into a new geojson file<br>df_geojson_merged.to_file(filename_geojson_output, driver=&#39;GeoJSON&#39;)<br><br>print(f&quot;GeoJsonParser: {filename_geojson_output} generated&quot;</pre><p>Let’s take a sample of one state in the GeoJson:</p><pre>{<br>    &quot;type&quot;: &quot;FeatureCollection&quot;,<br>    &quot;crs&quot;: {<br>        &quot;type&quot;: &quot;name&quot;,<br>        &quot;properties&quot;: {<br>            &quot;name&quot;: &quot;urn:ogc:def:crs:EPSG::4269&quot;<br>        }<br>    },<br>    &quot;features&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Feature&quot;,<br>            &quot;properties&quot;: {<br>                &quot;STATEFP&quot;: &quot;24&quot;,<br>                &quot;STATENS&quot;: &quot;01714934&quot;,<br>                &quot;AFFGEOID&quot;: &quot;0400000US24&quot;,<br>                &quot;GEOID&quot;: &quot;24&quot;,<br>                &quot;STUSPS&quot;: &quot;MD&quot;,<br>                &quot;NAME&quot;: &quot;Maryland&quot;,<br>                &quot;LSAD&quot;: &quot;00&quot;,<br>                &quot;ALAND&quot;: 25151100280,<br>                &quot;AWATER&quot;: 6979966958,<br>                &quot;TOTAL_CASES&quot;: 1394250.0,<br>                &quot;TOTAL_DEATHS&quot;: 16928.0,<br>                &quot;TOTAL_RECOVERED&quot;: 1371142.0,<br>                &quot;ACTIVE_CASES&quot;: 6180.0,<br>                &quot;TOTAL_CASES_BY_1M_POP&quot;: 230619.0,<br>                &quot;TOTAL_DEATHS_BY_1M_POP&quot;: 2800.0,<br>                &quot;TOTAL_TESTS&quot;: 25094995.0,<br>                &quot;TOTAL_TESTS_BY_1M_POP&quot;: 4150897.0,<br>                &quot;STATE_NAME&quot;: &quot;Maryland&quot;<br>            },<br>            &quot;geometry&quot;: {<br>                &quot;type&quot;: &quot;MultiPolygon&quot;,<br>                &quot;coordinates&quot;: [<br>                    [<br>                        [<br>                            [<br>                                -76.046213,<br>                                38.025533<br>                            ],<br>                            [<br>                                -76.007337,<br>                                38.036706<br>                            ],<br>                            [<br>                                -75.980089,<br>                                38.004891<br>                            ],<br>                            [<br>                                -75.984648,<br>                                37.938121<br>                            ], ...<br>                        ]<br>                    ]<br>                ]<br>            }<br>        },<br>    ]<br>}</pre><p>Excellent! Now the GeoJSON file contains extra data that we can display on a map!</p><h3>Creating a simple map with MapBox and NodeJS</h3><p><a href="https://www.mapbox.com/"><strong>MapBox</strong></a> is a mapping and location cloud platform for developers, offering tools to create custom maps and location-based services.</p><p><a href="https://www.mapbox.com/mapbox-studio"><strong>MapBox Studio</strong></a> is a user-friendly tool that allows for the customization of maps, styles, layers, and data. It enables users to create unique map experiences by adjusting visual elements and incorporating personal data, ideal for web and mobile applications. Important features to know for this demo:</p><ul><li>Styles: here you can create your custom maps based on some templates and customize the layers before integrating with your app.</li><li>Tilesets: is your custom GeoJson file, it contains all the tiles with some static metadata in it (like our new COVID-19 data).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwMtbuCWuz2GwdYGnP1vww.png" /><figcaption>Image from <a href="https://www.lostcreekdesigns.co/writing/tilesets-and-datasets-managing-data-in-mapbox-studio/">lostcreekdesigns.co</a></figcaption></figure><p>In this case, due the size and scale used in this GeoJSON, we can use the <strong>Free Tier</strong> of MapBox without any problem 🙂</p><h4><strong>Adding Tileset</strong></h4><p>The process is pretty straightforward in MapBox Studio. Go to <em>Tilesets</em> and upload your GeoJson file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94bxWETG7Ami4o9ipHyysA.png" /></figure><h4><strong>Creating Style</strong></h4><p>Here I’m going to use a custom template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVwpzwrrn2_7gWhZl65l8Q.png" /></figure><p>Inside the style, I’ll add the tileset as a new custom layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZ7Yax2h7pg-USjFS7ibZA.png" /></figure><p>Finally, I add some style properties for borders and filled colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLSpC61ONPgTO8kzrP54Sg.png" /></figure><h4><strong>Integrating the Map into a NodeJs</strong></h4><p>Now, I will create a really basic NodeJS (I got some help from ChatGPT for the CSS due I didn’t want to waste some time on it hehe).</p><p>First the commands to create the NodeJS app and the required packages.</p><pre>npm init<br>npm install --save express<br>npm install --save pug<br>npm install --save dotenv<br>npm install --save mapbox-gl</pre><p>On my <a href="https://github.com/luismirandad27/se-nodejs-mapbox-geopandas-integration/tree/main"><strong>GitHub Repo</strong></a>, you can see the full NodeJS project. Here are some important considerations:</p><p>1- To integrate mapbox with you app, you’ll need an API token. After you published the map and when you want to share the map you will see that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zFbO9IAgFDDGWmyL7HA6w.png" /></figure><p>2- This token will be store in my .env file, that’s why I’m using the dotenvpackage. In the app.js, I’ll pass the token to the get endpoint:</p><pre>app.get(&quot;/&quot;,(req,res)=&gt;{<br>    res.render(&quot;index&quot;, { mapboxAccessToken: process.env.MAPBOX_ACCESS_TOKEN });<br>});</pre><p>3- The token will be send to the HTML file (in this case, I’m using pug). If I want to pass the value to the javascript file that is used in my pug file, I have to create a variable on the window object. By the way, you may find the CSS and JS files from MapBox as well.</p><pre>doctype html<br>html<br>  head<br>    title COVID-19 Statistics<br>    link(rel=&quot;stylesheet&quot;, href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css&quot;)<br>    link(rel=&quot;stylesheet&quot;, href=&quot;/static/css/style.css&quot;)<br>    link(rel=&quot;stylesheet&quot;, href=&quot;https://api.mapbox.com/mapbox-gl-js/v3.1.2/mapbox-gl.css&quot;)<br>  body<br>    include includes/header<br><br>    block content<br><br>    include includes/footer<br>    script.<br>      window.mapboxAccessToken = &quot;#{mapboxAccessToken}&quot;;<br>    script(src=&quot;https://api.mapbox.com/mapbox-gl-js/v3.1.2/mapbox-gl.js&quot;)<br>    script(src=&quot;/static/js/mapbox.js&quot;)</pre><p>Finally, here is the javascript code to integrate MapBox on your HTML (/public/js/mapbox.js).</p><pre>// Just to format the numbers into Thousands (K) and Millions (M)<br>function formatNumber(num) {<br>    if (num &gt;= 1000000) {<br>        return (num / 1000000).toFixed(1) + &#39;M&#39;;<br>    } else if (num &gt;= 1000) {<br>        return (num / 1000).toFixed(1) + &#39;K&#39;;<br>    } else {<br>        return num.toString();<br>    }<br>}<br><br>// Adding the mapbox token into the correspondent variable<br>mapboxgl.accessToken = window.mapboxAccessToken;<br>const map = new mapboxgl.Map({<br>    container: &#39;map&#39;, // container (div) ID on your HTML<br>    style: &#39;mapbox://styles/luismirandad27/cls155ejw00bd01pofo5bae4f&#39;, // style URL<br>    center: [-98.5795, 39.8283],<br>    zoom: 3 <br>});<br><br>// Adding zoom and rotation control map<br>map.addControl(new mapboxgl.NavigationControl());<br><br>// Click event State Boundaries<br>map.on(&quot;click&quot;, &quot;covid-19-boundaries&quot;, (e) =&gt; {<br> <br>  // Important: getting the properties based on the boundaries clicked<br>    const properties = e.features[0]?.properties;<br> <br>  // Adding the popup<br>    new mapboxgl.Popup()<br>        .setLngLat(e.lngLat)<br>        .setHTML(<br>            `<br>            &lt;h4 class=&quot;popup-title&quot;&gt;${properties.NAME}&lt;/h4&gt;<br>            &lt;div class=&quot;popup-stats&quot;&gt;<br>                &lt;div class=&quot;popup-stat&quot;&gt;<br>                    &lt;span class=&quot;popup-stat-label&quot;&gt;Total Cases:&lt;/span&gt;<br>                    &lt;span class=&quot;popup-stat-value&quot;&gt;${formatNumber(properties.TOTAL_CASES)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;popup-stat&quot;&gt;<br>                    &lt;span class=&quot;popup-stat-label&quot;&gt;Total Deaths:&lt;/span&gt;<br>                    &lt;span class=&quot;popup-stat-value&quot;&gt;${formatNumber(properties.TOTAL_DEATHS)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;popup-stat&quot;&gt;<br>                    &lt;span class=&quot;popup-stat-label&quot;&gt;Total Recovered:&lt;/span&gt;<br>                    &lt;span class=&quot;popup-stat-value&quot;&gt;${formatNumber(properties.TOTAL_RECOVERED)}&lt;/span&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;popup-stat&quot;&gt;<br>                    &lt;span class=&quot;popup-stat-label&quot;&gt;Total Tests:&lt;/span&gt;<br>                    &lt;span class=&quot;popup-stat-value&quot;&gt;${formatNumber(properties.TOTAL_TESTS)}&lt;/span&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;`<br>        )<br>        .addTo(map);<br>});</pre><p>Finally, let’s run the app with the command node app.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQykLSPA-vsN-QPnDQQLQA.png" /></figure><p>Aweeeeeeesoooooooome!</p><h3>Conclusion</h3><p>In conclusion, integrating GeoJSON files with MapBox offers a powerful and flexible approach to creating interactive maps that can significantly enhance web and mobile applications. By updating GeoJSON files with dynamic data, such as COVID-19 statistics, and leveraging the capabilities of GeoPandas for data manipulation, we unlock new dimensions of geospatial visualization. The process, from obtaining and converting geospatial data to embedding enriched maps into applications using NodeJS, demonstrates the accessibility and potential of modern mapping technologies.</p><h4><strong>Some resources:</strong></h4><ul><li><a href="https://docs.mapbox.com/mapbox-gl-js/guides/">Mapbox GL JS</a></li><li><a href="https://docs.mapbox.com/mapbox-gl-js/example/popup/">Display a popup | Mapbox GL JS</a></li><li><a href="https://geopandas.org/en/stable/docs.html">Documentation - GeoPandas 0+untagged.50.g5558c35.dirty documentation</a></li></ul><h3>By the way…</h3><p><em>👏 Don’t forget to clap for this article if you enjoyed it! Your support means a lot and helps me keep creating content. Also, make sure to follow me here on Medium to stay updated with my upcoming articles. Thank you for reading and for your continued support!</em></p><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc7ee1f8cc25" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/geopandas-geojson-and-mapbox-unleashing-the-power-of-geospatial-data-for-web-developers-bc7ee1f8cc25">GeoPandas, GeoJSON, and MapBox: Unleashing the Power of Geospatial Data for Web Developers</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing NLQ: Streamlined Integration of LLMs and Databases with LangChain]]></title>
            <link>https://medium.com/@lmirandad27/enhancing-nlq-streamlined-integration-of-llms-and-databases-with-langchain-74ecdefecf0a?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/74ecdefecf0a</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 08:39:00 GMT</pubDate>
            <atom:updated>2024-01-21T08:39:00.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKCDXpKuANP-g9rsL6GjuA.jpeg" /><figcaption>Photo from <a href="https://deepnote.com/@abid/Langchain-Tutorial-aad1f7d6-89c5-4d60-ac0c-7672f697d980">Abid Ali Awan</a></figcaption></figure><h3>Introduction</h3><p>In the past few months, Large Language Models (LLMs) have captured my attention, marking a significant advancement in the field of artificial intelligence, especially in natural language processing. These advanced AI models, known for their ability to achieve general-purpose language understanding and generation, learn from vast amounts of text data through a computationally intensive training process. As artificial neural networks following a transformer architecture, LLMs have transformed how we interact with and process language data.</p><p>However, the true potential of LLMs extends far beyond just understanding and generating language. For businesses and non-profit organizations alike, the ability to effectively harness these models can be a game-changer, particularly when integrated with their data.</p><p>This blog post aims to delve into the integration of LLMs with one database (Snowflake) with an interesting framework recently launched and it’s pretty useful for these implementations: LangChain.</p><h3>Some definitions</h3><h4>Large Language Models (LLM)</h4><p>LLMs are a type of language model distinguished by their vast scale and ability to process and generate human language. They are built on the principles of machine learning and rely on large amounts of data to learn language patterns, syntax, semantics, and context.</p><p>Some example that you would find familiar are:</p><ul><li>GPT (OpenAI)</li><li>LLaMA (Facebook)</li><li>BERT (Google)</li><li>ERNIE (Baidu)</li></ul><p>An example of a straightforward application for a Large Language Model (LLM) like ChatGPT is as a chatbot, which I assume you’re already familiar with. One way to incorporate an LLM into your solutions is by utilizing API endpoints to set up and utilize the LLM model, often after customizing it through ad-hoc training.</p><p>Now, let’s discuss how you can use this LLM to interact with your data. In this scenario, you would employ the LLM as a Natural Language Query (NLQ) tool. This means that when a user poses a question, such as “What is the total sales?” the model would generate an SQL query like “SELECT sum(tot_sale) FROM sales.” Subsequently, you can use this SQL query to retrieve the relevant data and display it within your application. While implementing this functionality may require some effort, this is where LangChain becomes essential in the process.</p><h4><strong>LangChain</strong></h4><p>An interesting definition that comes from <a href="https://aws.amazon.com/what-is/langchain/">AWS Documentation</a> is:</p><p><em>LangChain is an open source framework for building applications based on large language models (LLMs). It also includes components that </em><strong><em>allow LLMs to access new data sets without retraining</em></strong><em>.</em></p><p><strong>The last part is the key: integrating new data sets.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-zGQFGs_7n0FFIXYAPKoQ.png" /><figcaption>Image from <a href="https://www.linkedin.com/posts/sourabhsahu1_%3F%3F%3F-%3F%3F%3F%3F%3F-%3F%3F-%3F%3F%3F%3F%3F%3F-%3F-activity-7097397846030639104-HCsj/">Sourabh Sahu</a></figcaption></figure><p>For our approach of NLQ models, LangChain can help us with the following:</p><ul><li><strong>Parses natural language queries</strong> to understand user intent and extract relevant information.</li><li><strong>Maintains context</strong> from previous interactions for better understanding of follow-up queries.</li><li><strong>Connects with databases and knowledge bases</strong> for data retrieval based on natural language input (dialects).</li><li><strong>Handles a variety of query types</strong>, ranging from simple data requests to complex, multi-step queries.</li><li><strong>Generates human-like responses</strong> to make interactions intuitive and user-friendly.</li></ul><p>So, looks that we can integrate an LLM algorithm with our database in an easy manner. Well, let’s try it!</p><h3>Integrating a Snowflake database and OpenAI’s LLM with LangChain</h3><h4><strong>About the Data</strong></h4><p>I was collecting some data from 2 main sources: Census for demographic data and Zillow for estimated home values. The data has been stored into 2 tables in my Snowflake account hosted on AWS:</p><p><strong>census_data_zip_codes</strong>: stores the data of some demographic variables from <a href="https://data.census.gov/">US Census</a> per zip codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUF4Sd21FQezNF_ZKxJYig.png" /><figcaption>Census demographic data by US Zip code</figcaption></figure><p><strong>home_value_zillow_zip_codes: </strong>stores monthly data about estimated home values from <a href="https://www.zillow.com/research/data/">Zillow </a>by US Zip Codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TquAB25mjISrYEFRgTMgLA.png" /><figcaption>Zillow’s estimated home value (monthly basis) by US Zip code</figcaption></figure><h4>Application of the LangChain framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G66OYJeJJ1u8osszyWSSmA.png" /><figcaption>Architecture of LangChain framework for NLQ</figcaption></figure><p>In the following chart, I’m utilizing various components within the LangChain framework:</p><p><strong>SQL Agent:</strong> An intriguing element that offers flexible interaction with our database. According to <a href="https://python.langchain.com/docs/use_cases/qa_structured/sql">LangChain’s documentation</a>, it provides several advantages:</p><ul><li><em>It can respond to queries based on the database schema and the database’s content, such as describing a specific table.</em></li><li><em>It can recover from errors by running a generated query, capturing any errors, and regenerating it correctly.</em></li></ul><p>This component will possess the capability to perform tasks like creating and executing queries, validating query syntax, retrieving table descriptions, and more.</p><p><strong>Database Toolkit:</strong> Through this component, we enable the SQL agent to employ a specific LLM model (GPT) and connect to a database, in this instance, integrating with Snowflake.</p><p><strong>Vector DB:</strong> This is a noteworthy feature. With it, we can store examples in a database that are semantically similar to any new question posed. The underlying concept is based on a few-shot examples. In this case, I’m using a FAISS database, although other options like Milvus and Pinecone are also available.</p><p><strong>Retriever Tool:</strong> This component will manage the vector database efficiently.</p><h4>Creating a SQL Agent in Python with LangChain</h4><p>If I want to use this Agent for multiple purposes, I’ll create a python file called langchain_helper.py</p><p><strong>Creating a virtual environment</strong></p><pre>python -m venv myenv</pre><p><strong>Activate the virtual environment (example on MacOS)</strong></p><pre>source .venv/bin/activate</pre><p><strong>Install libraries</strong></p><pre>pip install langchain<br>pip install python-dotenv</pre><p>The second library is going to be useful for storing your credentials from both database and the LLM API Key (OpenAI’s API). <em>Please be aware that when considering OpenAI API integration, you may need to deposit funds into your account to cover usage costs.</em></p><p><strong>Importing Libraries</strong></p><pre>import os<br>import json<br>from dotenv import load_dotenv<br><br># LangChain Packages<br>from langchain.chat_models import ChatOpenAI<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.schema import Document<br>from langchain.tools.retriever import create_retriever_tool<br>from langchain_community.vectorstores import FAISS<br>from langchain_community.utilities import SQLDatabase<br>from langchain_community.agent_toolkits import SQLDatabaseToolkit<br>from langchain.agents import AgentType, create_sql_agent</pre><p>On the same location of the python file, create a .env file and store both database credentials and LLM (OpenAI in this case) API keys:</p><pre>OPENAI_API_KEY = &quot;your-openai-key&quot;<br>snowflake_account = &quot;your-snowflake-account&quot;<br>username = &quot;your-snowflake-username&quot;<br>password = &quot;your-snowflake-password&quot;<br>database= &quot;your-snowflake-database&quot;<br>schema = &quot;your-snowflake-schema&quot;<br>warehouse = &quot;your-snowflake-warehouse&quot;<br>role = &quot;your-snowflake-role&quot;</pre><p>The way you can get those variables in the python code is with the following:</p><pre>api_key = os.getenv(&#39;OPEN_API_KEY&#39;)</pre><p><strong>Create the Retriever Tool</strong></p><p>In this example, I’m going to add some few shot examples, so I can let the LLM to look for some similarities and make easier the inference.</p><p>Let’s define first <strong>few shot learning</strong>:</p><p><em>Few-shot learning is used to demonstrate a task with a small number of examples before asking the model to perform a similar task. This approach helps the model understand the context and the specific type of task required.</em></p><p>For this case, I’ll create a JSON file ( few_shots.json) with examples like these:</p><pre>{<br>    &quot;What is the total population of Alabama?&quot;:&quot;SELECT sum(tot_census_pop_2020) as \&quot;Total Population\&quot; FROM census_data_zip_codes  WHERE state_code = &#39;AL&#39;&quot;,<br>    &quot;Total number of zipcodes&quot;:&quot;SELECT COUNT(1) as \&quot;Total Number Zip Codes\&quot; FROM census_data_zip_codes&quot;,<br>    &quot;Highest estimate housing units by state&quot;:&quot;SELECT  state_code, MAX(tot_home_available_2021) as \&quot;Total Housing Units\&quot; FROM census_data_zip_codes GROUP BY state_code ORDER BY \&quot;Total Housing Units\&quot; DESC&quot;,<br>    &quot;Unemployment rate in Oklahoma&quot;:&quot;SELECT  round(avg(rt_unemployment*100),2) as \&quot;Unemployment Rate\&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;&quot;,<br>    &quot;In which state is located king county&quot;:&quot;SELECT DISTINCT state_code as \&quot;State Code\&quot; FROM census_data_zip_codes WHERE county_name LIKE &#39;%king%&#39; AND LOWER(county_name) LIKE &#39;%county%&#39;&quot;,<br>    &quot;in which zip code we have the lowest unemployment.&quot;:&quot;SELECT zip_code as \&quot;Zip Code\&quot;, round(MIN(rt_unemployment),2) as \&quot;Unemployment Rate\&quot; FROM census_data_zip_codes WHERE rt_unemployment is not NULL GROUP BY \&quot;Zip Code\&quot;&quot;,<br>    &quot;Show me the historical data of house prices on California of the last 5 years&quot;:&quot;select to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, avg(avg_home_value_price) as avg_home_value_price from home_value_zillow_zip_codes where state_code = &#39;CA&#39; and month_code &gt;= to_char(dateadd(year, -5, current_date()),&#39;yyyymm&#39;)::numeric group by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) order by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)&quot;<br>}</pre><p>I found this part crucial because even though the LLM could try to create SQL queries based on the context of my tables (metadata), there might be some scenarios where special treatment on the data should be done.</p><p>Now, let’s create the retriever tool (remember, it will require a vector DB, I’ll use FAISS):</p><pre><br>def create_retriever_tool():<br><br>   embeddings = OpenAIEmbeddings()<br>   <br>   with open(&#39;few_shots.json&#39;,&#39;r&#39;) as file:<br>       few_shots = json.load(file)<br>   <br>   few_shot_docs = [<br>       Document(page_content=question, metadata={&#39;sql_query&#39;: few_shots[question]})<br>       for question in few_shots.keys()<br>   ]<br>   <br>   vector_db = FAISS.from_documents(few_shot_docs, embeddings)<br>   retriever = vector_db.as_retriever()<br>   <br>   tool_description = &quot;&quot;&quot;<br>    This tool will help you understand similar examples to adapt them to the user question.<br>    Input to this tool should be the user question.<br>   &quot;&quot;&quot;<br>   <br>   retriever_tool = create_retriever_tool(<br>       retriever, name=&quot;sql_get_similar_examples&quot;, description=tool_description<br>   )<br>   <br>   custom_tool_list = [retriever_tool]<br>  <br>   return custom_tool_list</pre><p>This function generates a vector database using the OpenAIEmbeddings module. It creates a list of Document objects, where each Document represents a question with its metadata (SQL query). It then uses the FAISS module to create a vector database from these documents and returns a retriever object. Finally, we return the tool as a list.</p><p><strong>Create the SQL Agent</strong></p><pre>def langchain_sql_agent():<br><br>    custom_tool_list = generate_retriever_tool()<br>    <br>    snowflake_url = f&quot;snowflake://{os.getenv(&#39;username&#39;)}:{os.getenv(&#39;password&#39;)}@{os.getenv(&#39;snowflake_account&#39;)}/{os.getenv(&#39;database&#39;)}/{os.getenv(&#39;schema&#39;)}?warehouse={os.getenv(&#39;warehouse&#39;)}&amp;role={os.getenv(&#39;role&#39;)}&quot;<br>  <br>    db = SQLDatabase.from_uri(snowflake_url,sample_rows_in_table_info=1, include_tables=[&#39;census_data_zip_codes&#39;,&#39;home_value_zillow_zip_codes&#39;])<br>    llm = ChatOpenAI(temperature=0, verbose=True, model=&quot;gpt-4-1106-preview&quot;, openai_api_key = os.getenv(&#39;OPENAI_API_KEY&#39;))<br>  <br>    toolkit = SQLDatabaseToolkit(db=db, llm=llm)<br>  <br>    custom_suffix = &quot;&quot;&quot;<br>                    I should first get the similar examples I know.<br>                    If the examples are enough to construct the query, I can build it.<br>                    Otherwise, I can then look at the tables in the database to see what I can query.<br>                    Then I should query the schema of the most relevant tables<br>                    &quot;&quot;&quot;<br>    <br>    agent = create_sql_agent(<br>        llm=llm,<br>        toolkit=toolkit,<br>        verbose=True,<br>        agent_type=AgentType.OPENAI_FUNCTIONS,<br>        extra_tools=custom_tool_list,<br>        suffix=custom_suffix,<br>    )<br>  <br>    return agent</pre><p>The way I’m connecting to Snowflake is by using the from_uri method from SQLDatabase module.</p><p>The interesting part is the custom_suffix variable. With this, we are able to tell the model to follow a recipe to solve any type of question:<em> if the few shot examples are not enough for the new question, it will look on the description of the tables.</em></p><p><strong>Invoking the Agent</strong></p><p>This is where your expertise in <strong>prompt engineering</strong> comes into play. When activating the agent, it’s crucial to include a <strong>prompt template</strong> in the model to help it grasp the general context of the situation and effectively address the query. You can refer to the LangChain documentation for some established standards. However, I stumbled upon an intriguing example in a blog by <a href="https://dev.to/ngonidzashe">Ngonidzashe Nzenze</a> regarding the art of asking questions and allowing the model to provide the most suitable representation of data in charts.</p><p>For instance, if a user inquires, “<em>what are the home values in Los Angeles for the past 2 years</em>,” it would be more beneficial to present the information in a line chart rather than plain text, wouldn’t it? In such cases, we can rely on the model to offer suggestions for visualization.</p><pre>def invoke_llm(agent, query):<br><br>    prompt = (<br>        &quot;&quot;&quot;<br>            For the following query, if it requires drawing a table, reply as follows:<br>            {&quot;table&quot;: {&quot;columns&quot;: [&quot;column1&quot;, &quot;column2&quot;, ...], &quot;data&quot;: [[value1, value2, ...], [value1, value2, ...], ...]}}<br><br>            If the query requires creating a bar chart, reply as follows:<br>            {&quot;bar&quot;: {&quot;columns&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, ...], &quot;data&quot;: [25, 24, 10, ...]}}<br><br>            If the query requires creating a line chart, reply as follows:<br>            {&quot;line&quot;: {&quot;columns&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, ...], &quot;data&quot;: [25, 24, 10, ...]}}<br><br>            There can only be two types of chart, &quot;bar&quot; and &quot;line&quot;.<br><br>            Do not apply any LIMIT in the query.<br><br>            If it is just asking a question that requires neither, reply as follows:<br>            {&quot;answer&quot;: &quot;answer&quot;}<br>            Example:<br>            {&quot;answer&quot;: &quot;The title with the highest rating is &#39;Gilead&#39;&quot;}<br><br>            If you do not know the answer, reply as follows:<br>            {&quot;answer&quot;: &quot;I do not know.&quot;}<br><br>            Return all output as a string.<br><br>            All strings in &quot;columns&quot; list and data list, should be in double quotes,<br><br>            For example: {&quot;columns&quot;: [&quot;title&quot;, &quot;ratings_count&quot;], &quot;data&quot;: [[&quot;Gilead&quot;, 361], [&quot;Spider&#39;s Web&quot;, 5164]]}<br><br>            Lets think step by step.<br><br>            Please ensure that the response is in json format without getting issue of formatting while applying json.loads()<br><br>            Below is the query.<br>            Query: <br>            &quot;&quot;&quot;<br>        + query<br>    )<br><br>    response = agent.run(prompt)<br><br>    return response.__str__()</pre><p>If the query is ok, the expected response from the agent would be:</p><pre>{&quot;line&quot;: {&quot;columns&quot;: [&quot;month&quot;, &quot;house_prices&quot;], &quot;data&quot;: [[&quot;2021-10&quot;, 547471.77], [&quot;2021-11&quot;, 549425.23], [&quot;2021-12&quot;, 553406.96], [&quot;2022-01&quot;, 562396.60], [&quot;2022-02&quot;, 575773.43], [&quot;2022-03&quot;, 592884.54], [&quot;2022-04&quot;, 608388.92], [&quot;2022-05&quot;, 619837.69], [&quot;2022-06&quot;, 624512.40], [&quot;2022-07&quot;, 621768.00], [&quot;2022-08&quot;, 613230.24], [&quot;2022-09&quot;, 602367.29], [&quot;2022-10&quot;, 594283.63], [&quot;2022-11&quot;, 588949.44], [&quot;2022-12&quot;, 584855.19], [&quot;2023-01&quot;, 579647.57], [&quot;2023-02&quot;, 574964.50], [&quot;2023-03&quot;, 571756.67], [&quot;2023-04&quot;, 571002.11], [&quot;2023-05&quot;, 572488.67], [&quot;2023-06&quot;, 575576.55], [&quot;2023-07&quot;, 579428.44], [&quot;2023-08&quot;, 583285.40], [&quot;2023-09&quot;, 586455.84], [&quot;2023-10&quot;, 589043.73]]}}</pre><p>We can play with the key/values from the object and make the chart!</p><p>For example, you can create your <strong>app with Streamlit</strong> to test this if you like. The code should be done like this (main.py):</p><pre>import langchain_helper as lch<br>import streamlit as st<br>import json<br>import pandas as pd<br>import altair as alt<br><br># Creating the LangChain SQL Agent<br>llm_agent = lch.langchain_sql_agent()<br><br>st.title(&quot;Questions with LLM powered by Snowflake&quot;)<br><br>query = st.text_area(&quot;Insert your query&quot;)<br><br>if st.button(&quot;Run&quot;):<br>    <br>    response = lch.invoke_llm(llm_agent, query)<br>    <br>    # Special data cleansing of the response (just in case...)<br>    response_cleaned = response.replace(&#39;```json\n&#39;,&#39;&#39;).replace(&#39;\n```&#39;,&#39;&#39;)<br>    json_response = json.loads(response_cleaned)<br><br>    main_key = list(json_response.keys())[0]<br><br>    if main_key == &#39;answer&#39;:<br>        st.write(&quot;API Response (Answer):&quot;, json_response[&#39;answer&#39;])<br><br>    elif main_key == &#39;line&#39;:<br>        st.write(&quot;API Response (Line Chart):&quot;)<br>        <br>        # Extracting columns and data<br>        line_data = json_response[&#39;line&#39;][&#39;data&#39;]<br>        columns = json_response[&#39;line&#39;][&#39;columns&#39;]<br>        values = [item[1] for item in json_response[&#39;line&#39;][&#39;data&#39;]] <br><br>        # Create DataFrame<br>        df_line = pd.DataFrame(line_data, columns=[columns[0], columns[1]])<br><br>        # Create the chart<br>        chart = alt.Chart(df_line).mark_line().encode(<br>            x=columns[0], <br>            y=alt.Y(columns[1], scale=alt.Scale(domain=(min(values), max(values))))<br>        )<br><br>        # Display the chart in Streamlit<br>        st.altair_chart(chart, use_container_width=True)<br><br>    elif main_key == &#39;table&#39;:<br>        st.write(&quot;API Response (Table):&quot;)<br>        data = json_response[&#39;table&#39;][&#39;data&#39;]<br>        columns = json_response[&#39;table&#39;][&#39;columns&#39;]<br>  <br>        # Convert numeric columns to float<br>        for i, column in enumerate(columns):<br>            try:<br>                data = [[row[0], float(row[1])] if i == columns.index(&#39;numeric_column_name&#39;) else row for row in data]<br>            except ValueError:<br>                pass<br>        <br>        df_data = pd.DataFrame(data, columns = json_response[&#39;table&#39;][&#39;columns&#39;])<br>        st.write(df_data)</pre><h4>Demonstration</h4><p>Let’s run the Streamlit app:</p><pre>streamlit run main.py</pre><p><strong>Question1: “Show<em> me the evolution of home values in zip 98001”</em></strong><em>.</em></p><p>This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Nte6XrrV9xwZL0Adl78kQ.png" /><figcaption>Evolution of home values by month</figcaption></figure><p>Let’s see how the SQL agent ran:</p><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `sql_get_similar_examples` with `{&#39;query&#39;: &#39;Show me the evolution of home values in zip 98001&#39;}`<br><br><br>[Document(page_content=&#39;What is the evolution of prices of the zip code 98001&#39;, metadata={&#39;sql_query&#39;: &quot;SELECT to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month,avg(avg_home_value_price) as house_prices  FROM home_value_zillow_zip_codes GROUP BY to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) ORDER BY to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)&quot;}), Document(page_content=&#39;Show me the historical data of house prices on the zip_code 98001 of the last 14 months&#39;, metadata={&#39;sql_query&#39;: &quot;select to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, zip_code, avg(avg_home_value_price) as avg_home_value_price from home_value_zillow_zip_codes where zip_code = &#39;98001&#39; and month_code &gt;= to_char(dateadd(month, -14, current_date()),&#39;yyyymm&#39;)::numeric group by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;), zip_code order by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)&quot;}), Document(page_content=&#39;Show me the historical data of house prices on California of the last 5 years&#39;, metadata={&#39;sql_query&#39;: &quot;select to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, avg(avg_home_value_price) as avg_home_value_price from home_value_zillow_zip_codes where state_code = &#39;CA&#39; and month_code &gt;= to_char(dateadd(year, -5, current_date()),&#39;yyyymm&#39;)::numeric group by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) order by to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)&quot;}), Document(page_content=&#39;Total number of zipcodes&#39;, metadata={&#39;sql_query&#39;: &#39;SELECT COUNT(1) as &quot;Total Number Zip Codes&quot; FROM exploration.exp_matrix_variable_score_llm&#39;})]<br>Invoking: `sql_db_query_checker` with `SELECT to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, avg(avg_home_value_price) as house_prices FROM home_value_zillow_zip_codes WHERE zip_code = &#39;98001&#39; GROUP BY to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) ORDER BY to_char(to_date(month_code::string,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)`<br><br><br>The provided query does not seem to contain any of the common mistakes listed. However, there is a small correction needed in the `to_date` function. The `to_date` function expects a string as the first argument, but `month_code` is being cast to a string using `::string` which is not the correct syntax in Snowflake. Instead, you should use `::VARCHAR` or `CAST(month_code AS VARCHAR)`. Also, the `avg_home_value_price` should be wrapped in the `AVG` function to calculate the average. Here is the corrected query:<br><br>```sql<br>SELECT <br>  to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, <br>  AVG(avg_home_value_price) as house_prices <br>FROM <br>  home_value_zillow_zip_codes <br>WHERE <br>  zip_code = &#39;98001&#39; <br>GROUP BY <br>  to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) <br>ORDER BY <br>  to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;);<br>```<br>Invoking: `sql_db_query` with `SELECT to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) as month, AVG(avg_home_value_price) as house_prices FROM home_value_zillow_zip_codes WHERE zip_code = &#39;98001&#39; GROUP BY to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;) ORDER BY to_char(to_date(month_code::VARCHAR,&#39;YYYYMM&#39;),&#39;YYYY-MM&#39;)`<br><br><br>[(&#39;2021-10&#39;, Decimal(&#39;547471.768800000000&#39;)), (&#39;2021-11&#39;, Decimal(&#39;549425.228900000000&#39;)), (&#39;2021-12&#39;, Decimal(&#39;553406.964500000000&#39;)), (&#39;2022-01&#39;, Decimal(&#39;562396.600000000000&#39;)), (&#39;2022-02&#39;, Decimal(&#39;575773.432600000000&#39;)), (&#39;2022-03&#39;, Decimal(&#39;592884.543300000000&#39;)), (&#39;2022-04&#39;, Decimal(&#39;608388.917100000000&#39;)), (&#39;2022-05&#39;, Decimal(&#39;619837.693700000000&#39;)), (&#39;2022-06&#39;, Decimal(&#39;624512.402700000000&#39;)), (&#39;2022-07&#39;, Decimal(&#39;621768.001000000000&#39;)), (&#39;2022-08&#39;, Decimal(&#39;613230.239700000000&#39;)), (&#39;2022-09&#39;, Decimal(&#39;602367.288200000000&#39;)), (&#39;2022-10&#39;, Decimal(&#39;594283.630300000000&#39;)), (&#39;2022-11&#39;, Decimal(&#39;588949.441500000000&#39;)), (&#39;2022-12&#39;, Decimal(&#39;584855.186500000000&#39;)), (&#39;2023-01&#39;, Decimal(&#39;579647.565700000000&#39;)), (&#39;2023-02&#39;, Decimal(&#39;574964.503200000000&#39;)), (&#39;2023-03&#39;, Decimal(&#39;571756.665700000000&#39;)), (&#39;2023-04&#39;, Decimal(&#39;571002.112200000000&#39;)), (&#39;2023-05&#39;, Decimal(&#39;572488.665400000000&#39;)), (&#39;2023-06&#39;, Decimal(&#39;575576.554300000000&#39;)), (&#39;2023-07&#39;, Decimal(&#39;579428.438000000000&#39;)), (&#39;2023-08&#39;, Decimal(&#39;583285.396800000000&#39;)), (&#39;2023-09&#39;, Decimal(&#39;586455.837200000000&#39;)), (&#39;2023-10&#39;, Decimal(&#39;589043.727000000000&#39;))]```json<br>{&quot;line&quot;: {&quot;columns&quot;: [&quot;month&quot;, &quot;house_prices&quot;], &quot;data&quot;: [[&quot;2021-10&quot;, 547471.77], [&quot;2021-11&quot;, 549425.23], [&quot;2021-12&quot;, 553406.96], [&quot;2022-01&quot;, 562396.60], [&quot;2022-02&quot;, 575773.43], [&quot;2022-03&quot;, 592884.54], [&quot;2022-04&quot;, 608388.92], [&quot;2022-05&quot;, 619837.69], [&quot;2022-06&quot;, 624512.40], [&quot;2022-07&quot;, 621768.00], [&quot;2022-08&quot;, 613230.24], [&quot;2022-09&quot;, 602367.29], [&quot;2022-10&quot;, 594283.63], [&quot;2022-11&quot;, 588949.44], [&quot;2022-12&quot;, 584855.19], [&quot;2023-01&quot;, 579647.57], [&quot;2023-02&quot;, 574964.50], [&quot;2023-03&quot;, 571756.67], [&quot;2023-04&quot;, 571002.11], [&quot;2023-05&quot;, 572488.67], [&quot;2023-06&quot;, 575576.55], [&quot;2023-07&quot;, 579428.44], [&quot;2023-08&quot;, 583285.40], [&quot;2023-09&quot;, 586455.84], [&quot;2023-10&quot;, 589043.73]]}}<br>```<br><br>&gt; Finished chain.</pre><p>Looks good, it learned from my few shot examples.</p><p><strong>Question 2: <em>“What is the vacancy rate in average in Oklahoma?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdqtH-P-p1DdupqhcmhbLQ.png" /><figcaption>Vacancy Rate in Oklahoma</figcaption></figure><p>Let’s see what happened behind the scenes…</p><pre>&gt; Entering new AgentExecutor chain...<br><br>Invoking: `sql_get_similar_examples` with `{&#39;query&#39;: &#39;What is the vacancy rate in average in Oklahoma?&#39;}`<br><br><br>[Document(page_content=&#39;Unemployment rate in Oklahoma&#39;, metadata={&#39;sql_query&#39;: &#39;SELECT  round(avg(rt_unemployment*100),2) as &quot;Unemployment Rate&quot; FROM census_data_zip_codes WHERE state_code = \&#39;OK\&#39;&#39;}), Document(page_content=&#39;What is the total population of Alabama?&#39;, metadata={&#39;sql_query&#39;: &#39;SELECT sum(tot_census_pop_2020) as &quot;Total Population&quot; FROM census_data_zip_codes  WHERE state_code = \&#39;AL\&#39;&#39;}), Document(page_content=&#39;Highest estimate housing units by state&#39;, metadata={&#39;sql_query&#39;: &#39;SELECT  state_code, MAX(tot_home_available_2021) as &quot;Total Housing Units&quot; FROM census_data_zip_codes GROUP BY state_code ORDER BY &quot;Total Housing Units&quot; DESC&#39;}), Document(page_content=&#39;in which zip code we have the lowest unemployment.&#39;, metadata={&#39;sql_query&#39;: &#39;SELECT zip_code as &quot;Zip Code&quot;, round(MIN(rt_unemployment),2) as &quot;Unemployment Rate&quot; FROM census_data_zip_codes WHERE rt_unemployment is not NULL GROUP BY &quot;Zip Code&quot;&#39;})]<br>Invoking: `sql_db_query_checker` with `SELECT ROUND(AVG(rt_vacancy_rate*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;`<br><br><br>SQL Query:<br><br>```sql<br>SELECT ROUND(AVG(rt_vacancy_rate*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;;<br>```<br>Invoking: `sql_db_query` with `SELECT ROUND(AVG(rt_vacancy_rate*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;`<br><br><br>Error: (snowflake.connector.errors.ProgrammingError) 000904 (42000): SQL compilation error: error line 1 at position 17<br>invalid identifier &#39;RT_VACANCY_RATE&#39;<br>[SQL: SELECT ROUND(AVG(rt_vacancy_rate*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;]<br>(Background on this error at: https://sqlalche.me/e/14/f405)<br>Invoking: `sql_db_schema` with `census_data_zip_codes`<br><br><br>Error: table_names {&#39;census_data_zip_codes&#39;} not found in database<br>Invoking: `sql_db_list_tables` with ``<br><br><br>home_value_zillow_zip_codes, census_data_zip_codes<br>Invoking: `sql_db_schema` with `census_data_zip_codes`<br><br><br><br>CREATE TABLE census_data_zip_codes (<br>        zip_code VARCHAR(5), <br>        county_name VARCHAR(50), <br>        county_fips_code VARCHAR(5), <br>        city_name VARCHAR(50), <br>        state_code VARCHAR(2), <br>        tot_census_pop_2020 DECIMAL(38, 0), <br>        rt_unemployment DECIMAL(19, 8), <br>        avg_household_income_2021 DECIMAL(38, 0), <br>        tot_home_available_2021 DECIMAL(38, 0), <br>        avg_people_per_home DECIMAL(23, 6), <br>        rt_vacancy DECIMAL(19, 8)<br>)<br><br>/*<br>1 rows from census_data_zip_codes table:<br>zip_code        county_name     county_fips_code        city_name       state_code      tot_census_pop_2020     rt_unemployment avg_household_income_2021       tot_home_available_2021       avg_people_per_home     rt_vacancy<br>02295   Suffolk County  25025   Boston  MA      None    None    None    None    None    None<br>*/<br>Invoking: `sql_db_query_checker` with `SELECT ROUND(AVG(rt_vacancy*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;`<br><br><br>SQL Query:<br><br>```sql<br>SELECT ROUND(AVG(rt_vacancy*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;;<br>```<br>Invoking: `sql_db_query` with `SELECT ROUND(AVG(rt_vacancy*100), 2) AS &quot;Average Vacancy Rate&quot; FROM census_data_zip_codes WHERE state_code = &#39;OK&#39;`<br><br><br>[(Decimal(&#39;20.02&#39;),)]{&quot;answer&quot;: &quot;The average vacancy rate in Oklahoma is 20.02%.&quot;}</pre><p>Great! It appears that the model has identified a resemblance to my examples, but it encountered a syntax error because the column name inferred by the model doesn’t actually exist. Consequently, it proceeded to examine the complete list of columns within the tables using a small sample of data.</p><p>You can check the code on my <a href="https://github.com/luismirandad27/ds-nlq-langchain-llm-snowflake.git">GitHub repo</a>.</p><h3>Conclusions</h3><p>The integration of Large Language Models like OpenAI’s GPT with databases, using tools like LangChain with Snowflake, represents a significant advance in data processing. This approach makes complex data analysis more accessible, allowing natural language interactions with large datasets. The effectiveness of LangChain in parsing queries, maintaining context, and generating intuitive responses showcases the practical potential of these models in various applications.</p><p>As we look to the future, the fusion of LLMs with database technologies promises to further revolutionize data management and analysis. This advancement is not just a technical leap but also a step towards democratizing data access, enabling users of all skill levels to engage with complex data effortlessly. The evolving capabilities of these models suggest a promising direction for AI in enhancing data accessibility and decision-making processes.</p><h4>By the way…</h4><p><em>👏 Don’t forget to clap for this article if you enjoyed it! Your support means a lot and helps me keep creating content. Also, make sure to follow me here on Medium to stay updated with my upcoming articles. Thank you for reading and for your continued support!</em></p><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a></p><h4><a href="https://mlearning.substack.com/about">WRITER at MLearning.ai</a> / <a href="https://open.substack.com/pub/mlearning/p/hacking-gpts-store-undetectable-prompt-injection?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">Hacking GPTs Store</a> / <a href="https://open.substack.com/pub/mlearning/p/20k-ai-art-prompts-generator-guide-collection?r=z7zu8&amp;utm_campaign=post&amp;utm_medium=web">20K+ Art Prompts</a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74ecdefecf0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering CI with Dbt Seeds and Snowflake (Part 1/2)]]></title>
            <link>https://blog.devgenius.io/mastering-ci-with-dbt-seeds-and-snowflake-part-1-2-22f2d30bdc43?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/22f2d30bdc43</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 12:11:31 GMT</pubDate>
            <atom:updated>2024-01-14T12:11:31.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ce-4ecEMUVSAVkD3ZfZO8g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang">Julian Hochgesang</a> (<a href="https://unsplash.com/photos/time-lapse-photography-of-vehicles-3-y9vq8uoxk">unsplash.com</a>)</figcaption></figure><h3>1 Introduction</h3><p>Throughout my experience as an <strong>analytics engineer</strong>, I’ve learned the significance of selecting optimal tools that elevate data usability for end users. <strong>Dbt (Data Build Tool)</strong> shines as a standout SQL-focused tool in data engineering, famed for its smooth git integration, flexible code structure, and strong data testing capabilities.</p><p>While I’m not a software engineer, my somewhat “love-hate” relationship with coding has been transformed by dbt, enhancing my pipeline processes!</p><p>Curious about how dbt can revolutionize your data pipeline efficiency? These two articles delve into practical use cases, illustrating how dbt’s features can significantly improve our data modeling and loading techniques.</p><h3>2 A data architecture example for dbt application</h3><p>Prior to going forward into these specific use cases, I want to present the design of a Snowflake database tailored for these scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdWvP4TWjfIbI1gGIp5bcw.png" /><figcaption>Snowflake Datawarehouse Architecture</figcaption></figure><p>In the provided diagram, you can observe the structure of the Snowflake database, which is composed of four distinct schemas.</p><ul><li><strong>Landing</strong>: The primary focus of this article will be on this schema. It serves as the initial storage area for raw data incoming from external sources, like AWS S3 buckets, where it’s stored in various tables.</li><li><strong>Staging</strong>: This is a transitional space where raw data undergoes cleaning, transformation, or enrichment before being moved to a more permanent storage area, preparing it for the next processing steps.</li><li><strong>Analytics</strong>: Used for analytical processes, this schema organizes, aggregates, and stores data in a manner conducive to complex queries and data analysis tasks.</li><li><strong>Delivery</strong>: The final schema in the process, where processed and refined data is made accessible to end-users or applications, typically in a format that’s easy to use and interpret, ready for reporting or decision-making.</li></ul><p><strong>With dbt integrated with this architecture,</strong> we can create our data pipelines in multiple environments. It allows us to implement those workflows in a “dev” environment (database <strong>DB_DEV</strong>), testing deployments in a “qa” environment (database <strong>DB_QA</strong>), and running the production pipeline in a “prod” environment (database <strong>DB_PROD</strong>).</p><p>Additionally, in Snowflake, integrating our data from cloud storage to the tables involves the use of storage integrations and stages. This process involves copying the data to the designated tables.</p><p><strong>Consider the scenario of having numerous sources, which could translate to numerous stages.</strong> Managing all of these can be quite challenging, right?</p><p>Is there anything in dbt that I can use to manage and configure my pipelines/stages dynamically? <strong>Let’s talk about seeds.</strong></p><h3>3 About dbt seeds</h3><p>There are numerous beneficial applications for dbt seeds, such as creating tables for mapping state codes to names. Many examples provided in the <a href="https://docs.getdbt.com/docs/build/seeds">documentation</a> focus on scenarios relevant to business use cases.</p><p>The concept of seeds as explained on the dbt website is quite straightforward. Essentially, <strong>seeds are CSV files that can be directly loaded into our database</strong>. However, there’s an important aspect to consider: <strong>the data in these files should be static and subject to infrequent changes.</strong></p><p>Moreover, <strong>we can leverage these CSV files to customize the deployment of our dbt pipelines in Snowflake.</strong> In the following section, we’ll delve into this method in more detail.</p><h4><strong>Let’s dive in the use cases</strong></h4><p>The following questions are gonna drive these articles:</p><ol><li><strong>How can we create and maintain multiple integrations with different data files from different cloud storage providers in my data warehouse?</strong></li><li><strong>If I have static data, How can I move the data (copy) into my snowflake tables in one shot?</strong></li><li><strong>Can I do the previous steps automatically while I’m deploying my pipelines?</strong></li></ol><p>In Section 2, I briefly touched on integrating your data files into Snowflake tables using storage integration and stages. For instance, if we want to load several files into many tables, creating stages individually is not practical, so a dynamic approach is preferable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nc0-WFyFSw894D9kcs17Zg.png" /><figcaption>dbt Seeds and dbt Macros Strategy</figcaption></figure><p>From the diagram, our starting point involves establishing 2 dbt seeds:</p><ul><li><strong>Seed 1</strong> will handle the creation and maintenance of various Snowflake stages.</li><li><strong>Seed 2</strong> is designated for cataloging the columns of each raw table that needs to be filled with data, specifically for CSV file inputs.</li></ul><p>Following the creation of these seeds, we will develop 3 dbt macros (Jinja functions):</p><ul><li><strong>Macro 1</strong> will utilize the first seed to iteratively create Snowflake stages while concurrently updating the <strong>STORAGE_ALLOWED_LOCATION</strong> parameter in the storage integration.</li><li><strong>Macro 2</strong>’s role is to generate raw tables in the landing schema for each stage created by Macro 1. For stages linked to CSV files, it will refer to Seed 2 for structuring.</li><li><strong>Macro 3</strong>’s objective is to manage the data transfer from the files to the stages during deployment. This is specifically for tables that contain static data with rare updates.</li></ul><p>Once we have these three macros in place, we can then construct our CI Job using these steps and execute it in our other databases (such as DB_QA or DB_PROD).</p><h3>4 dbt Project and Snowflake’s Settings</h3><p>If you’re interested in trying out the example on your own, you can follow this step-by-step guide, or you may choose to bypass this section. However, it’s crucial to be aware that certain adjustments need to be made in the dbt project configuration.</p><h4><strong>a Initiate your dbt project, ensuring it’s connected with GitHub and Snowflake.</strong></h4><h4><strong>b Establish databases and schemas in Snowflake</strong></h4><p>Given that the macros will operate in different environments, it’s essential to include the environment’s abbreviation in the database name. For instance, I set up three databases: <strong>DB_DEV</strong>, <strong>DB_QA</strong>, and <strong>DB_PROD</strong>.</p><p>Regarding schemas, you should at least create a <strong>landing schema</strong>. While you’re not obligated to use the exact name “landing,” it is a commonly used term.</p><h4>c Creating S3 Buckets</h4><p>For the bucket where I’m going to store the files, it’s important, like in the previous requirement, to include the environment’s abbreviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ed5KQ_47AO0vrJhYNVK5Qw.png" /><figcaption>S3 Buckets created</figcaption></figure><h4><strong>d Creating Storage Integration</strong></h4><p>Three storage integrations should be created in Snowflake, one by environment. You can follow this standard:</p><pre>CREATE STORAGE INTEGRATION [CLOUD PROVIDER]_STG_INT_[ENVIRONMENT]<br>TYPE = EXTERNAL_STAGE<br>STORAGE_PROVIDER = &#39;S3&#39;<br>ENABLED = TRUE<br>STORAGE_AWS_ROLE_ARN = &#39;{your_role_arn}&#39;<br>STORAGE_ALLOWED_LOCATIONS = (&#39;s3://dummy-bucket/&#39;);</pre><p>Example: <strong>AWS_STG_INT_DEV</strong></p><p>Leave the placeholder ‘dummy-bucket’ as it is; the first macro will handle the necessary updates.</p><p>Regarding AWS integration, it’s necessary to set up certain policies and roles for accessing S3 buckets. I referred to the <a href="https://docs.snowflake.com/en/user-guide/data-load-s3-config-storage-integration">Snowflake documentation</a> for guidance on this, as it provides clear instructions.</p><h4><strong>e Extra configuration on dbt project</strong></h4><p>Three things we have to do as initial configurations on the dbt project:</p><p><strong>Create 2 environment variables</strong></p><p>These variables are related to the environment we are working on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsrNjgByJFbzizjkm2CcMQ.png" /><figcaption>Environment variables on dtb</figcaption></figure><p><strong>Overwrite the </strong><strong>generate_schema_name macro</strong></p><p>The main reason is to allow dbt to always use the database.schema names according to what we created on Snowflake (e.g. db_prod.landing.my_table)</p><pre>{% macro generate_schema_name(custom_schema_name, node) -%}<br><br>    {%- set default_schema = target.schema -%}<br><br>    {%- if custom_schema_name is none -%}<br><br>        {{ default_schema }}<br><br>    {%- else -%}<br><br>        {{ custom_schema_name | trim }}<br><br>    {%- endif -%}<br><br>{%- endmacro %}</pre><p><strong>Update the configuration of dbt seeds</strong></p><p>Basically, we need to assure that the seed tables must be created on the <strong>landing</strong> schema and the csv files are going to have a semicolon delimiter (I’ll talk about this in part 2).</p><pre>seeds:<br>  &lt;project_name&gt;:<br>    +schema: landing<br>    +delimiter: &quot;;&quot;</pre><h3>5 Creating the dbt seeds</h3><h4>Seed 1: seed_snowflake_stages.csv</h4><p>In the previous sections, I mentioned the purpose of this seed. The idea of this object is to create snowflake stages and raw tables with a standard naming convention, like the following examples:</p><pre>-- Stage Name<br>[SCHEMA NAME]_STAGE_[CLOUD PROVIDER]_[FORMAT FILE]_[ENVIRONMENT]_[SUFFIX NAME]<br><br>-- Table Name<br>RAW_[CLOUD PROVIDER]_[FORMAT FILE]_[SUFFIX NAME]</pre><p>Example for a stage and table created in db_dev in landing schema:</p><p>Stage: DB_DEV.LANDING.LANDING_STAGE_AWS_JSON_DEV_EARTH_METEORITE_LANDINGS_NASA</p><p>Table: RAW_AWS_JSON_EARTH_METEORITE_LANDINGS_NASA</p><p>Our macro will use this seed to mold the stage with those standards. The following table lists the columns from this seed:</p><pre>| Column                 | Description                                                                                                                                                 |<br>|------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|<br>| id                     | Id of the stage. Should be unique                                                                                                                           |<br>| type_stage             | Type of data to be staged. You can customize in a manner you would understand the purpose of the data. In this case, due it’s raw data, the value is “raw”. |<br>| cloud_storage_provider | Values allowed: aws, gcp, azure.                                                                                                                            |<br>| source_file_type       | File format file. Values allowed: csv, json.                                                                                                                |<br>| stage_name_suffix      | Suffix for the name of the table and stage.                                                                                                                 |<br>| delimiter              | Delimiter character (csv files only)                                                                                                                        |<br>| flg_strip_array        | Json files only. If the file is an array of JSON object the value should be 1.                                                                              |<br>| flg_active             | If the stage should remain active for the next deployment, keep the value as 1.                                                                             |<br>| flg_move_data          | If the data should be copy to the snowflake table in the deployment process, keep the value as 1.                                                           |<br>| flg_recreate           | If you need to re-update the stage (change the url) or the table (columns), keep the value as 1.                                                            |</pre><p>Review the seed on the GitHub Repo <a href="https://github.com/luismirandad27/de-dbt-seed-snowflake-integration/blob/main/seeds/seed_snowflake_stages.csv">here</a>.</p><h4><strong>Seed 2: seed_snowflake_raw_table_columns.csv</strong></h4><p>This seed is only for tables that receives CSV files, and it contains a very simple structure.</p><pre>| Column          | Description                                                                   |<br>|-----------------|-------------------------------------------------------------------------------|<br>| id              | id of the table. It should be linked to the id column from the previous seed. |<br>| column_position | Position number of the column in the snowflake table.                         |<br>| column_name     | Name of the column in the snowflake table.                                    |</pre><p>Review the seed on the GitHub Repo <a href="https://github.com/luismirandad27/de-dbt-seed-snowflake-integration/blob/main/seeds/seed_snowflake_raw_table_columns.csv">here</a>.</p><h3><strong>6 Conclusion</strong></h3><p>In this initial post, my objective was to showcase the organization of database(s) in Snowflake’s data warehouse. Additionally, Snowflake simplifies the process of incorporating data files from different cloud storages through storage integration and stages, we saw a straightforward approach to establish and manage these architectural elements.</p><p>In addition, we reviewed necessary preconditions and proposed naming conventions that might assist you and your team in effectively arranging your Snowflake integrations.</p><p>I hope this encourages you to move on to the part 2, where I will dive into more complex subjects with dbt :)</p><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22f2d30bdc43" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mastering-ci-with-dbt-seeds-and-snowflake-part-1-2-22f2d30bdc43">Mastering CI with Dbt Seeds and Snowflake (Part 1/2)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering CI with Dbt Seeds and Snowflake (Part 2/2)]]></title>
            <link>https://blog.devgenius.io/mastering-ci-with-dbt-seeds-and-snowflake-part-2-2-95d60e4d32ba?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d60e4d32ba</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 12:12:13 GMT</pubDate>
            <atom:updated>2024-01-13T12:12:13.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roYrSc5O5F5zw7YCSoYkhA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13">Joshua Aragon</a> (<a href="https://unsplash.com/photos/black-laptop-computer-naer-plant-on-brown-wooden-surface-azft6PuI3Ug">unsplash.com</a>)</figcaption></figure><h3>1 Overview</h3><p>In the preceding <a href="https://blog.devgenius.io/mastering-ci-with-dbt-seeds-and-snowflake-part-1-2-22f2d30bdc43">article</a>, I introduced the concept of utilizing a method for dynamically generating and sustaining Snowflake stages. This involves establishing dbt seeds for the upkeep of these stages, along with the creation of unprocessed tables for data file storage.</p><p>The final scenario entails developing a method for dynamically transferring data files into the Snowflake tables using an additional dbt macro. In this concluding article, I will delve into the execution of these macros and include an extra feature: integrating all these macros into a Continuous Integration (CI) Job in dbt.</p><h3>2 Reviewing the workflow</h3><p>Up to this point, I’ve talked about setting up the dbt project and organizing the databases and schemas in the Snowflake data warehouse. The end of the last article focused on making two dbt seeds: one for keeping track of Snowflake stage info and the other for listing the columns in each table that gets CSV files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3Ce7T4HuVSUZI1iOs7zYg.png" /><figcaption>dbt Seeds and dbt Macros workflow</figcaption></figure><h3>3 Data used for the demo</h3><p>To test this workflow with AWS S3 integration, 2 data files were used:</p><p><strong>Json data about the history of earth meteorite landings obtained from </strong><a href="https://data.nasa.gov/resource/y77d-th95.json"><strong>NASA</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgEe-yiRtDW4DQgpQILD1A.png" /><figcaption>Earth meteorite landings data from NASA</figcaption></figure><p>You may want to take a look of how this JSON file is structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvMGVq2g4K1_9eiTaBf-yA.png" /><figcaption>Sample of JSON file</figcaption></figure><p>You have to be careful if the file starts with a square bracket. <strong>We need to asume that the file is an array of JSON objects.</strong></p><p><strong>Csv data about the list of companies that participated in the </strong><a href="https://data.nasa.gov/Management-Operations/SxSW-2016-Leads/yvxp-ccvk/about_data"><strong>NASA’s SxSW 2016 conference</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1l5b8nIT4r7Q78ZtE6KdZg.png" /><figcaption>SxSW 2016 Conference’s Leads</figcaption></figure><p>This is how the dbt seeds were filled:</p><h4>Seed 1:</h4><pre>id;type_stage;cloud_storage_provider;source_file_type;stage_name_suffix;delimiter;flg_strip_array;flg_active;flg_move_data;flg_recreate<br>earth_meteorite_landings_nasa;raw;aws;json;earth_meteorite_landings_nasa;NA;1;1;1;1<br>companies_conference_nasa;raw;aws;csv;companies_conference_nasa;,;0;1;1;1</pre><p>Important Notes:</p><ul><li>flg_strip_array: if the flag is 1, it assumes that the Json file consist of an <strong>array</strong> of Json objects.</li></ul><h4>Seed 2</h4><pre>id;column_position;column_name<br>companies_conference_nasa;1;company<br>companies_conference_nasa;2;position<br>companies_conference_nasa;3;country<br>companies_conference_nasa;4;email<br>companies_conference_nasa;5;domain<br>companies_conference_nasa;6;location</pre><p>By the end of the whole workflow, we should expect to have 2 stages and 2 raw tables:</p><pre>|                           Stage                          |                    Table                   |<br>|:--------------------------------------------------------:|:------------------------------------------:|<br>| LANDING_STAGE_AWS_JSON_DEV_EARTH_METEORITE_LANDINGS_NASA | RAW_AWS_JSON_EARTH_METEORITE_LANDINGS_NASA |<br>| LANDING_STAGE_AWS_CSV_DEV_COMPANIES_CONFERENCE_NASA      | RAW_AWS_CSV_COMPANIES_CONFERENCE_NASA      |</pre><h3>4 dbt Macros implementations</h3><h4>Use Case: Creating snowflake stages automatically (Macro 1)</h4><p>Here is the code:</p><pre>{% macro deploy_snowflake_stages(node, storage_prov=&#39;aws&#39;, landing_schema_name = &#39;landing&#39;) -%}<br>    <br>    -- depends_on: {{ ref(&#39;seed_snowflake_stages&#39;) }}<br>    <br>    {# Important Parameters #}<br>    {%- set env= env_var(&#39;DBT_ENV_NAME&#39;) -%}                                {# Database environment (dev, qa, prod) #}<br>    {%- set database_name= env_var(&#39;DBT_DB_NAME&#39;) -%}                       {# Database environment (dev, qa, prod) #}<br>    {%- set cloud_location=[] -%}                                           {# List of bucket folder URLs #}<br>    {%- set database_schema_name = database_name ~ &#39;.&#39; ~ landing_schema_name ~ &#39;.&#39; -%}    {# Database and schema (landing) #}<br>    <br>    {% if storage_prov == &#39;aws&#39; %}<br>        {%- set bucket_name = &#39;s3://snowflake-data-repository-&#39;~env~&#39;/&#39;  -%}<br>    {% else %}<br>        {# Include your other buckets from other cloud providers #}<br>    {% endif %}<br><br>    {% set storage_prov_list = [&#39;aws&#39;, &#39;gcp&#39;, &#39;azure&#39;] %}<br><br>    {% if storage_prov in storage_prov_list %}<br>        <br>        {# ################################ #}<br>        {# Creating the Storage Integration #}<br>        {# ################################ #}<br>        {%- set storage_int_name = storage_prov ~ &#39;_stg_int_&#39; ~ env -%}<br><br>        {# Creating the Storage Integration #}<br>        {%- set query -%}<br>            select * from {{ ref(&#39;seed_snowflake_stages&#39;) }} where cloud_storage_provider = &#39;{{ storage_prov }}&#39; and flg_active = 1<br>        {%- endset -%}<br><br>        {%- set res_snowflake_stages = run_query(query) -%}<br><br>        {# Concatenating all the Bucket folders directories to STORAGE_ALLOWED_LOCATIONS parameter #}<br>        {%- for row in res_snowflake_stages -%}<br><br>            {%- set stage_name = &quot;&#39;&quot; ~ bucket_name ~ row[1] ~ &#39;_&#39; ~ row[2] ~ &#39;_&#39; ~ row[3] ~ &#39;_&#39; ~ row[4] ~ &#39;/&#39; ~ &quot;&#39;&quot; -%}<br>            {%- set tmp = cloud_location.append(stage_name) -%}<br><br>        {% endfor %}<br><br>        {%- set cloud_location_str = cloud_location | join(&#39;,\n&#39;) -%}<br><br>        {# Create the Snowflake Storage Integration #}<br>        {%- set update_stg_int -%}<br>            <br>            alter storage integration {{ storage_int_name }}<br>            set storage_allowed_locations = ({{ cloud_location_str }});<br><br>        {%- endset -%}<br><br>        {%- set result = run_query(update_stg_int) -%}<br><br>        {# ########################### #}<br>        {# Create the Snowflake Stages #}<br>        {# ########################### #}<br>        {%- for row in res_snowflake_stages -%}<br><br>            {%- set stage_name = landing_schema_name ~ &#39;_stage_&#39; ~ storage_prov ~ &#39;_&#39; ~ row[3] ~ &#39;_&#39; ~ env ~ &#39;_&#39; ~ row[4] -%}<br><br>            {%- set drop_stage -%}<br>                drop stage if exists {{ database_schema_name }}{{ stage_name }}<br>            {% endset %}<br><br>            {%- set result = run_query(drop_stage) -%}<br><br>            {%- set url_name = &quot;&#39;&quot; ~ bucket_name ~ row[1] ~ &#39;_&#39; ~ row[2] ~ &#39;_&#39; ~ row[3] ~ &#39;_&#39; ~ row[4] ~ &#39;/&#39; ~ &quot;&#39;&quot; -%}    <br><br>            {%- set create_stage -%}<br><br>                create stage {{ database_schema_name }}{{stage_name}}<br>                url = {{ url_name }}<br>                storage_integration = {{ storage_int_name }}<br><br>            {% endset %}<br><br>            {%- set result = run_query(create_stage) -%}<br><br>        {% endfor %}<br><br>        {{ log(&quot;USER LOG: Deployment Snowflake Stages - FINISHED!&quot;) }}<br><br>    {% else %}<br><br>        {{ log(&quot;USER LOG: Deployment Snowflake Stages not executed! Invalid parameters!&quot;) }}<br><br>    {% endif %}<br><br>{%- endmacro %}</pre><p><strong>Highlights:</strong></p><p><strong>Macro Parameters</strong>: The macro takes three parameters: <strong>node</strong>, <strong>storage_prov</strong> (defaulting to &#39;aws&#39;), and <strong>landing_schema_name</strong> (defaulting to &#39;landing&#39;).</p><p><strong>Environment Setup</strong>: The macro sets up various environment variables, such as the database environment (<strong>env</strong>), database name (<strong>database_name</strong>), and the cloud location (<strong>cloud_location</strong>). These are used to determine the database and schema names and to store URLs for bucket folders. The last variable is useful for the <strong>Snowflake storage integration</strong>.</p><p><strong>Cloud Storage Provider Logic</strong>: The macro includes logic to handle different cloud storage providers. By default, it is set for AWS (Amazon Web Services), but it can be extended to support others like Google Cloud Platform (GCP) or Azure.</p><p><strong>Storage Integration Creation</strong>: The macro retrieves active stages from the <strong>seed_snowflake_stages</strong> table and dynamically constructs the <strong>STORAGE_ALLOWED_LOCATIONS</strong> parameter for the Snowflake storage integration. This is key for specifying where Snowflake can load data from.</p><p><strong>Stage Creation in Snowflake</strong>: The macro iterates through the results from the seed table and creates (or drops and re-creates) Snowflake stages for each entry. It constructs each stage’s name based on the schema, cloud provider, environment, and other details from the seed table.</p><p><strong>Dynamic Execution</strong>: The macro is dynamic, meaning it can create or alter stages and storage integrations based on the current environment (dev, qa, prod) and the cloud storage provider specified.</p><p>To run the macro on <strong>development</strong> environment for AWS cloud storage, the dbt instruction should be:</p><pre>dbt run-operation deploy_snowflake_stages --args &#39;{storage_prov: aws, landing_schema_name: landing}&#39;</pre><p>If everything goes ok, on Snowflake we can see the creation of the stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ji5ekgSoPCJd6dJ50QvmA.png" /><figcaption>Stages created on DB_DEV</figcaption></figure><h4>Use Case: Creating snowflake raw tables automatically (Macro 2)</h4><pre>{% macro deploy_snowflake_raw_tables(node, storage_prov=&#39;aws&#39;, landing_schema_name = &#39;landing&#39;) -%}<br>    <br>    -- depends_on: {{ ref(&#39;seed_snowflake_raw_table_columns&#39;) }}<br><br>    {%- set database_name = env_var(&#39;DBT_DB_NAME&#39;) -%}<br>    <br>    {# Getting the list of sources to create #}<br>    {%- set query -%}<br>        select <br>            id,<br>            source_file_type,<br>            type_stage || &#39;_&#39; || cloud_storage_provider || &#39;_&#39; || source_file_type || &#39;_&#39; || stage_name_suffix as table_name<br>        from {{ ref(&#39;seed_snowflake_stages&#39;) }} <br>        where   cloud_storage_provider = &#39;{{ storage_prov }}&#39; and <br>                flg_recreate = 1<br>    {%- endset -%}<br><br>    {%- set res_snowflake_tables = run_query(query) -%}<br><br>    {# Create the Snowflake Tables #}<br>    {%- for row in res_snowflake_tables -%}<br><br>        {%- set id = row[0] -%}<br>        {%- set source_file_type = row[1] -%}<br>        {%- set table_name = row[2] -%}<br><br>        {# Re-create table query #}<br>        {%- set drop_table -%}<br>            drop table if exists {{database_name}}.{{landing_schema_name}}.{{table_name}}<br>        {%- endset -%}<br><br>        {%- set res_snowflake_stage_drop = run_query(drop_table) -%}<br><br>        {%- if source_file_type == &#39;json&#39; -%}<br><br>            {%- set create_raw_table -%}<br>                <br>                {# It&#39;s not required to get the list of columns #}<br>                create or replace table {{database_name}}.{{landing_schema_name}}.{{table_name}}<br>                (   <br>                    metadata_filename text,<br>                    metadata_file_row_number number,<br>                    metadata_file_content_key text,<br>                    metadata_file_last_modified timestamp,<br>                    metadata_start_scan_time timestamp,<br>                    json_object variant,<br>                    updated_at timestamp<br>                )<br><br>            {%- endset -%}<br><br>            {%- set temp = run_query(create_raw_table) -%}<br><br>            {{ log(&#39;USER LOG: Creating table &#39; ~ table_name ~ &#39;...&#39;) }}<br><br>        {%- elif  source_file_type == &#39;csv&#39; -%}<br><br>            {%- set query -%}<br><br>                select<br>                    listagg(column_name || &#39; string&#39;, &#39;, &#39;) within group (order by column_position) as concatenated_columns<br>                from<br>                    {{ ref(&#39;seed_snowflake_raw_table_columns&#39;) }}<br>                where<br>                    id = &#39;{{ id }}&#39;<br><br>            {%- endset -%}<br><br>            {%- set columns_csv = run_query(query) -%}<br><br>            {%- for row in columns_csv -%}<br><br>                {%- set str_columns = row[0] -%}<br><br>                {%- set create_table -%}<br><br>                    create or replace table {{database_name}}.{{landing_schema_name}}.{{table_name}}<br>                    (   <br>                        metadata_filename text,<br>                        metadata_file_row_number number,<br>                        metadata_file_content_key text,<br>                        metadata_file_last_modified timestamp,<br>                        metadata_start_scan_time timestamp,<br>                        {{ str_columns }},<br>                        updated_at timestamp<br>                    )<br><br>                {%- endset -%}<br><br>                {%- set temp = run_query(create_table) -%}<br><br>            {%- endfor -%}<br><br>            {{ log(&#39;USER LOG: Creating table &#39; ~ table_name ~ &#39;...&#39;) }}<br><br>        {%- else -%}<br><br>            {{ log(&#39;USER LOG: Not valid source file type&#39;)}}<br>        <br>        {%- endif -%}<br><br>    {% endfor %}<br><br>    {{ log(&quot;USER LOG:  Deployment Snowflake Data Cloud - Creating Tables - FINISHED&quot;) }}<br><br>{%- endmacro %}</pre><p><strong>Highlights:</strong></p><p><strong>Database Name Setup</strong>: The macro sets the database name using an environment variable, <strong>DBT_DB_NAME</strong>.</p><p><strong>Source List Retrieval</strong>: The macro queries the <strong>seed_snowflake_stages</strong> seed table to get a list of sources for which tables need to be created or recreated. This list includes the source file type and a constructed table name based on the stage details and file type.</p><p><strong>Table Creation Logic</strong>: The macro iterates through the retrieved source list and performs the following:</p><ul><li>Drops existing tables if they exist in the specified database and schema.</li><li>For JSON files, it creates tables with predefined columns suitable for JSON data.</li><li>For CSV files, it dynamically constructs the table schema based on column information retrieved from the <strong>seed_snowflake_raw_table_columns</strong> seed table.</li><li>For both tables, the first 5 columns refers to the data file’s metadata.</li></ul><p>To run the macro on <strong>development</strong> environment for AWS cloud storage, the dbt instruction should be:</p><pre>dbt run-operation deploy_snowflake_raw_tables --args &#39;{storage_prov: aws, landing_schema_name: landing}&#39;</pre><p>What we could expect is the creation of both tables mentioned before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*li-31kZ3E9SyqUyUHUYVGg.png" /><figcaption>Raw tables created on DB_DEV</figcaption></figure><h4>Use Case: Moving data from static datasets (Macro 3)</h4><p>This one is a little bit bigger code, you can take a look on the full code on the <a href="https://github.com/luismirandad27/de-dbt-seed-snowflake-integration/blob/main/macros/deployment/copy_staged_files_into_tables.sql"><strong>GitHub repo</strong></a>, however, I’m going to explain the crucial part.</p><p>First, the objective of this macro is to run iteratively (based on the stages’ seed) multiple COPY INTO statements, this will move the data into the table. However, the syntax of this action will be different depending on the file format.</p><p>For example, the dbt macro will generate a statement for JSON files like this:</p><pre>{%- set copy_into_data -%}<br>    {# Run copy into #}<br>    copy into {{ database_schema_name }}.{{ table_name }} (<br>        metadata_filename,<br>        metadata_file_row_number,<br>        metadata_file_content_key,<br>        metadata_file_last_modified,<br>        metadata_start_scan_time,<br>        json_object,<br>        updated_at<br>    )<br>    from<br>        (<br>            SELECT<br>                METADATA$FILENAME as metadata_filename,<br>                METADATA$FILE_ROW_NUMBER as METADATA_FILE_ROW_NUMBER,<br>                METADATA$FILE_CONTENT_KEY as METADATA_FILE_CONTENT_KEY,<br>                METADATA$FILE_LAST_MODIFIED as METADATA_FILE_LAST_MODIFIED,<br>                METADATA$START_SCAN_TIME as METADATA_START_SCAN_TIME,<br>                t.$1,<br>                current_timestamp()<br>            FROM<br>                @{{ database_schema_name }}.{{ stage_name }} (file_format =&gt; {{ database_schema_name }}.json_format_array_temp_{{row[4]}} ) t<br>        );<br>{%- endset -%}</pre><p>First, we apply a subquery to include a temporary FILE FORMAT object created in one step before in the same macro.</p><p>Because we need to only add the full JSON object we need to use the keyword $1 to get the full object. On <strong>staging schema</strong>, we can use the raw table (as a <strong>dbt source</strong>) an take the advantage that Snowflake can handle semistructured data.</p><p>The same statement will change for CSV data files:</p><pre>{# Query to list all columns for a table #}<br>{%- set query_table_columns -%}<br><br>    select<br>        listagg( &#39;$&#39; || column_position || &#39;, &#39;) within group (order by column_position) as concatenated_columns<br>    from<br>        {{ ref(&#39;seed_snowflake_raw_table_columns&#39;) }}<br>    where <br>        id = &#39;{{ id }}&#39;<br><br>{%- endset -%}<br><br>{%- set res_snowflake_table_cols = run_query(query_table_columns) -%}<br><br>{%- for row_col in res_snowflake_table_cols -%}<br><br>    {# Create Copy Query #}<br>    {%- set copy_stage_data -%}<br><br>        copy into {{ database_schema_name }}.{{ table_name }} <br>        from<br>            (<br>                SELECT<br>                    METADATA$FILENAME as metadata_filename,<br>                    METADATA$FILE_ROW_NUMBER as METADATA_FILE_ROW_NUMBER,<br>                    METADATA$FILE_CONTENT_KEY as METADATA_FILE_CONTENT_KEY,<br>                    METADATA$FILE_LAST_MODIFIED as METADATA_FILE_LAST_MODIFIED,<br>                    METADATA$START_SCAN_TIME as METADATA_START_SCAN_TIME,<br>                    {{row_col[0]}}<br>                    current_timestamp()<br>                FROM<br>                    @{{ database_schema_name }}.{{ stage_name }} (file_format =&gt; {{ database_schema_name }}.csv_format_array_temp_{{row[4]}} ) t<br>            );<br><br>    {%- endset -%}<br><br>    {%- set res_snowflake_stage_copy = run_query(copy_stage_data) -%}<br><br>{%- endfor -%}</pre><p>While we read the seed with the column list, I use listagg to concat all the columns so I can prepare the SELECT inside the COPY INTO efficiently.</p><p>The same like the other scenario, I created a temporary FILE FORMAT for CSV files (later on, it will be dropped).</p><p>Let’s execute the macro:</p><pre>dbt run-operation copy_staged_files_into_tables --args &#39;{schema_name: landing}&#39;</pre><p>Finally, the raw snowflake tables will be populated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc0fsbYEkdnVuFQjtHoHqg.png" /><figcaption>Landing table with JSON data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abvNFx98mzpyIqxby5GVEw.png" /><figcaption>Landing table with CSV format data</figcaption></figure><p>Cool! Now I have data in my tables!</p><h3>5 Bonus: Creating a CI Job for deployment</h3><p>Obviously, you don’t want to run these macro instructions manually and at every time. Normally, we would like to perform this maintenance (creation or recreation) on every <strong>deployment</strong> to our QA and PROD databases.</p><p>With dbt, we can deploy our pipelines with <strong>CI Jobs</strong>, so we can execute several instructions while we perform a pull request between git branches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzIqBXarejZN4bJfWyeK8g.png" /><figcaption>dbt Environments</figcaption></figure><p>So far I have created 2 deployment environments: Production and QA. If I want to deploy my pipeline to QA environment (DB_QA database in snowflake), I create a <strong>Continuous Integration (CI) Job:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*QpUyYYYhw7QfoPuMWJjR1A.png" /><figcaption>CI Jobs</figcaption></figure><p>Now, we can add our dbt instructions on this job. Just in case, we will require the update of the 2 dbt seeds before the execution of the 3 macros:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnW8u6ABGJYqZcguxcugDA.png" /><figcaption>Configuring CI job</figcaption></figure><p>Note: it’s important to change the target in <strong>Advanced Settings</strong> to “qa” (if the CI job is for the Production environment, should be “prod”).</p><p>Now, when you make a pull request to the branch is linked to this dbt environment, this job will launch and update the stages, create the raw tables and move any static data to the Snowflake tables!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlmKsqW9vTedY9d-OmCaJA.png" /><figcaption>Snowflake stages deployed! Awwweeeesomeeee!</figcaption></figure><h3><strong>6 Conclusion</strong></h3><p>In this final article, we explored how to implement the dbt macros that were developed for this workflow. As you might notice, it does involve a bit of coding, but honestly, it’s quite enjoyable!</p><p>There’s room for further development here, so if you have any suggestions or ideas, I’d love to hear them!</p><p>I hope this project inspires you to discover the impressive capabilities of dbt when applied creatively.</p><p>Check out the complete dbt project at the <a href="https://github.com/luismirandad27/de-dbt-seed-snowflake-integration/tree/main">link</a> provided! Don’t forget to star it!</p><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d60e4d32ba" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mastering-ci-with-dbt-seeds-and-snowflake-part-2-2-95d60e4d32ba">Mastering CI with Dbt Seeds and Snowflake (Part 2/2)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Data Integration Made Easy with Change Data Capture (CDC)]]></title>
            <link>https://blog.devgenius.io/real-time-data-integration-made-easy-with-change-data-capture-cdc-dd536f2d0f43?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd536f2d0f43</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Thu, 04 May 2023 03:30:07 GMT</pubDate>
            <atom:updated>2023-05-04T10:11:12.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8inxFMsF649fgHxVrYP8JA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dekubaum">Dennis Kummer</a> (<a href="https://unsplash.com/photos/52gEprMkp7M">unsplash.com</a>)</figcaption></figure><h3>Introduction</h3><p>If you are familiar with some data processing patterns in a Data Lake, you may know what a multi-hop architecture (bronze, silver and gold layers) is. While using this pattern, you can design a well-organized data workflow where the data could come from many sources and reside in final repositories for different purposes: data analysis, data science and so on.</p><p>Each layer has its own purpose but we are not going to talk about them in this article. However, inside this data architecture, it’s important to mention that there are interesting patterns designed to manage these workflows efficiently. With efficiency we try to cover integrity, consistency and quality on the data.</p><p>In this article, I’m going to talk about the Change Data Capture (CDC) and how we can apply it as well as how Databricks help us to do it easier.</p><h3>What is Change Data Capture (CDC)?</h3><p>CDC helps us to track changes and transfer the information automatically to the target dataset. These immediate updates can be enriched by using a streaming processing where the data will come in multiple micro-batches and will “hit” the target dataset.</p><p>That means that we CDC we still empower our ETL with the benefits of data streaming like:</p><ul><li>Real time asynchronization</li><li>Reduced latency</li><li>Improved Scalability</li><li>Increased efficiency</li></ul><p>To update our target dataset with the reliable information we need “something” that notify us how we should update each row. We have different ways to do it:</p><p>1- Log-based CDC: we can have an external table that works as a log with all the actions we performed on the source dataset that allow us to know the things we need to do on the target (insert, update, delete).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYwMbRitfT2a1Dwm1sTrGA.png" /><figcaption>Example of <a href="https://www.striim.com/blog/change-data-capture-cdc-what-it-is-and-how-it-works/">CDC (Log-based)</a></figcaption></figure><p>2- Trigger-based CDC: by every action we are doing in the source dataset, we trigger an additional step to transfer the information to the target dataset. For example, if I update one row in the source, this update will trigger (native trigger) a function that updates the same in the target dataset. However, this will significantly reduce the performance of the database (multiple writes).</p><p>3- Comparing source and target datasets and get the differences.</p><p>One last type is the Audit-based CDC and we are gonna explain it with an example in the next section.</p><h3>Working with Change Data Capture with PySpark in Databricks</h3><p>Let’s say we have a table in the bronze layer (see the medallion architecture on the <a href="https://docs.databricks.com/lakehouse/medallion.html">Databricks Documentation</a>), with raw information about video games that comes from a Kafka topic. It contains this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zWjKcptBQ_2dGepAF0Puw.png" /><figcaption>Structure of games_raw table</figcaption></figure><p>The row_jsoncontains the whole information of the game item and you may notice 2 columns: row_actionand row_time. The row_actionrefers to the action we need to perform in the silver layer table. The row_timehelps us to know which change is the latest.</p><p>This is a sample data on the bronze’s table games_raw :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05FxWmqhYTlOSmiMewE7xw.png" /><figcaption>games_raw’s sample</figcaption></figure><p>The idea is that depending on the type of action we have to do the same action in the games_silver table. If the action is an update, we need to look for the latest update action to perform (yes, we can make a ranking of updates per row).</p><p>First this is the main method that will read the bronze table and write the data into the silver table.</p><pre>from pyspark.sql import functions as F<br><br>def process_data_to_silver():<br>    <br>    schema = &quot;game_id STRING, title STRING, company STRING, platform Array&lt;STRING&gt;, row_action STRING, row_time TIMESTAMP&quot;<br><br>    stream_query = (<br>        spark.readStream.table(&quot;games_raw&quot;)<br>                .filter(&quot;row_topic == &#39;games&#39;&quot;)<br>                .select(F.from_json(F.col(&quot;row_json&quot;),schema).alias(&quot;v&quot;))<br>                .select(&quot;v.*&quot;)<br>            .writeStream<br>                .foreachBatch(batch_merge_operation_cdc)<br>                .option(&quot;checkpointLocation&quot;,&quot;dbfs:/mnt/cdc_demo/checkpoints/games_silver&quot;)<br>                .trigger(availableNow=True)<br>                .start()<br>    )<br><br>    stream_query.awaitTermination()</pre><p>Some things to remark:</p><ul><li>Assuming that we are working in a multiplex architecture, we are storing multiple topics in the bronze table.</li><li>The F.from_jsonmethod helps us to “split” the json object into columns. It’s important to map properly the schema for this new table.</li></ul><p>One last thing: you may notice the foreachBatch()method. This is crucial because with that, we are going to perform the CDC. By using trigger(availableNow=True), we are trying to process all the data available in the stream by using multiple micro-batches.</p><p>Finally each microbatch it’s going to execute the batch_merge_operation_cdc function. The following code is the detail of the function:</p><pre>from pyspark.sql.window import Window<br>from pyspark.sql import functions as F<br><br># Defining method to add at every microbatch<br>def batch_merge_operation_cdc(microBatchDF, batchID):<br>    <br>    # Creating window operation<br>    window_operation = Window.partitionBy(&quot;game_id&quot;).orderBy(F.col(&quot;row_time&quot;).desc())<br><br>    # Creating temporary view from bronze layer with the updates ranked<br>    (microBatchDF.filter(F.col(&quot;row_action&quot;).isin([&#39;insert&#39;,&#39;update&#39;]))<br>                .withColumn(&quot;action_rank&quot;,F.rank().over(window_operation))<br>                .filter(&quot;action_rank == 1&quot;)<br>                .drop(&quot;action_rank&quot;)<br>                .createOrReplaceTempView(&quot;games_raw_ranked_updates&quot;)<br>    )<br><br>    # Performing MERGE operation<br>    merge_query = &quot;&quot;&quot;<br>        MERGE INTO games_silver a<br>        USING games_raw_ranked_updates b <br>        ON a.game_id = b.game_id<br>            WHEN MATCHED AND a.row_time &lt; b.row_time<br>                THEN UPDATE SET *<br>            WHEN NOT MATCHED<br>                THEN INSERT *<br>    &quot;&quot;&quot;<br><br>    microBatchDF.sparkSession.sql(merge_query)</pre><ol><li>We are creating a temporary view called games_raw_ranked_updates. This view contains the latest changes we are going to perform in the silver table (by using a window function).</li><li>The MERGE query will make the magic. After joining the silver table and the view, we will know what to do (to update or to insert).</li><li>Keep in mind that to run the SQL query per each microbatch we need to make the .sparkSession.sql(merge_query)</li></ol><p>Assume we are adding 2 new rows in the bronze table. This will require updating the names of 2 video games (renaming <em>God Of War and Resident Evil Village</em> to <em>God Of War (2018) and Resident Evil 8: Village</em>).</p><pre>%sql<br><br>INSERT INTO games_raw VALUES<br>(11,&quot;{<br>  &#39;game_id&#39;: &#39;0003&#39;,<br>  &#39;title&#39;: &#39;God of War (2018)&#39;,<br>  &#39;company&#39;: &#39;Santa Monica Studio&#39;,<br>  &#39;platform&#39;: [&#39;PlayStation 4&#39;, &#39;PlayStation 5&#39;],<br>  &#39;row_action&#39;: &#39;update&#39;,<br>  &#39;row_time&#39;: &#39;2022-05-01T08:17:00.000Z&#39;<br> }&quot;,&quot;games&quot;),<br> (12,&quot;{<br>  &#39;game_id&#39;: &#39;0009&#39;,<br>  &#39;title&#39;: &#39;Resident Evil 8: Village&#39;,<br>  &#39;company&#39;: &#39;Capcom&#39;,<br>  &#39;platform&#39;: [&#39;PC&#39;, &#39;Xbox&#39;, &#39;PlayStation 4&#39;,&#39;PlayStation 5&#39;],<br>  &#39;row_action&#39;: &#39;insert&#39;,<br>  &#39;row_time&#39;: &#39;2022-05-01T10:20:00.000Z&#39;<br> }&quot;,&quot;games&quot;);</pre><p>Let’s run the function process_data_to_silver()and let’s see the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGL_LJhcGTgZuQdSpPJm1A.png" /><figcaption>Updated games information</figcaption></figure><p>Awesome, it’s working! Let’s present one more thing…</p><h3><strong>The Change Data Feed (CDF) Feature from Databricks</strong></h3><p>The previous example was a custom CDC process. However, Databricks is making our lives easier. With CDF, Databricks is generating a table called table_changeswhere we can track all the actions performed to the target dataset based on a specific version we ask to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsDmiNRphAoIpGgoX8RA8g.png" /><figcaption>CDC and CDF in the Medallion Architecture (Source: Own Elaboration)</figcaption></figure><p>Let’s see an example to clarify this:</p><p>First let’s enable the CDF feature</p><pre>%sql<br>ALTER TABLE games_silver<br>SET TBLPROPERTIES (delta.enableChangeDataFeed = true);</pre><p>Let’s gonna add a new row in the bronze table:</p><pre>%sql<br>INSERT INTO games_raw VALUES<br>(13,&quot;{<br>  &#39;game_id&#39;: &#39;0010&#39;,<br>  &#39;title&#39;: &#39;Cyberpunk 2077&#39;,<br>  &#39;company&#39;: &#39;CD Projekt RED&#39;,<br>  &#39;platform&#39;: [&#39;PC&#39;, &#39;Xbox&#39;, &#39;PlayStation 4&#39;,&#39;Playstation 5&#39;],<br>  &#39;row_action&#39;: &#39;update&#39;,<br>  &#39;row_time&#39;: &#39;2022-05-02T10:25:00.000Z&#39;<br> }&quot;,&quot;games&quot;);</pre><p>We want to update the platform String array for the game_id ‘0010’.</p><pre>process_data_to_silver()</pre><p>So we updated the data, to review the table_changes table, we required one important parameter: the version number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMK8tAa-nYsJbFewZ0Yxtg.png" /></figure><p>We noticed that the last change was performed in <strong>version 4</strong>. So let’s make a query in this new table:</p><pre>%sql<br>SELECT *<br>FROM table_changes(&quot;games_silver&quot;, 4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahGs1fZrnuaZMZIclJFuDA.png" /><figcaption>table_changes</figcaption></figure><p>Nice! We can see the changes performed in the silver table including the previous values (update_preimage) of the row and the final values ( update_postimage).</p><h3><strong>How can we apply the CDF feature?</strong></h3><p>Databricks describes multiple use cases for applying the CDF feature (this information comes from this <a href="https://www.databricks.com/blog/2021/06/09/how-to-simplify-cdc-with-delta-lakes-change-data-feed.html">link</a>):</p><p><strong><em>Silver &amp; gold tables</em></strong></p><p><em>Improve Delta performance by processing only changes following initial MERGE comparison to accelerate and simplify ETL/ELT operations.</em></p><p><strong><em>Materialized views</em></strong></p><p><em>Create up-to-date, aggregated views of information for use in BI and analytics without having to reprocess the full underlying tables, instead updating only where changes have come through.</em></p><p><strong><em>Transmit changes</em></strong></p><p><em>Send Change Data Feed to downstream systems such as Kafka or RDBMS that can use it to incrementally process in later stages of data pipelines.</em></p><p><strong><em>Audit trail table</em></strong></p><p><em>Capturing Change Data Feed outputs as a Delta table provides perpetual storage and efficient query capability to see all changes over time, including when deletes occur and what updates were made.</em></p><h3><strong>Conclusion</strong></h3><p>You saw a brief summary of what is Change Data Capture (CDC), an interesting way to keep your data across the ETL with high reliability and high compatibility with near-real time movement of data. One use case I’m applying here is to use the CDC in a medallion architecture designed by Databricks (Bronze — Silver — Gold Layers).</p><p>Finally, Databricks offers a feature called Change Data Feed (CDF) that applies the previous concept by creating automatically a table where we can track all the changes and finally we can take advantage on this for multiple use cases.</p><p>You can check the entire notebook <a href="https://github.com/luismirandad27/de-python-changedatacapture-databricks.git">here</a> and add the repo into your Databricks Workspace.</p><h3>References</h3><ul><li><a href="https://www.striim.com/blog/change-data-capture-cdc-what-it-is-and-how-it-works/">https://www.striim.com/blog/change-data-capture-cdc-what-it-is-and-how-it-works/</a></li><li><a href="https://www.databricks.com/blog/2021/06/09/how-to-simplify-cdc-with-delta-lakes-change-data-feed.html">https://www.databricks.com/blog/2021/06/09/how-to-simplify-cdc-with-delta-lakes-change-data-feed.html</a></li></ul><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd536f2d0f43" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/real-time-data-integration-made-easy-with-change-data-capture-cdc-dd536f2d0f43">Real-Time Data Integration Made Easy with Change Data Capture (CDC)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Collaborative Filtering: Enhancing Movie Recommendation Systems]]></title>
            <link>https://medium.com/@lmirandad27/the-magic-of-collaborative-filtering-enhancing-movie-recommendation-systems-7e24fe7b4165?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e24fe7b4165</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[movie-recommendation]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 16:02:34 GMT</pubDate>
            <atom:updated>2023-02-11T18:08:09.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLjOEcbCSkzrUQ9uOpsiQQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jeremyyappy">Jeremy Yap</a> (<a href="https://unsplash.com/photos/J39X2xX_8CQ">unsplash.com</a>)</figcaption></figure><h3>Introduction</h3><p>As a part of my Post Degree Diploma in Data Analytics, I’m taking a Software Engineering course. Maybe you would ask, why are you taking a software engineering class in that kind of specialization? (Well, it’s part of the curriculum). In this course, we are creating a software development project which consists of developing a website (pretty obvious).</p><p>The website we are building is a movie recommendation site where users can view information about a collection of movies, leave reviews or comments, and create their own watchlists. To provide movie recommendations to users, we were searching for an algorithm and stumbled upon the collaborative filtering algorithm, specifically the user-based version.</p><p>In this article, we will discuss what this algorithm entails.</p><h3>The Collaborative Filtering Algorithm</h3><p>To sum it up, the collaborative filtering algorithm is based on the preferences and behavior of multiple users. If a user shares similar likes and dislikes with their friends, it can be assumed that they have similar preferences, allowing the algorithm to recommend items accordingly.</p><p>There are two types of this algorithm:</p><ul><li><strong>Item-based Collaborative Filtering:</strong> This algorithm examines the items a user has liked in the past and recommends similar items based on the fact that these recommended items have been rated similarly by other users with similar preferences.</li><li><strong>User-based Collaborative Filtering:</strong> This algorithm looks for similar users with the same preferences and recommends items that those similar users have rated highly.</li></ul><p>At the moment, we will focus on the user-based algorithm.</p><p><strong>User-based Collaborative Filtering Algorithm</strong></p><p>For an easier explanation, let’s make an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*br4wCvTRz_qG0CrNyP3DtA.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>Suppose we have a table where the rows represent users and the columns represent movies. Each cell in the table represents a rating (ranging from 1 to 5) for a particular movie by a particular user. The goal is to recommend a movie for Luis. If a cell contains a “?” symbol, it means the user has not rated that movie yet. Let’s proceed with the algorithm.</p><p><strong><em>Step 1: Search for users who have rated the same movies as Luis, regardless of their ratings being the same or not.</em></strong></p><p>In this case, we have the following:</p><ul><li>Luis and Gianella rated Avengers Endgame, Midnight in Paris and Spiderman No Way Home.</li><li>Luis and Victor rated The Conjuring, Midnight in Paris and Spiderman No Way Home.</li><li>Luis and Marc rated Avengers Endgame, Midnight in Paris and Spiderman No Way Home.</li><li>Luis and Regal rated Avengers Endgame and Spiderman No Way Home.</li></ul><p><em>Coding</em></p><p>Let’s say we have a variable called ratings that is in form of a HashMap like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*auzSHj2uHLWzx9ud" /><figcaption>Source: Own Elaboration</figcaption></figure><p>To find the movies that a user <em>a (Luis) </em>and a user <em>b (one of the others) </em>rated, this is the method:</p><pre>public List&lt;Integer&gt; getCommonRatedMoviesList (int a, int b) {<br>  <br>  List&lt;Integer&gt; commonRatedMovies = new ArrayList&lt;&gt;();<br>  <br>  HashMap&lt;Integer,Double&gt; moviesRatedA = ratings.get(a);<br>  HashMap&lt;Integer,Double&gt; moviesRatedB = ratings.get(b);<br>  <br>  for(Map.Entry&lt;Integer, Double&gt; entryA: moviesRatedA.entrySet()) {<br>   if (moviesRatedB.containsKey(entryA.getKey())) {<br>    commonRatedMovies.add(entryA.getKey());<br>   }<br>  }<br>  <br>  return commonRatedMovies;<br>  <br> }</pre><p><strong><em>Step 2: Calculate how “similar” are both users by using the cosine distance</em></strong></p><p>Once we have compiled a list of the movies that Luis has rated, along with the ratings from other users, we can use the cosine distance to determine how “distant” Luis is from the other users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*N8-7oGdqEOb_MGn_" /><figcaption>Source: Own Elaboration</figcaption></figure><p>To calculate the distance (let’s call it similarity), we have the following formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*b04heRyUfA5sjT2s" /><figcaption>Source: Own Elaboration</figcaption></figure><p>Where:</p><ul><li>p-movies: the movies that both a and b rated</li><li>ra<strong>p</strong>: the rating of movie <strong>p</strong> by user a</li><li>rb<strong>p</strong>: the rating of movie <strong>p</strong> by user b</li></ul><p>If the value is closer to -1, that means that both users are not similar and if it’s closer to 1 both are pretty similar.</p><p><em>Coding:</em></p><pre>public double calculateSimilarity(int a, int b, List&lt;Integer&gt; crm) {<br>  <br>  double similarity = 0.0;<br>  <br>  double avgRa = calculateAverageRating(a);<br>  double avgRb = calculateAverageRating(b);<br>  <br>  double numerator = 0.0;<br>  double denom1 = 0.0;<br>  double denom2 = 0.0;<br>  <br>  HashMap&lt;Integer,Double&gt; moviesRatedA = ratings.get(a);<br>  HashMap&lt;Integer,Double&gt; moviesRatedB = ratings.get(b);<br>  <br>  for(int i=0; i&lt; crm.size(); i++) {<br>   <br>   numerator += (moviesRatedA.get(crm.get(i)))*(moviesRatedB.get(crm.get(i)));<br>   <br>   denom1   += Math.pow(moviesRatedA.get(crm.get(i)), 2);<br>   denom2   += Math.pow(moviesRatedB.get(crm.get(i)), 2);<br>   <br>  }<br>  <br>  denom1 = Math.sqrt(denom1);<br>  denom2 = Math.sqrt(denom2);<br>  <br>  if (crm.size()&gt; 1 &amp;&amp; numerator !=0 &amp;&amp; denom1 != 0 &amp;&amp; denom2 != 0) {<br>   return numerator / (denom1 * denom2);<br>  }<br>  return -100;<br>  <br> }</pre><p><strong><em>Step 3: Sorting users based on the similarity score</em></strong></p><p>The idea is to sort the users based on the score and keep the most similar users at the top.</p><p><strong><em>Step 4: Predict the rating that the user could make based on the similarities with others</em></strong></p><p>After calculating the similarities between Luis and the others and sorting the list, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*Jh5oVFd_0yzYgTBF" /><figcaption>Source: Own Elaboration</figcaption></figure><p>After sorting, we have to pick up the “closest neighbors”, because the idea is to have the users with the highest similarity with Luis (if you have a user with a negative similarity, you won’t want to consider him/her right?).</p><p>With the bounded list, let’s make the prediction by using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*BCX0abxoG_71vsmo" /><figcaption>Source: <a href="https://mindy-dossett.com/2021/04/18/collaborative-filtering-in-Java/">Mindy Zhou Dossett</a></figcaption></figure><p>Where:</p><ul><li>a: the user we want to predict his/her rating</li><li>p: the movie we want to predict</li><li>j-users: all users that rated the same movies like Luis</li><li>rj(bar): the average of ratings from user j</li><li>ra(bar): the average of ratings from user a (Luis in this case)</li><li>rjp: the rating of the movie p by user j</li></ul><p><em>Coding:</em></p><pre>public double calculatePrediction(int a, int movieIdx) {<br>  <br>  //First we are going to calculate the similarities and let&#39;s set a limit of Neighbors<br>  HashMap&lt;Integer, Double &gt; similarUsers = getUsersSimilarities(a);<br>  <br>  int numUsers = Math.min(similarUsers.size(), NUM_NEIGHBORS);<br>  <br>  if (numUsers == 0) {<br>   return 0;<br>  }<br>  <br>  double rating; <br>  <br>  double numerator = 0.0;<br>  double denom = 0.0;<br>  <br>  int j=0;<br>  <br>  for(Map.Entry&lt;Integer, Double&gt; user: similarUsers.entrySet()) {<br>   <br>   if (j&lt;numUsers) {<br>    <br>    double avgRj = calculateAverageRating(user.getKey());<br>    <br>    double similarityWithJ = user.getValue();<br>    <br>    double ratingFromUser = ratings.get(user.getKey()).get(movieIdx) == null ? 0 : ratings.get(user.getKey()).get(movieIdx) ;<br>    <br>    if (ratingFromUser &gt; 0) {<br>    <br>     numerator += similarityWithJ * (ratingFromUser  - avgRj);<br>     <br>     denom += Math.abs(similarityWithJ);<br>     <br>     j++;<br>     <br>    }<br>    <br>   }else {<br>    <br>    break;<br>    <br>   }   <br>  <br>  }<br>  <br>  double avgRa = calculateAverageRating(a);<br>   <br>  rating = avgRa + (numerator / denom);<br>  <br>  return rating;<br>  <br> }</pre><p>We are predicting that Luis rated “Evil Dead” with 3.77 (by using the top 2 neighbors but also rated this movie).</p><p><strong><em>Step 5: Make the recommendations</em></strong></p><p>For example, you can recommend those movies that you predicted a rating more than 3, 4, 4.5, etc.</p><p>If you want to check the full code, you can go <a href="https://github.com/luismirandad27/se-collaborative-filtering-algorithm-java">here</a> :)</p><h3><strong>Conclusions</strong></h3><p>The Collaborative Filtering algorithm enables us to make recommendations based on the “similarities” between users (or items). To determine this similarity, we use the cosine distance, although other methods like the Pearson correlation can also be used, depending on the choice of the user.</p><p>By the way, this algorithm can be applied to any type of item that uses a rating system, not just movies.</p><h3>References</h3><ul><li><a href="https://mindy-dossett.com/2021/04/18/collaborative-filtering-in-Java/">https://mindy-dossett.com/2021/04/18/collaborative-filtering-in-Java/</a></li><li><a href="https://medium.datadriveninvestor.com/cosine-similarity-cosine-distance-6571387f9bf8">https://medium.datadriveninvestor.com/cosine-similarity-cosine-distance-6571387f9bf8</a></li></ul><h3>HAPPY LEARNING!</h3><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a> | <a href="https://luismiguelmiranda.com/">Personal Website</a></p><h4><a href="https://mlearning.substack.com/about"><strong>BECOME a WRITER at MLearning.ai</strong></a></h4><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e24fe7b4165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips to pass the AZ-900 Azure Fundamentals Exam (feat. Active Recall Technique)]]></title>
            <link>https://blog.devgenius.io/tips-to-pass-the-az-900-azure-fundamentals-exam-feat-active-recall-technique-cf343da45b87?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf343da45b87</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[azure-fundamentals]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[certification]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 17:02:28 GMT</pubDate>
            <atom:updated>2023-01-23T14:02:28.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*BKp0rTh1J8dwMlR3FGW3iA.png" /><figcaption>My Azure Fundamentals Certification :)</figcaption></figure><h3>Overview</h3><p>I decided to take the Azure Fundamentals certification exam at the beginning of 2023 because it seemed like an interesting opportunity to gain an understanding of the key features of this cloud provider and test my skills.</p><p>The exam is designed to test one’s abilities by requiring them to make decisions based on real-world scenarios (such as cloud migration or hosting an app) and correctly define concepts. To prepare for the exam, I used a different study method to efficiently retain the information for a longer period of time.</p><p>In this article, I will provide tips on the topics covered in the exam and also share a helpful technique called active recall with spaced repetition that can be useful for other tests as well.</p><h3>Tips</h3><p><strong>Tip 0: Read the Exam Guide (Obviously)</strong></p><p>A good way to plan your preparation is by looking at the topics covered in the exam and focus on them separately.</p><p>These are the general topics:</p><ul><li>Describe cloud concepts (25–30%)</li><li>Describe Azure architecture and services (35–40%)</li><li>Describe Azure management and governance (30–35%)</li></ul><p>You can find the exam guide in this <a href="https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE3VwUY"><strong>link</strong></a>.</p><p><strong>Tip 1: Take an online course</strong></p><p>As always, Udemy offers different courses for this kind of preparation. In this case, I took the course <a href="https://www.udemy.com/course/az-900-azure-exam-prep-understanding-cloud-concepts/"><em>AZ-900 Bootcamp: Microsoft Azure Fundamentals</em></a> which was updated in November 2022.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*D0KCqAH240bEJ5KQlQDq7A.jpeg" /><figcaption><em>AZ-900 Bootcamp: Microsoft Azure Fundamentals (taken from Udemy)</em></figcaption></figure><p>This course is taught by Thomas Mitchell, a Cloud and Infrastructure Expert with more than 25 years in the IT industry. The course’s sections are well separated based on the Exam Guide and also it has a section with topics that have been removed from the exam but you can review them (you know, just in case).</p><p><strong>Tip 2: Read the documentation</strong></p><p>By reading the documentation, you will get more information about the features and characteristics about the cloud infrastructure and services. It is always important to review these documents to check topics like pricing.</p><p>If you take the Thomas Mitchell’s course, you may see some references that you can check while you are studying and making your notes.</p><p><strong>Link</strong>: <a href="https://learn.microsoft.com/en-us/azure/?product=popular">https://learn.microsoft.com/en-us/azure/?product=popular</a></p><p>If you want, you can take the learning path modules in the Microsoft Training page:</p><p><strong>Link</strong>: <a href="https://learn.microsoft.com/en-us/training/">https://learn.microsoft.com/en-us/training/</a></p><p><strong>Tip 3: Use Active Recall with Spaced Repetition</strong></p><p><strong>About Active Recall</strong></p><p>Let’s talk first about what Active Recall is. Basically, with this technique we are trying to actively retrieve information from our brains instead of just doing passive reviewing (or re-reading). In other words, you are training your brain by constantly <strong>recalling </strong>the information that is stored to solve a question or to define a concept.</p><p>How can you do this? Well, one alternative is to create your own flashcards where you put a question and the definition/solution. You can shuffle your flashcards and try to answer the questions and retry as many times as you want.</p><p>How many times do I need to repeat the active recall technique to have a long-term retention of the information? Use spaced repetition!</p><p><strong>About Spaced Repetition</strong></p><p>Sometimes, we prepare ourselves for a very tough exam. We can study one day before and make a review at the same day, but once you finish the exam and you stop reviewing your course content, you will start to lose that information progressively (in an exponential behaviour).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*2Qyj_pr6f0_5QzedTm7HEA.png" /><figcaption>The Forgetting Curve (Author: Harry Cloke in eLearning Industry)</figcaption></figure><p>Like in this graph called “the forgetting curve”, the % of remembered information (retention) is getting lost through the time. Spaced repetition is a way that you can delay that decrease. How? You can make active recall in continuous days (could be an interval of 2 days, that depends on you).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*1nGqW1wLyXCiqe6qMawpjA.png" /><figcaption>Combatin the Forgetting Curve (Author: Harry Cloke in the eLearning Industry)</figcaption></figure><p>With this, you are trying to keep the 100% retention constantly and the forgetting curve will slightly flatten in time.</p><p>Create your flashcards based on the topics for the exam (you can check exam questions too) and practice by using these techniques. It is important to keep a plan so you may have enough time to do this before your exam.</p><p><strong>Tip 4: Topics I found relevant to check</strong></p><p>Here are the most important topics to check while you are preparing for your exam:</p><p><em>1- Basic Cloud Concepts</em></p><ul><li>The Shared Responsibility Model</li><li>The Cloud Models: public, private and hybrid (differences and advantages)</li><li>What is the Consumption Based Model</li><li>What are the main characteristics/principles of Cloud Computing: high availability, scalability, elasticity, agility, geo distribution and disaster recovery.</li><li>CapEx vs OpEx</li><li>Differences between IaaS, PaaS and SaaS: you must know some examples of service for each type. For example, Azure Virtual Machines works as IaaS.</li></ul><p><em>2- Core Architectural Components</em></p><ul><li>Azure Regions. Besides the concept, you must know that there are special Azure Regions (for the US government and China Region).</li><li>What are Region Pairs?</li><li>Availability Zones vs Availability Sets</li><li>Resource Groups: characteristics and considerations (like: what happens if you delete a Resource Group or can you deploy resources from multiple regions in 1 resource group?)</li><li>Azure Subscription: concept and how you can define boundaries.</li><li>Management Groups</li></ul><p><em>3- Core Azure Compute Services and Products</em></p><ul><li>About Azure Compute Types: Azure Virtual Machine, Azure Scale Set, Azure Container Instances (+ Kubernetes), Azure App Service, Azure Functions and Azure Logic Apps.</li><li>Differences between Azure Container Instances vs Azure Kubernetes.</li><li>Azure Management Tools: Azure Portal, Azure PowerShell, Azure CLI, Azure CloudShell, Azure Mobile App and Azure REST API (you must know the requirements of a computer must have to use one of these tools.</li></ul><p><em>4- Core Azure Networks</em></p><ul><li>Virtual Network: what is the scope of this service.</li><li>What are the key network capabilities of a VNet: isolation and segmentation, internet communication, communication between resources and communication with On-Prem Infrastructures.</li><li>VNet Peering: VNet Peering vs Global VNet Peering</li><li>Azure DNS and Azure DNS Private Resolver</li><li>Azure VPN Gateway</li><li>Azure Express Route and its models: colocation, point-to-point ethernet, any-to-any and directly from Express Route.</li><li>Azure Private Links and Private Endpoints</li></ul><p><em>5- Core Azure Storage Services and Products</em></p><ul><li>Azure Storage Accounts and its types: standard general purpose v2, premium block blobs, premium file shares and premium page blobs. Also it is important to know the boundaries of this service (# storage accounts per region for example)</li><li>Azure Blob Storage vs Storage Account and vs Blob Objects</li><li>Access Tiers: Hot Access, Cool Access and Archive Access.</li><li>Azure Files and its use cases</li><li>Azure Queues</li><li>Azure Table Storage (schemaless)</li><li>Azure Managed Disks and its types: ultra disk, premium SSD, premium SSD v2, standard SSD and standard HDD</li><li>Azure Disk Roles</li><li>Redundancy options: LRS vs ZRS and GRS vs GZRS</li></ul><p><em>6- Moving and Migrating Data in Azure</em></p><ul><li>What is AZCopy</li><li>Storage Explorer</li><li>Azure File Sync</li><li>Azure Migrate and its offerings</li></ul><p><em>7- Security, Private, Compliance and Trust</em></p><ul><li>Defense in Depth: the principles (CIA model) and the layers of protection</li><li>Azure Firewall</li><li>Azure DDoS Protection: compare the 2 tiers — Basic vs Standard</li><li>Azure Network Security Groups (NSG)</li><li>Authentication vs Authorization</li><li>Azure Active Directory: compare its licenses — Free vs Premium P1 vs Premium P2</li><li>Azure AD Identity Protection vs Privileged Identity Management</li><li>Azure AD Domain Services</li><li>Azure AD B2B and B2C</li><li>Azure AD Authentication options: SSPR, MFA and Passwordless Authentication</li><li>Azure AD Conditional Access</li><li>Azure RBAC (Role based access control): look for the common built-in roles like Global Admin, User Admin, Billing Admin and others.</li><li>Azure Tags and Azure Monitor</li><li>Azure Service Health</li><li>For Azure Governance Methodologies: Azure Policy, RBAC, Resource Locks, Azure Blueprints and Azure Advisor</li><li>Trust Center vs Azure Trust Portal</li><li>Compliance Manager</li><li>Azure Government and Azure China</li></ul><p><em>8- Azure Pricing and Support</em></p><ul><li>Pricing Calculator</li><li>TCO Calculator</li><li>Cost Management Tool</li><li>Support Plan Options: Basic vs Developer vs Standard vs Professional</li><li>Service Level Agreements: Availability metrics (MTO, MTF) and Recovery Metrics (RTO, RPO)</li><li>What is a composite SLA? What happens if Azure makes a SLA violation?</li><li>Service Lifecycle: development phase → public review/private review → general availability</li><li>Modern Lifecycle Policy vs Fixed Lifecycle Policy</li></ul><p><em>9- Some important Azure Services you must know (at least its definition)</em></p><ul><li>Azure Service Bus</li><li>Azure DevOps</li><li>Azure DevTestLabs</li><li>Azure Synapse</li><li>Azure Machine Learning Studio</li><li>Azure Application Insights</li><li>Azure Event Grid</li><li>Azure Sentinel</li><li>Azure Security Center</li><li>Azure Traffic Manager (DNS-based traffic)</li><li>Azure Repos</li><li>IoT (IoT Edge, IoT Hub, Iot Central and Time Series Insights)</li><li>Azure Stack</li><li>Azure Arc</li></ul><h3><strong>Conclusion</strong></h3><p>In this article, you see some tips about how you can study for the Azure Fundamentals exam (AZ-900). As always, reading the documentation and taking some online courses may guide you to know the proper concepts that are going to be tested on the exam.</p><p>Finally, by using <strong>active recall</strong> with <strong>spaced repetition,</strong> you can prepare yourself not only for the exam, but also to keep that knowledge for future projects!</p><h3>References</h3><ul><li><a href="https://elearningindustry.com/forgetting-curve-combat">https://elearningindustry.com/forgetting-curve-combat</a></li><li><a href="https://www.udemy.com/course/az-900-azure-exam-prep-understanding-cloud-concepts/">https://www.udemy.com/course/az-900-azure-exam-prep-understanding-cloud-concepts/</a></li><li><a href="https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE3VwUY">Azure Fundamentals (AZ-900) Exam Guide</a></li></ul><h4>HAPPY LEARNING!</h4><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a> | <a href="https://luismiguelmiranda.com/">Personal Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf343da45b87" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/tips-to-pass-the-az-900-azure-fundamentals-exam-feat-active-recall-technique-cf343da45b87">Tips to pass the AZ-900 Azure Fundamentals Exam (feat. Active Recall Technique)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping: How to Use Python to Collect Data from the Web]]></title>
            <link>https://blog.devgenius.io/web-scraping-how-to-use-python-to-collect-data-from-the-web-d66a0fb94176?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d66a0fb94176</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 17:02:40 GMT</pubDate>
            <atom:updated>2023-01-22T23:34:20.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADWrVZUd0Or8eU7VidO1kg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5Ntkpxqt54Y">Sai Kiran Anagani</a> (<a href="https://unsplash.com/">unsplash.com</a>)</figcaption></figure><h3>Overview</h3><p>For example, when creating a data science project, you start with a data extraction. Today, you can find structured datasets from many sites, including Kaggle and GCP’s public datasets. But what if there is no data available on these resources? Web scraping!</p><p>This article provides a basic explanation of the technique, some common use cases, and a practical exercise with Python.</p><h3><strong>What is Web Scraping?</strong></h3><p>Web scraping is a technique for extracting data from websites. Since we’re dealing with a website, this technique involves using an HTTP (or HTTPS) request to retrieve the HTML code (or XML) and parse the code to extract the interesting data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEDOQMSuzdTb7BoH2b-OiA.png" /><figcaption><strong>Web Scraping Workflow</strong> (Source: Own Elaboration)</figcaption></figure><h3><strong>What are the most common use cases for web scraping?</strong></h3><p>Based on the definition of web scraping, this technique is very flexible for different scenarios such as:</p><ol><li><strong>Web Monitoring</strong>: Track website changes over time.</li><li><strong>Customer Relationship Management (CRM)</strong>: Allows you to ‘deep down’ your website to extract customer and business information, including preferences and more. This helps improve lead generation.</li><li><strong>Data Mining</strong>: We may collect data about our products and customers to determine current market trends. Another example is scraping data from sports websites and analyzing team performance.</li><li><strong>Social Media Analytics</strong>: for marketing purposes.</li><li><strong>Search Engine Optimization (SEO)</strong>: Improve your search engine ranking.</li></ol><p>It looks really fun! So anyone can extract data from all websites available for his own “purpose”, but …</p><p><strong>Is it legal to do Web Scraping?</strong></p><p><strong>Yes and No.</strong> Of course, it depends on the situation and the purpose of the scraping. The most important thing to consider before starting online web scraping is the copyright restrictions of the country and the website itself.</p><h3><strong>How to make web scraping with Python</strong></h3><p>In Python, we can make web scraping by using the <strong>BeautifulSoup</strong> library. So, before starting, we need to install it.</p><pre>pip3 install beautifulSoup4</pre><p><strong>Project’s Scenario</strong></p><p>I found a website whose main purpose is to practice scraping skills. It’s a dummy site that mimics a bookstore (website: <a href="https://books.toscrape.com/">https://books.toscrape.com/</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xutbQSQhekIPb3OlGmGvqg.png" /><figcaption>Source: <a href="https://books.toscrape.com/index.html">Books to Scrape</a></figcaption></figure><p>Suppose you want to get a list of book categories (travel, mystery, historical fiction, etc.). We’ll use BeautifulSoup for this, but first let’s talk about the most common features that this library offers.</p><p><strong>a-</strong> Creating a BeautifulSoup object</p><pre>import request<br>import BeautifulSoup<br><br>url = [YOUR URL]<br>page = requests.get(url)<br>soup = BeautifulSoup(page.content, &quot;html.parser&quot;)</pre><p>In this case we are creating a BeautifulSoup object called soup and using a HTML parser. By the way, there are other parsers like <strong>lxml</strong> or <strong>html5lib.</strong></p><p><strong>b-</strong> To make a “prettified” version of the HTML/XML you can use soup.prettify().</p><p><strong>c-</strong> To get the title of the HTML, you may use soup.title.</p><p><strong>d-</strong> To search an specific tag or element inside a document:</p><pre>html_element = soup.find()</pre><p>To find the next div in the document you may use soup.find(‘div&#39;).</p><p><strong>e-</strong> To search all occurrences for an specific tag or HTML element:</p><pre>Html_elements = soup.find_all()</pre><p>This returns an array with all the occurrences, including the child, grandchild, great grandchild (and so on) elements. To avoid looking for all the occurrences and just considering the child elements, you can set the parameter recursive to False.</p><p><strong>f-</strong> To get the text of a tag element, you may use element.getText() or element.text.</p><p>We know a little about the main features, now we must know what are the HTML tags associated with each book category name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyV3lfmcQn3O5El_KIa3AA.png" /><figcaption>Analyzing the BookStore Website (Source: <a href="https://books.toscrape.com/index.html">Books to Scrape</a>)</figcaption></figure><p>Based on the analysis, I made this code:</p><pre>book_category_list = []<br><br>url = &quot;https://books.toscrape.com&quot;<br>page = requests.get(url)<br>soup = BeautifulSoup(page.content, &quot;html.parser&quot;)<br><br>results = soup.find(&#39;div&#39;,class_=&quot;container-fluid page&quot;)<br>div_sidebar = results.find(&#39;aside&#39;,class_=&quot;sidebar&quot;)<br>list_books_li = div_sidebar.find_all(&#39;li&#39;)<br><br>for li_element in list_books_li:<br>   book_category_a = li_element.find(&#39;a&#39;)<br>   book_category_list.append(book_category_a.text.strip().lower())<br><br>print(book_category_list)</pre><p>This is the result:</p><pre>[&#39;books&#39;, &#39;travel&#39;, &#39;mystery&#39;, &#39;historical fiction&#39;, &#39;sequential art&#39;, &#39;classics&#39;, &#39;philosophy&#39;, &#39;romance&#39;, &#39;womens fiction&#39;, &#39;fiction&#39;, &#39;childrens&#39;, &#39;religion&#39;, &#39;nonfiction&#39;, &#39;music&#39;, &#39;default&#39;, &#39;science fiction&#39;, &#39;sports and games&#39;, &#39;add a comment&#39;, &#39;fantasy&#39;, &#39;new adult&#39;, &#39;young adult&#39;, &#39;science&#39;, &#39;poetry&#39;, &#39;paranormal&#39;, &#39;art&#39;, &#39;psychology&#39;, &#39;autobiography&#39;, &#39;parenting&#39;, &#39;adult fiction&#39;, &#39;humor&#39;, &#39;horror&#39;, &#39;history&#39;, &#39;food and drink&#39;, &#39;christian fiction&#39;, &#39;business&#39;, &#39;biography&#39;, &#39;thriller&#39;, &#39;contemporary&#39;, &#39;spirituality&#39;, &#39;academic&#39;, &#39;self help&#39;, &#39;historical&#39;, &#39;christian&#39;, &#39;suspense&#39;, &#39;short stories&#39;, &#39;novels&#39;, &#39;health&#39;, &#39;politics&#39;, &#39;cultural&#39;, &#39;erotica&#39;, &#39;crime&#39;]</pre><p><strong>Note</strong>: Imagine that while I’m using the find method twice, I’m walking from the parent tags to the child tags.</p><p>And that’s a little example of web scraping with Python!</p><p>In my <a href="https://github.com/luismirandad27/de-python-bookstore-web-scraping"><strong>GitHub repo</strong></a>, you can find the complete code that fetches the book category list, then extracts the information for each book available on the site and saves that information to a CSV file.</p><h3><strong>Conclusions</strong></h3><p>I hope you found this article useful. You’ve seen a simple definition of web scraping and its use cases. This helps us see this technique as a very powerful data extraction tool.</p><p>Finally, BeautifulSoup is a very interesting library in Python that helps parse HTML code and simplify website scraping. Once you have data that you think is relevant, you can start analyzing it or building a machine learning model.</p><h3><strong>References</strong></h3><ul><li><a href="https://www.analyticsvidhya.com/blog/2022/09/web-scraping-tool-for-data-engineering/#:~:text=Web%20Scraping%20for%20Data%20Scientists,this%20information%20and%20extend%20possibilities">Web Scraping: Tool for Data Engineering</a></li><li><a href="https://realpython.com/beautiful-soup-web-scraper-python/">Beautiful Soup: Build a Web Scraper With Python</a></li><li><a href="https://hub.packtpub.com/getting-started-with-web-scraping-with-beautiful-soup/">Getting started with Web Scraping with Beautiful Soup</a></li></ul><p><strong>HAPPY LEARNING!</strong></p><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a> | <a href="https://luismiguelmiranda.com/">Personal Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d66a0fb94176" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/web-scraping-how-to-use-python-to-collect-data-from-the-web-d66a0fb94176">Web Scraping: How to Use Python to Collect Data from the Web</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Apache Airflow (feat Astronomer)]]></title>
            <link>https://medium.com/@lmirandad27/getting-started-with-apache-airflow-feat-astronomer-6e8cb239b784?source=rss-b69755d413a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e8cb239b784</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Luis Miguel Miranda]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 16:02:18 GMT</pubDate>
            <atom:updated>2023-01-22T23:32:50.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWs4Fc1T5g1-IPL6VXZqBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/w7ZyuGYNpRQ">Kevin Ku</a> (<a href="http://unsplash.com/">unsplash.com</a>)</figcaption></figure><h3>Overview</h3><p>Last month, I had the opportunity to complete the Apache Airflow Fundamentals preparation and certification course offered by Astronomer and I was able to learn more about this amazing tool. Apache Airflow is an <strong>open source orchestrator</strong> that helps to programmatically schedule and monitor workflows. It certainly has many advantages compared to CRON jobs: it’s dynamic, highly scalable, and highly interactive.</p><p>One way to keep learning about Airflow is by participating in small projects that put what you’ve learned into practice. In this article, I’ll cover what I learned and how to use Astronomer, an Airflow-powered data orchestration platform, to create my first workflow.</p><p>Let’s get started!</p><h3><strong>Core Concepts with Airflow</strong></h3><p>I’ve given you a little overview of Apache Airflow. Before explaining what my project is, let’s talk about some important concepts:</p><p><strong>The main components</strong></p><p>There are 5 important components:</p><ol><li><strong>Web Server</strong>: it provides a website with an interactive UI where you can monitor your workflows and make additional configurations, like setting your connections.</li><li><strong>Scheduler</strong>: like any data workflow, you need to plan. This does the job.</li><li><strong>Database</strong>: it stores the metadata about the DAG (workflow), its tasks, etc. You may see the name “Metastore” on other websites and articles.</li><li><strong>Executor</strong>: it’s connected to the scheduler and basically defines which workers run which tasks. If you are familiar with the Spark architecture, Airflow’s executors are analogous to Spark’s cluster managers.</li><li><strong>Worker(s)</strong>: they will execute the tasks assigned by the Executor.</li></ol><p>If we can draw the Airflow’s architecture with these components, we have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*QQY_OPHWDl4R3-HI3_srRw.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>This case applies to <em>multi-node architectures</em>. That is, each worker is assigned to a node. If we use a <em>single-node architecture</em>, we can conclude that all these components are stored together in one node.</p><p><strong>Core Concepts</strong></p><p>Now you know the main components, let’s talk about some important concepts:</p><ul><li><strong>DAG (Directed Acyclic Graph)</strong>: basically, it’s your data pipeline.</li><li><strong>Operators</strong>: these are the task types for your pipeline. There are 3 types:</li></ul><p><em>Action Operators</em>: for batch, python and SQL executions.</p><p><em>Transfer Operators</em>: when you send data from a source to a destination.</p><p><em>Sensor Operators</em>: this type refers to a task that will wait for something to start (could be an event).</p><ul><li><strong>Task</strong>: this is an operator instance. Making an analogy with object-oriented programming, an operator is a class and a task is an instance of the class. Note: A DAG can contain many tasks, which can be linked together via dependencies.</li><li><strong>Dependencies</strong>: can be used to create “connections” between tasks. One important thing to remember is that loop dependencies should be avoided.</li></ul><p><strong>Task Lifecycle</strong></p><p>How do all the previous components interact in between when a new task appears? Let’s find out with this diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Lz6lg2Uh_HF_kaoS1oflcQ.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>When you create a DAG, it will be saved in the DAG folder. You can see your DAGs in your web server and scheduler.</p><ol><li>If the Scheduler determines that the time to execute the DAG arrives, a new <em>DAG Run</em> is going to be created and stored in the Metastore.</li><li>When a Task must be executed, a new <em>task instance</em> is created and also stored in the Metastore.</li><li>The scheduler will send the task instance to the Executor. The Executor will manage this task instance by assigning it to the right worker.</li><li>Each time the task instance changes its status, this information will be updated in the Metastore. This is crucial because the database must reflect the current status of the task.</li><li>All the information about the DAG and the tasks executions must be reflected correctly in the Web Server.</li></ol><p>The Scheduler will constantly asks if all work is done. If this is true, the status will be updated in the Metastore.</p><h3><strong>Deploying a Data Workflow with Astronomer</strong></h3><p><strong>Requirements</strong></p><p>Astronomer allows you to develop many workflows easily. You can see that all the components of the workflow can be created using a few commands. But first, let’s install the dependencies.</p><p>1- Installing docker and astro:</p><pre>brew install docker<br>brew install astro</pre><p>2- Creating your airflow project folder</p><p>First, locate in the directory where you want to have your project, then use the following:</p><pre>mkdir astro-project<br>cd astro-project<br><br>:: Create project components<br>astro dev init</pre><p>3-<em> </em>Configure your dag</p><p>In your <em>/dag </em>folder, you will store your DAG files. In this location, let’s create a DAG file called <em>test_dag.py</em> (yes, DAG files are written in Python).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*EwpOqwZvh75_uHaJ5sOQtQ.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>The code below is for a DAG object with two tasks. Based on the soccer player information stored in an array, the first task outputs information about the team they are playing for, and the second task outputs the player’s nationality.</p><pre># Importing Libraries for Apache Airflow<br>from airflow import DAG<br>from airflow.operators.python_operator import PythonOperator<br>from airflow.operators.bash import BashOperator<br><br>from datetime import datetime,timedelta<br><br># To store default configurations for all tasks, we can create one dictionary<br># with all the configurations.<br>default_args ={<br>    &#39;owner&#39;: &#39;me&#39;, <br>    &#39;retries&#39;: 1,<br>    &#39;start_date&#39;:datetime(2022,12,21)<br>}<br><br># Creating a DAG object called &#39;test_dag&#39;<br>dag = DAG(<br>    &#39;test_dag&#39;,<br>    default_args = default_args<br>)<br><br># For the example this is the array with information of 3 soccer players<br>players = [<br>        {&#39;playerName&#39;:&#39;Kylian Mbappé&#39;,&#39;playerTeam&#39;:&#39;PSG&#39;,&#39;playerNationality&#39;:&#39;France&#39;},<br>        {&#39;playerName&#39;:&#39;Lionel Messi&#39;,&#39;playerTeam&#39;:&#39;PSG&#39;,&#39;playerNationality&#39;:&#39;Argentina&#39;},<br>        {&#39;playerName&#39;:&#39;Luca Modric&#39;,&#39;playerTeam&#39;:&#39;Real Madrid&#39;,&#39;playerNationality&#39;:&#39;Croatia&#39;}<br>    ]<br><br># This methods is for task 1<br>def print_players_teams():<br>    for player in players:<br>        print(f&quot;Player {player[&#39;playerName&#39;]} is playing for {player[&#39;playerTeam&#39;]} team.&quot;)<br><br># This methods is for task 2<br>def print_players_nationalities():<br>    for player in players:<br>        print(f&quot;Player {player[&#39;playerName&#39;]} is from {player[&#39;playerNationality&#39;]}.&quot;)<br><br><br># To create a task that run a python method we need to use a Python Operator<br><br># Creating a Task object for the first task<br>task_print_players_teams = PythonOperator(<br>    task_id = &#39;task_print_players_teams&#39;,<br>    dag = dag,<br>    python_callable = print_players_teams<br>)<br><br># Creating a Task object for the second task<br>task_print_players_nationalities = PythonOperator(<br>    task_id = &#39;task_print_players_nationalities&#39;,<br>    dag = dag,<br>    python_callable = print_players_nationalities<br>)<br><br># To set the dependencies between dependencies we can use the following<br>task_print_players_teams &gt;&gt; task_print_players_nationalities<br><br># In this case the second task cannot run until the first one ran successfully.</pre><p>4- Start your airflow service</p><p>To test your DAG you need to start your airflow service. In your terminal, go to your folder project and type the following:</p><pre>astro dev start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CQdjaHGoNF1MOrc0giLzw.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>You will notice that 4 processes are running:</p><ul><li>Postgres service: refers to the Metastore Database</li><li>Scheduler</li><li>Triggerer</li><li>Web Server</li></ul><p>Finally, to access the Web Server go to <em>localhost:8080</em> in your web browser (username and password is <em>admin</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGLy7sIY4RTUe2qCBBeWqA.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>You will see that your DAG is in your airflow service. Remember that each time you update your dag file, the web server will update the UI automatically.</p><p>Click on the DAG name to see the details, in this case I will choose the <em>Graph View</em> to see the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UaCdklmWeDFgauFFzAjcg.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>Run your DAG by clicking the <em>Play</em> icon on the right side of your screen. Go to Browse/Dag Runs to see your executions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuEKCUUmNFUvAxjciqGmKQ.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>You will see the last execution and the last status. Click on the <em>Run Id</em>, go to the <em>Graph View</em> and see your tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBaohxDpQC8sD3QPuacWUA.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>If you click in one of your tasks, select on <em>Logs</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSLGqGzSYs0wknsQ0yPAHw.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>You will see that we are actually printing the information that we want to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqqL9o6w0B8DomDxnKnVWQ.png" /><figcaption>Source: Own Elaboration</figcaption></figure><p>And that’s it! I know, it is a simple example but it’s a good starting point.</p><p>If you want to stop your Airflow service, go to your Terminal, locate your Airflow project folder and type:</p><pre>astro dev stop</pre><p>By the way, I made an ETL batch process with Apache Airflow (Astronomer) where I’m extracting 3 CSV files from a AWS S3 bucket, transforming the data and loading into new tables. Those outputs datasets (stored in parquet) will be datasets for an AWS Quicksight Dashboard. All this processing was made with PySpark so you can integrate Spark Processing with Airflow!!</p><p><strong>Go to my </strong><a href="https://github.com/luismirandad27/de-fifa-world-cup-data-pipeline-airflow-pyspark"><strong>GitHub</strong></a><strong> to find out!</strong></p><h3>Conclusion</h3><p>We have seen the basic and important concepts of Apache Airflow: the main components, core concepts and its architecture. We also found that thanks to Astronomer we can manage our Airflow projects faster and easier.</p><p>Other concepts such as using tools and providers, adding new connections, using REST APIs, and backfilling processes are also important when building DAGs. I hope this article has inspired you to learn more about this tool and put it into practice in your projects!</p><p>I highly recommend taking Apache Airflow Fundamentals Preparation Course by <a href="https://academy.astronomer.io/astronomer-certification-apache-airflow-fundamentals-preparation">Astronomer</a>. This is useful for getting a comprehensive overview of Apache Airflow.</p><p><strong>HAPPY LEARNING!</strong></p><p>Follow me: <a href="https://www.linkedin.com/in/lmirandad27/">LinkedIn</a> | <a href="https://github.com/luismirandad27">GitHub</a> | <a href="https://luismiguelmiranda.com/">Personal Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e8cb239b784" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>