<?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 Felipe Fernandez on Medium]]></title>
        <description><![CDATA[Stories by Felipe Fernandez on Medium]]></description>
        <link>https://medium.com/@ofelipefernandez?source=rss-f6f5e20b4e8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cpTyFxhRXKAHfMNimFZRcQ.jpeg</url>
            <title>Stories by Felipe Fernandez on Medium</title>
            <link>https://medium.com/@ofelipefernandez?source=rss-f6f5e20b4e8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:15:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ofelipefernandez/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[Vector Search- movie recommendation using MongoDB and HuggingFace]]></title>
            <link>https://medium.com/@ofelipefernandez/vector-search-movie-recommendation-using-mongodb-and-huggingface-56fc960b8ba7?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fc960b8ba7</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Thu, 23 May 2024 16:13:57 GMT</pubDate>
            <atom:updated>2024-05-23T16:13:57.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Leveraging the power of Vector Search in MongoDB and the advanced Natural Language Processing (NLP) capabilities of HuggingFace. We’ll explore how to use these technologies to create a system that can understand a user’s query and recommend movies based on the semantic meaning of the query</p><p>The code snippet provided is part of a larger system that uses HuggingFace to generate embeddings for movie plots and MongoDB to store and search these embeddings. This approach allows us to go beyond simple keyword-based search and provide recommendations that truly understand the user’s intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ii-ggJshMzBDVCIV.png" /></figure><h3>Create MongoDB database</h3><ul><li>Create MongoDB account:</li><li>Create a cluster:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*xZxKegCWE-hZpxOwI_FIqA.png" /></figure><ul><li>Click on Load Sample Data and wait for the sample data to be deployed</li><li>Go to collection sample_mflix and query on some data</li></ul><h3>HuggingFace embeddings</h3><ul><li>Create a HuggingFace Access Token:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*l0XDAo2o-QjT2E2BI3Chuw.png" /></figure><ul><li>Create a function that generates embeddings using HuggingFace</li></ul><pre>hf_token=os.getenv(&#39;HF_token&#39;)<br>embedding_url = &quot;https://api-inference.huggingface.co/pipeline/feature-extraction/sentence-transformers/all-MiniLM-L6-v2&quot;<br><br>#Generate embedding function<br>def generate_embedding(text: str) -&gt; list[float]:<br><br>  response = requests.post(<br>    embedding_url,<br>    headers={&quot;Authorization&quot;: f&quot;Bearer {hf_token}&quot;},<br>    json={&quot;inputs&quot;: text})<br><br>  if response.status_code != 200:<br>    raise ValueError(f&quot;Request failed with status code {response.status_code}: {response.text}&quot;)<br><br>  return response.json()<br><br>query = &quot;Felipe  is the best data engineer in the world!&quot;<br>print(generate_embedding(query))<br></pre><p>Prints a list of Floating numbers, which is the embedding vector generated for the query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*0bsGG844LMbiXiIPimjXig.png" /></figure><p>Everything is working so far.</p><h3>Create vector embeddings</h3><p>Create vector embeddings for a certain number of documents, 50 in this case, with the field plot in my moviescollection,</p><p>We will create a new field within the original collection called plot_embedding_hf</p><pre># Create a new client and connect to the server<br>client = MongoClient(uri)<br>db = client.sample_mflix #Select the mflix database<br>collection = db.movies   #Select the movies collection<br><br>for doc in collection.find({&#39;plot&#39;:{&quot;$exists&quot;: True}}).limit(50):<br>   doc[&#39;plot_embedding_hf&#39;] = generate_embedding(doc[&#39;plot&#39;])<br>   collection.replace_one({&#39;_id&#39;: doc[&#39;_id&#39;]}, doc)</pre><p>Going back to the database and verifying that the collection has been updated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7GwunLu8_s8ewqxLJmdzA.png" /></figure><p>As we can see the plot_embedding_hf field has been created with an array of length 384.</p><p>I can modify it to run it for every single document in the collection, but to do so the free endpoint will not work due to the rate limit, so I’ll just keep it for a subsample of documents.</p><h3>Create Search Index</h3><ul><li>Go to Search&gt;Create Search Index&gt;JSON Editor&gt;samples_mflix.movies</li></ul><p>Copy and paste the following:</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;dynamic&quot;: true,<br>    &quot;fields&quot;: {<br>      &quot;plot_embedding_hf&quot;: [<br>        {<br>          &quot;dimensions&quot;: 384,<br>          &quot;similarity&quot;: &quot;dotProduct&quot;,<br>          &quot;type&quot;: &quot;knnVector&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p><strong>knnVector </strong>tells Atlas Search that the plot_embedding_hf field contains vector embeddings, used in machine learning tasks like finding similar items.</p><p><strong>dimensions: 384 </strong>This specifies that the vectors in the plot_embedding_hffield have 384 dimensions. Each dimension represents a specific aspect of the data being encoded.</p><p><strong>similarity: “dotProduct”.</strong> This defines the method used to compare the query vector with the indexed vectors. The dotProduct method calculates the cosine similarity between the two vectors. Cosine similarity measures how similar two vectors are in direction, regardless of their magnitude.</p><h3>Vector Search</h3><p>Perform a vector Search in the MongoDB collection to find the document which plot_embedding_hf field is semantically similar to the provided query, consider the name of the index created in the previous step.</p><pre>query = &quot;Movie about dinosaurs&quot;<br><br>results = collection.aggregate([<br>  {&quot;$vectorSearch&quot;: {<br>    &quot;queryVector&quot;: generate_embedding(query),<br>    &quot;path&quot;: &quot;plot_embedding_hf&quot;,<br>    &quot;numCandidates&quot;: 100,<br>    &quot;limit&quot;: 4,<br>    &quot;index&quot;: &quot;PlotSemanticSearch&quot;,<br>      }}<br>]);<br><br>for document in results:<br>    print(f&#39;Movie Name: {document[&quot;title&quot;]},\nMovie Plot: {document[&quot;plot&quot;]}\n&#39;)</pre><p>This is what I get when running it in the 50 movies we created the vector embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*RNegyNOolAxkjNMBE8eCsw.png" /></figure><p>As you can see, the first movie is about a Dinosaur, the result I expected.</p><p>References: <br>- <a href="https://www.youtube.com/watch?v=JEBDfGqrAUA&amp;t=657s">https://www.youtube.com/watch?v=JEBDfGqrAUA&amp;t=657s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fc960b8ba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with dbt: My learning process with the dbt Fundamentals course]]></title>
            <link>https://medium.com/@ofelipefernandez/getting-started-with-dbt-my-learning-process-with-the-dbt-fundamentals-course-7815eeb573e4?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7815eeb573e4</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 03:57:26 GMT</pubDate>
            <atom:updated>2024-04-27T03:57:26.466Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is dbt?</strong></h3><p>As explained by dbt itself:</p><p>“dbt is a transformation workflow that helps you get more work done while producing higher quality results. You can use dbt to modularize and centralize your analytics code, while also providing your data team with guardrails typically found in software engineering workflows. Collaborate on data models, version them, and test and document your queries before safely deploying them to production, with monitoring and visibility.</p><p>dbt compiles and runs your analytics code against your data platform, enabling you and your team to collaborate on a single source of truth for metrics, insights, and business definitions. This single source of truth, combined with the ability to define tests for your data, reduces errors when logic changes, and alerts you when issues arise.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*AiP3NEjI6FMnvtUk" /><figcaption>Image by dbt</figcaption></figure><h3>Connect dbt Cloud to BigQuery.<a href="https://docs.getdbt.com/guides/bigquery?step=1#introduction">​</a></h3><p>In this quickstart guide, you’ll learn how to use dbt Cloud with BigQuery. It will show you how to:</p><ul><li>Create a Google Cloud Platform (GCP) project.</li><li>Connect dbt Cloud to BigQuery.</li><li>Take a sample query and turn it into a model in mydbt project.</li><li>Add tests to my models.</li><li>Document my models.</li><li>Schedule a job to run.</li></ul><p>I followed the steps in the guide “Quickstart for dbt Cloud and BigQuery”, once you reach step 7- “Initialize Your dbt Project and Start Developing” I continued with the course.</p><h3><strong>Models:</strong></h3><ul><li><strong>What are models?</strong></li></ul><p>In dbt, models are the building blocks for transforming data in your warehouse. They are essentially SQL scripts wrapped in a YAML configuration file, defining how raw data is transformed into clean, usable tables. Each model performs a specific transformation task, making your data pipeline easy to understand and maintain. Models are primarily written as a select statement and saved as a .sql file.</p><ul><li><strong>What is modularity?</strong></li></ul><p>Modularity refers to breaking down complex tasks into smaller, independent units. In dbt, this translates to creating well-defined, reusable models. Each model focuses on a specific transformation step, avoiding redundant code and promoting cleaner, more maintainable data pipelines.</p><ul><li><strong>Modularity and the ref function</strong></li></ul><p>The ref function is a powerful tool that enables modularity within dbt models. It allows you to reference other models within your current model&#39;s SQL code. This means you can leverage pre-defined transformations from other models, eliminating the need to repeat code and ensuring consistency throughout your data pipeline.</p><p>I created a model named “customers.sql” with the following SQL select statement.</p><pre>with customers as (<br><br>    select * from {{ ref(&#39;stg_customers&#39;) }}<br><br>)... #the code continues<br></pre><p>When you execute dbt run, dbt will build this as a <em>view</em> named customers in your target schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LiVJwPKEKsBh-s2jpnnOQ.png" /></figure><h3>Sources:</h3><p>Sources make it possible to name and describe the data loaded into your warehouse by your Extract and Load tools. By declaring these tables as sources in dbt, you can then:</p><ul><li>select from source tables in your models using the {{ source() }} function, helping define the lineage of your data</li><li>test your assumptions about your source data</li><li>calculate the freshness of your source data</li></ul><p><strong>Declaring a source:</strong></p><p>Creating a file named “src_jaffle_shop.yml” within the models folder.</p><pre>version: 2<br><br>sources:<br>  - name: jaffle_shop<br>    database: dbt-tutorial<br>    schema: jaffle_shop<br>    tables:<br>      - name: customers<br>      - name: orders</pre><p><strong>Selecting from sources:</strong></p><pre>#models/stg_orders.sql<br>select<br>    id as order_id,<br>    user_id as customer_id,<br>    order_date,<br>    status<br><br>from {{ source(&#39;jaffle_shop&#39;, &#39;orders&#39;) }}<br><br>#models/stg_customers.sql<br>select <br>    id as customer_id,<br>    first_name,<br>    last_name<br>from {{ source(&#39;jaffle_shop&#39;, &#39;customers&#39;) }}<br></pre><p>Using the {{ source () }} function also creates a dependency between the model and the source table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*uL1O22ZvEyLtfMVZYeNiQw.png" /></figure><h3><strong>Testing:</strong></h3><p>Data tests are assertions you make about your models and other resources in your dbt project (e.g. sources, seeds and snapshots). When you run dbt test, dbt will tell you if each test in your project passes or fails.</p><p>There are two ways of defining data tests in dbt:</p><ul><li>A singular data test is testing in its simplest form: If you can write a SQL query that returns failing rows, you can save that query in a .sql file.</li><li>A generic data test is a parameterized query that accepts arguments. The test query is defined in a special test block.</li></ul><p>Adding tests to the models:</p><ol><li>Create a new YAML file in the models directory, named models/schema.yml</li></ol><pre>version: 2<br><br>models:<br>  - name: customers<br>    columns:<br>      - name: customer_id<br>        tests:<br>          - unique<br>          - not_null<br><br>  - name: stg_customers<br>    columns:<br>      - name: customer_id<br>        tests:<br>          - unique<br>          - not_null<br><br>  - name: stg_orders<br>    columns:<br>      - name: order_id<br>        tests:<br>          - unique<br>          - not_null<br>      - name: status<br>        tests:<br>          - accepted_values:<br>              values: [&#39;placed&#39;, &#39;shipped&#39;, &#39;completed&#39;, &#39;return_pending&#39;, &#39;returned&#39;]<br>      - name: customer_id<br>        tests:<br>          - not_null<br>          - relationships:<br>              to: ref(&#39;stg_customers&#39;)<br>              field: customer_id</pre><ul><li>unique: This test ensures that the customer_id, order_idcolumns have no duplicate values.</li><li>not_null: This test verifies that the customer_id, order_id columns do not contain any null values.</li><li>accepted_values: This test checks if the values in the status column are within a predefined list of acceptable values. In this case, the accepted values are &#39;placed&#39;, &#39;shipped&#39;, &#39;completed&#39;, &#39;return_pending&#39;, and &#39;returned&#39;.</li></ul><p>Checking that all tests have passed by running dbt test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*LSNl9Cm-Tc4blA5To9XK-Q.png" /></figure><h3>Documentation:</h3><p>Adding descriptions to your dbt project makes it easier to explain what your models do. This helps your teammates understand the data and work together.</p><ol><li>Update your models/schema.yml file to include some descriptions on each value, in this case in “models” and “columns”</li></ol><pre>version: 2<br><br>models:<br>  - name: customers<br>    description: One record per customer<br>    columns:<br>      - name: customer_id<br>        description: Primary key<br>        tests:<br>          - unique<br>          - not_null<br>      - name: first_order_date<br>        description: NULL when a customer has not yet placed an order.</pre><p>By running dbt docs generate dbt takes a look at your project and the data warehouse you’re using, then builds a simple file (called JSON) that explains everything in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*v3Z1Sl5PmgESSeozkKqCwQ.png" /></figure><p>By clicking in “View docs” you can take a look at the docs generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg4u0-tz5jcTiwq1lVwPtA.png" /></figure><p>In the documentation, you can see a representation of the project structure, a markdown description for a model, and a list of all of the columns in the model.</p><h3>Deployment:</h3><p>Refers to the process of moving your dbt project and its models from a development environment to a production environment where the data transformations impact the data used for analytics.</p><ul><li><strong>Environments:</strong> dbt typically uses separate environments for development, staging, and production. This allows you to test and validate your data transformations before pushing them to production and potentially impacting real-world data.</li><li><strong>Deployment Workflow:</strong> The deployment workflow involves switching your dbt profile to point to the target environment (e.g., production) and running the appropriate dbt commands to execute the models.</li><li><strong>Automation:</strong> Many teams leverage CI/CD pipelines (Continuous Integration/Continuous Delivery) to automate the deployment process. This ensures consistency and reduces the risk of human error.</li><li><strong>Version Control:</strong> Version control systems like Git are crucial for managing changes to your dbt models. They allow you to track changes, revert to previous versions if necessary, and collaborate effectively on model development.</li></ul><h3>Create and run a job<a href="https://docs.getdbt.com/guides/bigquery?step=15#create-and-run-a-job">​</a></h3><p>Jobs are a set of dbt commands that you want to run on a schedule. For example, dbt build.</p><p>Create the deployment environment and manually Run your job by clicking on “Run now”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*-lvQREl7H30QItb0rqflvA.png" /></figure><p>As you can see the Environment displays all the recent runs in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*3UA39c7l45PC-_kppPWKTg.png" /></figure><p>And you can also explore in detail the Run information and progress.</p><h3>Final thoughts:</h3><p>dbt has become a super helpful tool for working with data warehouses. By focusing on building things in smaller, reusable pieces, keeping good notes, and having a clear process to move things from development to production, it makes data pipelines easier to build, understand, and keep running smoothly.</p><p><strong>Pros of dbt:</strong></p><ul><li><strong>Break it Down:</strong> Complicated data transformations can be broken down into smaller, reusable chunks. This makes your code cleaner and easier to work with for everyone.</li><li><strong>Data on Point:</strong> dbt has built-in tests to make sure your data is accurate and consistent, every time.</li><li><strong>Teamwork:</strong> Clear documentation helps everyone understand what your data models are doing, saving time and confusion.</li><li><strong>Easy Deployment:</strong> Moving your models from development to where they’re used is simple with dbt’s different settings and automation features.</li></ul><p><strong>References:</strong></p><ul><li><a href="https://docs.getdbt.com/guides/bigquery">https://docs.getdbt.com/guides/bigquery</a></li><li><a href="https://courses.getdbt.com/courses/fundamentals">https://courses.getdbt.com/courses/fundamentals</a></li><li><a href="https://docs.getdbt.com/docs/introduction">https://docs.getdbt.com/docs/introduction</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7815eeb573e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering Project: Youtube API — dlt — BigQuery — Looker and GitHub actions for automation]]></title>
            <link>https://medium.com/@ofelipefernandez/data-engineering-project-youtube-api-dlt-bigquery-looker-and-github-actions-for-automation-09ecedf5d859?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/09ecedf5d859</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 23:22:41 GMT</pubDate>
            <atom:updated>2024-04-24T23:27:15.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Engineering Project: Youtube API — dlt — BigQuery — Looker and GitHub actions for automation</h3><p>In today’s data-driven world, keeping data pipelines efficient and automated is crucial. This blog post dives into my project building a data load tool (dlt) specifically designed for handling YouTube data. We’ll explore how this dlt automates the flow of YouTube data from ingestion to visualization, utilizing tools like BigQuery, Looker, and GitHub Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ePXTylaETsUrkA3BsKY4Kg.png" /></figure><h3>What is dlt and Why You Need It?</h3><ul><li><strong>Automated Data Loading:</strong> dlt automates the process of loading your data from any source to your target destination. This eliminates manual uploads and streamlines your entire data pipeline.</li><li><strong>Reduced Errors, Increased Efficiency:</strong> dlt minimizes errors that can occur with manual data handling. This frees you up to focus on analysis and extracting valuable insights, not data wrangling.</li><li><strong>Scalable for Future Needs:</strong> dlt is built to handle growing data volumes. This ensures your data pipelines remain efficient and reliable as your data needs evolve.</li></ul><h3>Install dlt with BigQuery<a href="https://dlthub.com/docs/dlt-ecosystem/destinations/bigquery#install-dlt-with-bigquery">​</a></h3><p>To install the DLT library with BigQuery dependencies:</p><pre>pip install dlt[bigquery]​</pre><p>1. Initialize a project with a pipeline that loads to BigQuery by running:</p><pre>dlt init chess bigquery</pre><p>2. Install the necessary dependencies for BigQuery by running:</p><pre>pip install -r requirements.txt</pre><p>This will install dlt with the bigquery extra, which contains all the dependencies required by the bigquery client.</p><p>3. Log in to or create a Google Cloud account</p><p>Sign up for or log in to the <a href="https://console.cloud.google.com/">Google Cloud Platform</a> in your web browser.</p><p>4. Create a new Google Cloud project</p><p>After arriving at the <a href="https://console.cloud.google.com/welcome">Google Cloud console welcome page</a>, click the project selector in the top left, then click the New Project button, and finally click the Create button after naming the project whatever you would like.</p><p>5. Create a service account and grant BigQuery permissions</p><p>You will then need to <a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts#creating">create a service account</a>. After clicking the Go to Create service account button on the linked docs page, select the project you created and name the service account whatever you would like.</p><p>Click the Continue button and grant the following roles, so that dlt can create schemas and load data:</p><ul><li><em>BigQuery Data Editor</em></li><li><em>BigQuery Job User</em></li><li><em>BigQuery Read Session User</em></li></ul><p>You don’t need to grant users access to this service account now, so click the Done button.</p><p>6. Download the service account JSON</p><p>In the service accounts table page that you’re redirected to after clicking Done as instructed above, select the three dots under the Actions column for the service account you created and select Manage keys.</p><p>This will take you to a page where you can click the Add key button, then the Create new key button, and finally the Create button, keeping the preselected JSON option.</p><p>A JSON file that includes your service account private key will then be downloaded.</p><p>7. Update your dlt credentials file with your service account info</p><p>Open your dlt credentials file:</p><pre>open .dlt/secrets.toml</pre><p>Replace the project_id, private_key, and client_email with the values from the downloaded JSON file:</p><pre>[destination.bigquery.credentials]<br>project_id = &quot;project_id&quot; # please set me up!<br>private_key = &quot;private_key&quot; # please set me up!<br>client_email = &quot;client_email&quot; # please set me up!</pre><p><strong>dlt Pipeline Structure</strong></p><p>Use the Youtube API to get the comments metadata for a specific video</p><pre>YOUTUBE_API_KEY = os.getenv(&#39;API_KEY&#39;)<br>VIDEO_ID = &quot;yUL-RvDzaAU&quot;<br><br>youtube = build(&quot;youtube&quot;, &quot;v3&quot;, developerKey=YOUTUBE_API_KEY)<br><br>comments_data = []<br>page_token = None<br><br>while True:<br>    request = youtube.commentThreads().list(<br>        part=&quot;snippet&quot;,<br>        videoId=VIDEO_ID,<br>        textFormat=&quot;plainText&quot;,<br>        pageToken=page_token,<br>        maxResults=100  # Maximum allowed by YouTube API<br>    )<br>    response = request.execute()<br><br>    if &quot;items&quot; in response:<br>        for item in response[&quot;items&quot;]:<br>            <br>            published_date=item[&quot;snippet&quot;][&quot;topLevelComment&quot;][&quot;snippet&quot;][&quot;publishedAt&quot;]<br>            comment_text = item[&quot;snippet&quot;][&quot;topLevelComment&quot;][&quot;snippet&quot;][&quot;textDisplay&quot;]<br>            author_name = item[&quot;snippet&quot;][&quot;topLevelComment&quot;][&quot;snippet&quot;][&quot;authorDisplayName&quot;]<br>            like_count=item[&quot;snippet&quot;][&quot;topLevelComment&quot;][&quot;snippet&quot;][&quot;likeCount&quot;]<br>            total_reply_count=item[&quot;snippet&quot;][&quot;totalReplyCount&quot;]<br>            video_id=item[&quot;snippet&quot;][&quot;videoId&quot;]<br>            comments_data.append({&quot;author&quot;: author_name, <br>                            &quot;text&quot;: comment_text,<br>                            &quot;like_count&quot;:like_count,<br>                            &quot;total_reply_count&quot;:total_reply_count,<br>                            &quot;video_id&quot;:video_id,<br>                                &quot;published_date&quot;:published_date<br>                                })<br>               <br>    if &quot;nextPageToken&quot; in response:<br>        page_token = response[&quot;nextPageToken&quot;]<br>    else:<br>        break</pre><p>Now we use dlt to load the data to Bigquery:</p><pre>import dlt<br><br>pipeline = dlt.pipeline(pipeline_name=&quot;youtube_comments_pipeline&quot;,<br>        destination=&#39;bigquery&#39;,<br>        dataset_name=&quot;youtube_comments_data&quot;,)<br><br># run the pipeline with default settings, and capture the outcome<br>info = pipeline.run(comments_data, <br>                    table_name=&quot;youtube_comments_table&quot;, <br>                    write_disposition=&quot;append&quot;)</pre><p>We are using the “Append” write disposition to load only the new comments into my table “youtube_comments_table” and my dataset “youtube_comments_data”.</p><h3><strong>Running the script</strong></h3><p>Running the python script, I have succesfully loaded 292 comments into Bigquery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXma6hQnDzZpbe_c0eHmHg.png" /></figure><h3>Github actions:</h3><p>Create the repository secret variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*5WMZ8u4TR_oqOn74Kloq9Q.png" /></figure><p>Automate to run every 30 minutes using Github Actions:</p><pre>name: Run dlt pipeline script<br><br>on:<br>  schedule:<br>    - cron: &#39;*/30 * * * *&#39;  # Run every 30 minutes<br>  workflow_dispatch: null<br>env:<br>  DATASET_NAME: youtube_comments_data<br>  DESTINATION__BIGQUERY__CREDENTIALS__PROJECT_ID: resounding-hope-414923<br>  DESTINATION__BIGQUERY__CREDENTIALS__LOCATION: US<br>  DESTINATION__BIGQUERY__CREDENTIALS__CLIENT_EMAIL: terraform-service-account@resounding-hope-414923.iam.gserviceaccount.com<br>  DESTINATION__BIGQUERY__CREDENTIALS__PRIVATE_KEY: ${{ secrets.DESTINATION__BIGQUERY__CREDENTIALS__PRIVATE_KEY }}<br>  YOUTUBE_API_KEY: ${{ secrets.API_KEY }}<br>        <br>jobs:<br>  maybe_skip:<br>    runs-on: ubuntu-latest<br>    outputs:<br>      should_skip: ${{ steps.skip_check.outputs.should_skip }}<br>    steps:<br>    - id: skip_check<br>      uses: fkirc/skip-duplicate-actions@v5<br>      with:<br>        concurrent_skipping: always<br>        skip_after_successful_duplicate: &#39;false&#39;<br>        do_not_skip: &#39;[]&#39;<br><br>  run_pipeline:<br>    needs: maybe_skip<br>    if: needs.maybe_skip.outputs.should_skip != &#39;true&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>    - name: Check out<br>      uses: actions/checkout@v4<br>    - name: Setup Python<br>      uses: actions/setup-python@v5<br>      with:<br>        python-version: 3.10.x<br>    - uses: syphar/restore-virtualenv@v1<br>      id: cache-virtualenv<br>      with:<br>        requirement_files: requirements_github_action.txt<br>    - uses: syphar/restore-pip-download-cache@v1<br>      if: steps.cache-virtualenv.outputs.cache-hit != &#39;true&#39;<br>    - run: pip install -r requirements_github_action.txt<br>      if: steps.cache-virtualenv.outputs.cache-hit != &#39;true&#39;<br>    - id: &#39;auth&#39;<br>      uses: &#39;google-github-actions/auth@v2&#39;<br>      with:<br>        credentials_json: &#39;${{ secrets.GCP_CREDENTIALS }}&#39;<br>    - name: &#39;Set up Cloud SDK&#39;<br>      uses: &#39;google-github-actions/setup-gcloud@v2&#39;<br>    - name: &#39;Use gcloud CLI&#39;<br>      run: &#39;gcloud info&#39;<br>    - name: Run pipeline script<br>      run: python &#39;dlt_pipeline.py&#39;</pre><p>This GitHub Actions workflow is designed to run a Python script (dlt_pipeline.py) on a schedule (every 30 minutes) or manually via the workflow_dispatch event. The workflow uses several environment variables, some of which are secrets stored in the GitHub repository. These variables include dataset name, BigQuery credentials, and a YouTube API key. The workflow also includes a job (maybe_skip) that uses the fkirc/skip-duplicate-actions@v5 action to prevent duplicate runs.</p><p>The main job (run_pipeline) of the workflow is dependent on the maybe_skip job and will only run if maybe_skip determines that the run should not be skipped. This job sets up a Python environment, restores a cached virtual environment if available, or installs dependencies from requirements_github_action.txt. It then authenticates with Google Cloud using the google-github-actions/auth@v2 action and the GCP_CREDENTIALS secret. After setting up the Cloud SDK with google-github-actions/setup-gcloud@v2, it runs the gcloud info command for debugging purposes.</p><p>Finally, it runs the dlt_pipeline.py script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6Evw8BqzcQlgScqtDao6aQ.png" /></figure><p>In this project, we’ve built a data pipeline that fetches comments from a specific YouTube video and stores them in a BigQuery table. The pipeline is implemented in Python, using the YouTube Data API v3 to fetch the comments and the dlt library to manage the data pipeline. The pipeline is set up to append the fetched data to the youtube_comments_table in the youtube_comments_data dataset. The outcome of the pipeline run is printed to the console for debugging and verification purposes.</p><p>Additionally, we’ve set up a GitHub Actions workflow to automate the running of this pipeline. The workflow is configured to run every 30 minutes or manually via the workflow_dispatch event. It sets up a Python environment, installs the necessary dependencies, and authenticates with Google Cloud. It then runs the dlt_pipeline.py script, executing the data pipeline and storing the fetched comments in BigQuery. This automation ensures that the data is regularly updated, providing a near real-time dataset of YouTube comments for further analysis.</p><p>Full code can be found at:</p><p><a href="https://github.com/felipefe20/dlt-bigquery">GitHub - felipefe20/dlt-bigquery</a></p><h3>References:</h3><p><a href="https://dlthub.com/docs/dlt-ecosystem/destinations/bigquery">https://dlthub.com/docs/dlt-ecosystem/destinations/bigquery</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09ecedf5d859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka 101]]></title>
            <link>https://medium.com/@ofelipefernandez/apache-kafka-101-2754961ea678?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2754961ea678</guid>
            <category><![CDATA[confluent-kafka]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 15:10:00 GMT</pubDate>
            <atom:updated>2024-04-09T15:10:00.793Z</atom:updated>
            <content:encoded><![CDATA[<p>This is what I learned in the course “Apache Kafka 101” by Confluent</p><h3>What Is Apache Kafka?</h3><p>Apache Kafka is an event streaming platform, but what exactly does that mean? This platform excels at collecting, processing, storing, and integrating data — all on a massive scale. It tackles tasks like distributed logging, stream processing, data integration, and even pub/sub messaging.</p><p>To truly understand Kafka’s power, let’s break down the concept of an “event streaming platform” and how it functions. Before we dive into Kafka’s architecture or its core components, let’s explore what an event is itself. This understanding will be crucial for us to grasp how Kafka stores events, manages data flow, and ultimately analyzes these event streams.</p><h3>What Are Events?</h3><p>Recordings of any action, incident, or change that software or applications track. For example, a website click or a temperature reading from a sensor — those are both events.</p><p>Think of an event as a notification. It signals that something has happened, along with a timestamp for when it occurred. This timestamp is crucial because it allows the system to understand the sequence of events and potentially trigger subsequent actions.</p><h3>Kafka and Events — Key/Value Pairs</h3><p>Kafka stores events in a special kind of log called a “distributed commit log.” Imagine a massive logbook, but instead of being one big notebook, it’s divided into smaller sections we call “partitions.” This division allows Kafka to handle a much larger volume of information.</p><p>Events in Kafka are like entries in this logbook, with two parts: a key and a value. The key acts like a label, helping Kafka quickly find specific events. The value holds the actual information about the event, such as details from a website click or a sensor reading.</p><p>Here’s where things get interesting: internally, Kafka stores these keys and values as byte sequences. Think of it as a coded language for Kafka itself. But don’t be intimidated! When you use Kafka with your programming language, it automatically translates these codes back into a format you understand, like JSON or other structured formats. This translation process is called “serialization” and “deserialization.” It’s like having a built-in decoder ring for Kafka’s code.</p><h3>Kafka Topics</h3><p>Events can multiply rapidly. To manage this constant flow, we need a system for organization. This is where Kafka topics come into play.</p><p>Topics are similar to categories within a filing cabinet. Each topic holds a specific type of event, making it easier to locate and manage them. As a developer working with Kafka, topics are a fundamental concept. You’ll create different topics to categorize different event types. For instance, you might have a separate topic for website clicks and another for sensor readings. Additionally, you can create further topics to store filtered or transformed versions of the same event type, allowing for even greater organization and flexibility.</p><p>Kafka utilizes topics as the core unit for storing events. Topics function similarly to logs, which are well-understood data structures due to their straightforward characteristics:</p><ul><li><strong>Append-Only:</strong> New messages are always added to the end of the topic, ensuring a clear chronological order.</li><li><strong>Sequential Access:</strong> Reading messages requires specifying a starting point within the topic (offset) and then reading entries sequentially.</li><li><strong>Immutability:</strong> Once an event is recorded in the topic, it cannot be altered. This immutability guarantees data integrity and simplifies reasoning about event history.</li></ul><p>Unlike traditional messaging systems with temporary topics and queues, Kafka topics offer inherent data persistence. Messages within a topic are not automatically deleted after a set period. Instead, each topic can be configured with specific retention policies. These policies determine how long data is stored based on factors like age or overall topic size. Retention periods can range from seconds to years, or even indefinitely.</p><p>The foundation of Kafka topics are logs stored on disk. When you write an event to a topic, it achieves a level of durability comparable to trusted database systems. This combination of log simplicity and content immutability forms a cornerstone of Kafka’s success as a critical component in modern data infrastructure. However, these features are merely the starting point for Kafka’s capabilities.</p><h3>Kafka Partitioning</h3><p>Imagine a single server storing an entire Kafka topic. This approach would limit Kafka’s ability to handle large volumes of data or high message throughput. While Kafka excels as a distributed system managing numerous topics across multiple machines, a single, unpartitioned topic could become a bottleneck.</p><p>Fortunately, Kafka offers a solution: topic partitioning. This process divides the single topic log into smaller, independent logs called partitions. Each partition can reside on a separate node within the Kafka cluster. This distribution allows the work of storing, writing, and processing messages to be spread across multiple nodes, significantly improving scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEfDU7DG_ZjEsh-x1pik4A.png" /><figcaption>Source: <a href="https://developer.confluent.io/courses/apache-kafka/events/">https://developer.confluent.io/courses/apache-kafka/events/</a></figcaption></figure><h3>How Partitioning Works</h3><p>After partitioning a topic, a mechanism is needed to determine the destination partition for each message. This process depends on whether the message includes a key:</p><ul><li><strong>Messages without Keys:</strong> When a message lacks a key, Kafka distributes them across partitions in a round-robin fashion. This ensures all partitions receive a roughly equal share of data, but it sacrifices any inherent order in the message sequence.</li><li><strong>Messages with Keys:</strong> If a message includes a key, Kafka employs a hashing function on the key to determine the target partition. This approach guarantees that messages with the same key consistently land in the same partition, thereby preserving order within that key group. For instance, using a customer ID as the message key ensures all events related to a specific customer arrive in the same partition and maintain sequential order.</li></ul><p>While there’s a potential downside — highly active keys could lead to larger and busier partitions — the benefits of maintaining order often outweigh this risk. In most practical scenarios, managing these situations is straightforward. Preserving key order is often a valuable trade-off for message distribution within a Kafka topic.</p><h3>Kafka Brokers</h3><p>From a deployment perspective, Apache Kafka relies on a network of machines called brokers. In modern setups, these brokers might not be individual physical servers. Instead, they could be containerized applications running on virtualized environments, ultimately utilizing the processing power of physical data centers. Regardless of the specific deployment method, each broker operates independently, running the Kafka broker software.</p><p>These brokers play a crucial role. They house specific partitions from various topics and handle incoming requests. These requests involve either writing new events to assigned partitions or reading existing events from them. Additionally, brokers manage the replication of partitions across the cluster, ensuring data redundancy and fault tolerance.</p><h3>Replication</h3><p>Storing each partition on a single broker wouldn’t be ideal. Hardware failures can happen regardless of whether brokers are physical servers or containers. To ensure data safety, Kafka replicates partition data across multiple brokers. These copies are known as follower replicas, while the original partition is called the leader replica.</p><p>When new data is written to the leader (which is also typically the point of contact for reading), the leader automatically replicates these writes to the followers. This replication process occurs seamlessly in the background. While some producer settings allow for adjustments to durability guarantees, developers generally don’t need to be actively involved in this process when building systems on Kafka. The key takeaway for developers is that data is inherently safe — if one node in the cluster fails, another can take over its role, ensuring service continuity.s</p><h3>Kafka Producer</h3><p>Kafka provides a straightforward API for message producers. In Python, the kafka-python library offers a KafkaProducer class that you use to connect to the Kafka cluster. This class requires a configuration dictionary specifying details like broker addresses, security settings, and network behavior parameters for the producer. Additionally, a ProducerRecord class helps construct the key-value pairs you want to send to the cluster.</p><p>If you are connecting to a Kafka cluster in Confluent Cloud, you need to provide credentials for access. The example below shows using a cluster API key and secret.</p><pre>from confluent_kafka import Producer<br>import socket<br><br>conf = {&#39;bootstrap.servers&#39;: &#39;pkc-abcd85.us-west-2.aws.confluent.cloud:9092&#39;,<br>        &#39;security.protocol&#39;: &#39;SASL_SSL&#39;,<br>        &#39;sasl.mechanism&#39;: &#39;PLAIN&#39;,<br>        &#39;sasl.username&#39;: &#39;&lt;CLUSTER_API_KEY&gt;&#39;,<br>        &#39;sasl.password&#39;: &#39;&lt;CLUSTER_API_SECRET&gt;&#39;,<br>        &#39;client.id&#39;: socket.gethostname()}<br><br>producer = Producer(conf)<br><br>producer.produce(topic, key=&quot;key&quot;, value=&quot;value&quot;)<br><br>producer.flush()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*4XaDi1JtATSCFW-DOCI_Ew.png" /><figcaption>Source: <a href="https://developer.confluent.io/courses/apache-kafka/events/">https://developer.confluent.io/courses/apache-kafka/producers/</a></figcaption></figure><h3>Kafka Consumers</h3><p>The counterpart to producers in Kafka are consumers. These consumers are responsible for reading messages from topics within the cluster. Similar to producers, Kafka offers a user-friendly API for message consumption.</p><h4>Basic poll loop</h4><p>A typical Kafka consumer application is centered around a consume loop, which repeatedly calls the poll method to retrieve records one-by-one that have been efficiently pre-fetched by the consumer in behind the scenes. Before entering the consume loop, you’ll typically use the subscribe method to specify which topics should be fetched from:</p><pre>from confluent_kafka import Consumer<br><br>conf = {&#39;bootstrap.servers&#39;: &#39;pkc-abcd85.us-west-2.aws.confluent.cloud:9092&#39;,<br>        &#39;security.protocol&#39;: &#39;SASL_SSL&#39;,<br>        &#39;sasl.mechanism&#39;: &#39;PLAIN&#39;,<br>        &#39;sasl.username&#39;: &#39;&lt;CLUSTER_API_KEY&gt;&#39;,<br>        &#39;sasl.password&#39;: &#39;&lt;CLUSTER_API_SECRET&gt;&#39;,<br>        &#39;group.id&#39;: &#39;foo&#39;,<br>        &#39;auto.offset.reset&#39;: &#39;smallest&#39;}<br><br>consumer = Consumer(conf)<br><br>running = True<br><br>def basic_consume_loop(consumer, topics):<br>    try:<br>        consumer.subscribe(topics)<br><br>        while running:<br>            msg = consumer.poll(timeout=1.0)<br>            if msg is None: continue<br><br>            if msg.error():<br>                if msg.error().code() == KafkaError._PARTITION_EOF:<br>                    # End of partition event<br>                    sys.stderr.write(&#39;%% %s [%d] reached end at offset %d\n&#39; %<br>                                     (msg.topic(), msg.partition(), msg.offset()))<br>                elif msg.error():<br>                    raise KafkaException(msg.error())<br>            else:<br>                msg_process(msg)<br>    finally:<br>        # Close down consumer to commit final offsets.<br>        consumer.close()<br><br>def shutdown():<br>    running = False</pre><p>In Kafka, scaling consumers is more or less automatic. A single instance of a consuming application will always receive the messages from all the partitions in the topic it’s subscribed to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQr-Nkv47hsm-5o-xRJutw.png" /><figcaption>Source: <a href="https://developer.confluent.io/courses/apache-kafka/events/">https://developer.confluent.io/courses/apache-kafka/consumers/</a></figcaption></figure><p>Sources: <br><a href="https://docs.confluent.io/kafka-clients/python/current/overview.html">https://docs.confluent.io/kafka-clients/python/current/overview.html</a><br><a href="https://developer.confluent.io/courses/apache-kafka/events/">https://developer.confluent.io/courses/apache-kafka/events/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2754961ea678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a YouTube data analysis Telegram Bot powered by Kafka and ksqlDB]]></title>
            <link>https://medium.com/@ofelipefernandez/building-a-youtube-data-analysis-telegram-bot-powered-by-kafka-and-ksqldb-9b6ee430f2c8?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b6ee430f2c8</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[ksqldb]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Fri, 08 Mar 2024 17:01:12 GMT</pubDate>
            <atom:updated>2024-03-08T17:01:12.363Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wanted to analyze YouTube data in real-time and receive notifications directly on your phone? This article dives into building a Telegram bot that achieves just that. We’ll explore how Apache Kafka and ksqlDB using Confluent Cloud, which are powerful streaming data tools, can be leveraged to create this functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*oG0rYD1QJS2qWhRk.png" /><figcaption>Source: Confluent Cloud</figcaption></figure><p><strong>What is Kafka?</strong></p><p>Apache Kafka is an open-source platform designed for handling real-time data streams. Kafka acts like a sophisticated pipeline system. It can ingest data from various sources, store it reliably, and then distribute it to different applications for further processing or analysis. This makes Kafka valuable for applications that require immediate reaction to data updates, like fraud detection or stock price analysis.</p><p><strong>What is ksqlDB?</strong></p><p>KsqlDB is a stream processing engine that allows you to analyze real-time data flowing through the streaming platform. We’ll use ksqlDB to analyze the incoming data stream for the playlist.</p><h3>Implementation:</h3><p>I want to know how popular a Youtube playlist is, in this case, I chose one from one of the most-known Spanish speaker Youtubers:</p><p><a href="https://youtube.com/playlist?list=PLU8fI-5lkaHoqz7TpSU-fuCK_l8Y7h0W2&amp;si=5u8w-efFoMloksRg">https://youtube.com/playlist?list=PLU8fI-5lkaHoqz7TpSU-fuCK_l8Y7h0W2&amp;si=5u8w-efFoMloksRg</a></p><p><strong>1. Data Acquisition:</strong></p><ul><li><strong>Get YouTube Data API Key:</strong> Head over to the Google Cloud Platform Console: <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a> and create a project. Enable the YouTube Data API v3 and follow the instructions to generate an API key. This key will be used to access YouTube data programmatically.</li><li><strong>Identify Relevant Metrics:</strong> Define the key metrics that matter to you. In my case I kept it simple, I defined views, likes and comments</li></ul><pre><br>def main2():<br>    logging.info(&quot;START&quot;)<br><br>    kafka_config = config[&quot;kafka&quot;] | {<br>        &#39;client.id&#39;: socket.gethostname()<br>    }<br>    producer = Producer(kafka_config)<br><br>    google_api_key = config[&quot;google_api_key&quot;]<br>    youtube_playlist_id = config[&quot;youtube_playlist_id&quot;]<br>    while True:<br>        for video_item in fetch_playlist_items(google_api_key, youtube_playlist_id):<br>            video_id = video_item[&quot;contentDetails&quot;][&quot;videoId&quot;]<br>            for video in fetch_videos(google_api_key, video_id):<br>                logging.info(&quot;GOT %s&quot;, pformat(summarize_video(video)))<br><br>                producer.produce(<br>                    topic=&quot;youtube_videos_felipe&quot;,<br>                    key=video_id,<br>                    value=json.dumps({<br>                        &quot;TITLE&quot;: video[&quot;snippet&quot;][&quot;title&quot;],<br>                        &quot;VIEWS&quot;: int(video[&quot;statistics&quot;].get(&quot;viewCount&quot;, 0)),<br>                        &quot;LIKES&quot;: int(video[&quot;statistics&quot;].get(&quot;likeCount&quot;, 0)),<br>                        &quot;COMMENTS&quot;: int(video[&quot;statistics&quot;].get(&quot;commentCount&quot;, 0)),<br>                    }).encode(&quot;utf-8&quot;),<br>                    on_delivery=on_delivery,<br>                )<br><br>        producer.flush()<br>        time.sleep(10)<br><br>if __name__ == &quot;__main__&quot;:<br>    logging.basicConfig(level=logging.INFO)<br>    sys.exit(main2())</pre><p>The main2 function in the youtube_watcher.py script is designed to continuously fetch data from a YouTube playlist and produce it to a Kafka topic. It first sets up a Kafka producer with the configuration specified in the config[&quot;kafka&quot;] dictionary. Then, it enters an infinite loop where it fetches items from a YouTube playlist specified by youtube_playlist_id. For each video in the playlist, it fetches detailed video data, logs a summary of the video, and produces a message to the Kafka topic youtube_videos_felipe.</p><p>The message key is the video ID, and the value is a JSON-encoded string containing the video title, view count, like count, and comment count. After producing messages for all videos, it flushes the producer to ensure all messages are sent, then waits for 10 seconds before starting the next iteration of the loop.</p><p>2. <strong>Kafka and ksqlDB setup</strong></p><ul><li><strong>Create a cluster in Confluent Cloud: </strong>I named mine youtube_bot</li><li><strong>Create ksqlDB cluster in Confluent Cloud: </strong>I named it<strong> </strong>ksql_youtube_cluster</li></ul><p>Once you have provisioned the Clusters, we can start creating the streams and tables required to handle the data.</p><p><strong>3. Create streams and tables to handle the data</strong></p><p><strong>3.1 Connect and receive data from YouTube into Kafka topic</strong></p><p>Create a stream to accept the following data from the Python API requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6ciLJ6OY2Mdc_e5XNUvUA.png" /></figure><p>Checking that the stream was correctly created and keep waiting for changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4N3KzIPs0u764J47PXYcA.png" /></figure><p>Run Python script again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*GG_gApdzKx2HOStqS_kNnQ.png" /></figure><p>My stream is receiving data without any problem.</p><p>We have a Python script that gathers the data we are interested in and streams it to Kafka</p><p>We have a snapshot of the data at this point in time, we could start a schedule to run this script every certain time and start getting data, but we want to look for changes over time, and some transformations are required.</p><p><strong>3.2 Data transformations using ksqlDB</strong></p><p>Processing within ksql and looking for changes in the data. We do that by creating a table with offset columns, based on current and previous views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRAqmDi3r2C-fK2wwQxJmg.png" /></figure><p>Now querying and selecting all records from the YOUTUBE_CHANGES stream where the current number of likes is not equal to the previous number of likes.</p><p>The EMIT_CHANGES part of the query will continue to output new results as they come in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEI9pKciqX5f3G1deqUXZw.png" /></figure><p>As we can see there is a small variation in the view count in many videos, this was the screenshot of just one of them, the view count for one of the videos has increased from 2905687 to 2905688.</p><p>We have completed this flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*WCkDnwGOXXUIZfZns78TYw.png" /></figure><p>So far we have completed these steps:</p><ul><li>Track for changes in data (Youtube videos)</li><li>Storing the data within ksql tables</li><li>Detect changes over time</li></ul><p><strong>4. Telegram Bot:</strong></p><p>We are onto the last part of the project: Alert or messaging, for this case I’m using a telegram bot, by going to @botfather and follow the instructions to create a new bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*ueY1iVZYEx_yixCj38SHVw.png" /></figure><p>I need the chat ID, this is how I’ll get it.</p><pre>import requests<br><br>bot_token = &quot;&lt;YOUR_BOT_TOKEN&gt;&quot;<br>response = requests.get(f&quot;https://api.telegram.org/bot{bot_token}/getUpdates&quot;)<br>updates = response.json()<br><br># Get the chat_id from the first update<br>chat_id = updates[&#39;result&#39;][0][&#39;message&#39;][&#39;chat&#39;][&#39;id&#39;]<br><br>print(chat_id)</pre><p>Once I have the chat_id I can go back to ksql and keep creating some streams.</p><p>Create a stream to have one event for every message we’d like to send, this message must have the same shape as the telegram API expects, we create the stream by doing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*HZRKJB3_jJghEdw8GuZ_Qg.png" /></figure><p><strong>Create a connector:</strong></p><ul><li>Go to Connectors&gt;HTTP Sink connector &gt; telegram_outbox_felipe</li><li>Generate API credentials.</li></ul><p>Some considerations:</p><ul><li>In “Http URL” put:</li></ul><pre>https://api.telegram.org/bot&lt;YOUR_BOT_TOKEN&gt;/sendMessage</pre><ul><li>HTTP Request Method: “POST”</li><li>HTTP Headers: “Content-Type: application/json”</li><li>Request Body Format: “json”</li><li>Batch json as array: “False”</li></ul><p><strong>Test the connector:</strong></p><p>Let’s test the connection by inserting some values into the stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*LrIbDN9ZXtupJWoaRReapw.png" /></figure><p>And it’s working!! I have my first message sent from ksql to my telegram bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*0XaFIcdDSkmwX2fWy-YRSA.png" /></figure><p>Now we need to finish the pipeline and fill the gap between the table YOUTUBE_CHANGES and this stream telegram_outbox_felipe</p><p>We can subscribe to the table changes and send the messages to telegram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Qa19aZsvAgVt4V8w1urKfQ.png" /></figure><p>We now have completed this flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*ZYhHlpV9W4m-dXZiqhQlkw.png" /></figure><p><strong>Creating persistent queries to stream data:</strong></p><p>Writing a ksql statement to insert values from one stream youtube_changes_stream_felipeinto telegram_outbox_felipe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*XoM2MoJ6zxkT2Y5bGKV5-A.png" /></figure><p>Run the Python script to get the data from YouTube again.</p><p>And It’s working, all these videos have changes in their likes count and I’m receiving alarms in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*hzLZrcmiURGvj8rd-bpHrw.png" /></figure><p>To keep it live streaming, we only need to keep our python script running, in this case with view_counts to make sure its numbers are increasing constantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*fA_4cr8sPNZ9911CcBe20Q.png" /></figure><p>You can see how my persistent queries are running and my telegram bot keeps receiving alerts in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9Q3T8Fh2x6buJfPG_YdyQ.png" /></figure><p>I let the script run for a while, then examined the connector to determine the total number of messages processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*KmAllniF8JuILruQtqT6EA.png" /></figure><p><strong>Conclusion:</strong></p><p>We have completed the project and built a real-time pipeline to understand a YouTube playlist’s popularity. This system continuously gathers data and sends Telegram alerts, keeping you informed of its performance. This is a foundational project you can build upon.</p><p>All the code is available on my GitHub:</p><p><a href="https://github.com/felipefe20/kafka-ksql-telegram-project">GitHub - felipefe20/kafka-ksql-telegram-project</a></p><p><strong>Resources:</strong></p><p><a href="https://www.youtube.com/watch?v=jItIQ-UvFI4&amp;t=1430s&amp;ab_channel=Confluent">https://www.youtube.com/watch?v=jItIQ-UvFI4&amp;t=1430s&amp;ab_channel=Confluent</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b6ee430f2c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Basics of Apache Spark in Databricks]]></title>
            <link>https://medium.com/@ofelipefernandez/understanding-the-basics-of-apache-spark-in-databricks-ad3f09d9162c?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad3f09d9162c</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[coursera]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 14:54:00 GMT</pubDate>
            <atom:updated>2024-03-05T14:54:00.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark is a powerful open-source data processing engine that enables efficient and scalable data analytics. In this article, we will explore the underlying architecture Databricks and how it leverages Apache Spark to provide a great data engineering experience.</p><p><strong>Databricks and Apache Spark Clusters:</strong></p><p>Databricks is a cloud-based service that manages Apache Spark clusters. These clusters are groups of computers treated as a single unit, capable of executing commands issued from notebooks. By utilizing a master-worker architecture, Spark clusters parallelize data processing across multiple computers, resulting in improved scale and performance.</p><p><strong>Spark Driver and Worker Nodes: </strong>In Databricks, the notebook interface acts as the Spark driver program or master. It contains the main loop for the program and creates distributed datasets on the cluster. On the other hand, Spark clusters consist of worker nodes that execute operations in the form of transformations and actions. The driver node assigns tasks to worker nodes, instructing them to pull data from specified sources.</p><p><strong>Spark Session:</strong> Regardless of the deployment location, driver programs access Apache Spark through a spark session object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Itb5crjXD37QZHQ5LqNtOA.png" /><figcaption>Source: Coursera Microsoft Azure Databricks</figcaption></figure><p>In a Spark cluster, the main components are the driver and the executors. Here’s how they work together:</p><ol><li>Driver: The driver is like the brain of the cluster. It runs the main Spark application and coordinates the execution of tasks. The driver splits the work into smaller tasks and assigns them to the executors. It also manages the overall execution flow and collects the results from the executors.</li><li><strong>Executors: T</strong>he machines that perform the tasks assigned by the driver. Each executor runs on a separate node in the cluster, they receive tasks from the driver and execute them in parallel. They process the data, perform computations, and return the results to the driver.</li></ol><p>Here’s how the driver and executors work together:</p><ul><li>The driver splits the work into jobs and further divides them into tasks.</li><li>Each task is assigned to an executor for parallel execution.</li><li>Executors process the tasks independently and in parallel on different nodes.</li><li>Executors fetch the required data partitions from the original data source.</li><li>Once the tasks are completed, the results are sent back to the driver.</li><li>The driver collects the results from all the executors and combines them as needed.</li></ul><p>This collaboration between the driver and executors allows Spark to distribute and process large amounts of data efficiently across a cluster, enabling faster and more scalable data processing.</p><p><strong>What are the benefits of parallelism?</strong></p><p>Parallelism in Databricks offers several benefits and helps in scaling tasks or jobs effectively. Here are the benefits of parallelism and how it helps in scaling tasks or jobs:</p><ol><li><strong>Increased Performance: </strong>Parallelism allows tasks or jobs to be executed simultaneously on multiple nodes or executors. This leads to faster processing and improved performance as the workload is distributed across the cluster.</li><li><strong>Scalability: </strong>With parallelism, you can easily scale tasks or jobs horizontally by adding more nodes or executors to the cluster. This means you can handle larger workloads and process more data without worrying about limitations on memory and processing power.</li><li><strong>Efficient Resource Utilization: </strong>Parallelism enables efficient utilization of resources in the cluster. By dividing the work into smaller tasks and assigning them to different executors, you can make optimal use of available CPU cores, memory, and network bandwidth.</li><li><strong>Fault Tolerance:</strong> Parallelism provides fault tolerance by distributing the workload across multiple nodes. If any node or executor fails, the tasks assigned to that node can be automatically re-assigned to other available nodes, ensuring uninterrupted processing and minimizing the impact of failures.</li><li><strong>Flexibility: </strong>Parallelism allows you to divide your work into multiple jobs and stages, providing flexibility in managing complex data processing workflows. You can break down a large job into smaller stages and execute them in parallel, optimizing the overall execution time.</li></ol><p>In Databricks, parallelism is achieved through the use of executors and slots. Executors are Java Virtual Machines (JVMs) running on individual nodes, and each executor has multiple slots for parallel task execution. The driver assigns tasks to these slots, enabling parallel processing of data across the cluster.</p><h3>Benefits of Using Databricks for Apache Spark</h3><p>While Apache Spark itself is a powerful tool, using it through Databricks offers several advantages compared to a self-managed setup. These advantages can significantly improve the efficiency, manageability, and security of your data processing pipelines.</p><ul><li><strong>Reduced Complexity and Faster Time to Value:</strong> Databricks takes care of the heavy lifting associated with managing Spark clusters. This includes provisioning and configuring compute resources, deploying Spark versions, and handling ongoing maintenance. This frees up your team’s valuable time and resources, allowing them to focus on core data engineering and analytics tasks, leading to a faster time to value for your projects.</li><li><strong>Enhanced Performance and Scalability:</strong> Databricks offers optimized Spark runtimes tuned for specific cloud environments. This, combined with seamless integration with high-performance storage solutions like Delta Lake, allows you to achieve significant performance gains compared to a self-managed setup. Additionally, Databricks allows elastic scaling of clusters. This means you can easily adjust the size of your cluster based on your workload requirements, ensuring optimal resource utilization and cost efficiency.</li><li><strong>Robust Security and Governance:</strong> Databricks provides enterprise-grade security features and access controls that are essential for protecting sensitive data. Features like role-based access control, data encryption, and audit logging ensure that your data is secure and only authorized users can access it. Additionally, Databricks adheres to strict industry compliance standards, providing peace of mind for organizations with stringent data privacy regulations.</li><li><strong>Simplified Collaboration and Reproducibility:</strong> Databricks notebooks offer a centralized and collaborative environment for developing, sharing, and executing Spark jobs. This allows teams to work together effectively on data pipelines, share best practices, and ensure code reproducibility. This collaborative approach streamlines the development process and simplifies knowledge transfer within your organization.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad3f09d9162c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project: Processing Streaming Data with Google Cloud Pub/sub and Dataflow]]></title>
            <link>https://medium.com/@ofelipefernandez/project-processing-streaming-data-with-pub-sub-and-dataflow-631e6082c94d?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/631e6082c94d</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 01:26:47 GMT</pubDate>
            <atom:updated>2024-02-26T03:22:48.243Z</atom:updated>
            <content:encoded><![CDATA[<p>This project provides a hands-on exploration of using Pub/Sub and Dataflow for streaming data processing, based on Chapter 6 of the “Data Engineering with Google Cloud Platform” book, Through a series of steps:</p><ul><li><strong>Part 1, Setting up Pub/Sub:</strong> How to establish topics and subscriptions for data ingestion and distribution.</li><li><strong>Part 2, Building a Dataflow pipeline:</strong> How to design and implement a pipeline to transform and process streaming data in real-time.</li></ul><p>Make sure you have the following GCP services ready: <strong>Dataflow, Pub/Sub, Google Cloud Storage (GCS), and BigQuery</strong>.</p><h3><strong>What is streaming Data?</strong></h3><p>Streaming data refers to information generated and received continuously over time, in contrast to static datasets that remain unchanged.</p><ul><li><strong>Sensor readings</strong> from devices like weather stations or industrial equipment.</li><li><strong>Social media updates</strong> in real-time.</li><li><strong>Financial transactions</strong> occur every second.</li><li><strong>Website user activity</strong> as it happens.</li></ul><p>Unlike static datasets analyzed after the fact, streaming data demands immediate processing and analysis to extract valuable insights and make decisions in real-time. This opens up possibilities for:</p><ul><li><strong>Fraud detection:</strong> Identify suspicious activity as soon as it happens.</li><li><strong>Personalized recommendations:</strong> Tailor experiences based on ongoing user behavior.</li><li><strong>Machine learning models:</strong> Train models on continuous data streams for improved accuracy.</li><li><strong>Real-time insights:</strong> Respond to changes and make decisions instantly.</li></ul><p>The following diagram shows the most common pattern for processing streaming data from data sources to BigQuery tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*JpKINXzLFSrhixVFXnW56g.png" /></figure><p><strong>Getting started:</strong></p><ul><li>Clone the repository within your cloud shell environment.</li></ul><p><a href="https://github.com/felipefe20/GCP-Streaming-project">https://github.com/felipefe20/GCP-Streaming-project</a></p><h3><strong>Part 1: Setting up Pub/Sub</strong></h3><p>Pub/Sub is a messaging system. Messaging systems receive messages from multiple systems and distribute them:</p><p>Here are the overall steps in this Pub/Sub section:</p><ol><li><strong>Creating a Pub/Sub topic</strong></li></ol><p>I will create the Pub/Sub topic using shell commands, as follows:</p><pre>gcloud pubsub topics create bike-sharing-trips-topic-felipe</pre><p><strong>2. Creating and running a Pub/Sub publisher using Python</strong></p><ul><li>I want to return a JSON object with bike-sharing trip data, in this case data of</li></ul><p>This Python function, create_random_message(), generates a dictionary that represents a random message. The message contains information about a hypothetical bike trip. Here’s what each key in the dictionary represents:</p><p>-trip_id: A random integer between 10000 and 99999, representing the unique identifier for the trip.<br>- start_date : The current date and time in UTC, represented as a string.<br>- start_station_id: A random integer between 200 and 205, representing the identifier for the start station of the trip.<br>- bike_number: A random integer between 100 and 999, representing the unique identifier for the bike used in the trip.<br>- duration_sec: A random integer between 1000 and 9999, representing the duration of the trip in seconds.</p><pre>PROJECT_ID = &quot;resounding-hope-414923&quot;<br>TOPIC_ID = &quot;bike-sharing-trips-topic-felipe&quot;<br><br>publisher = pubsub_v1.PublisherClient()<br>topic_path = publisher.topic_path(PROJECT_ID, TOPIC_ID)<br><br>def create_random_message():<br>    trip_id = randint(10000,99999)<br>    start_date = str(datetime.utcnow())<br>    start_station_id = randint(200,205)<br>    bike_number = randint(100,999)<br>    duration_sec = randint(1000,9999)<br><br>    message_json = {&#39;trip_id&#39;: trip_id,<br>            &#39;start_date&#39;: start_date,<br>            &#39;start_station_id&#39;: start_station_id,<br>            &#39;bike_number&#39;:bike_number,<br>            &#39;duration_sec&#39;:duration_sec<br>            }<br>    return message_json</pre><p>Creating a For loop to create 10 different random messages, then run the Python script and see how 10 messages are generated.</p><pre>python3 pubsub_publisher.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*tTuoh6CgTfR3iQIw4cB4Lg.png" /></figure><p><strong>3. Creating a Pub/Sub subscription</strong></p><p>Subscriptions are entities that have an interest in receiving messages from the topic.</p><p>Creating a subscription named bike-sharing-trips-subs-felipe using cloud shell.</p><pre>gcloud pubsub subscriptions create --topic bike-sharing-trips-topic-felipe bike-sharing-trips-subs-felipe</pre><p>Going to the user interface and clicking on Pull, the subscription will receive all 10 messages, as can be seen here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFCAP2TpDxrMcTVmZV3Zxw.png" /></figure><p>The transition from publisher to subscriber is fast, taking only milliseconds, and Pub/Sub can manage numerous publishers and subscribers without compromising scalability. This makes Pub/Sub a crucial component in establishing a streaming process. In the next section, we’ll employ Dataflow as the subscriber. Dataflow will subscribe to our topic, modify the data, and then deposit it into BigQuery.</p><h3><strong>Part 2, Building a Dataflow Pipeline:</strong></h3><p>We need three environments to make sure our streaming pipeline is working:</p><p>1- Apache Beam streaming pipeline:</p><p><strong>What is Apache Beam?</strong></p><p>Apache Beam is a unified programming model for building both batch and streaming data processing pipelines. It allows you to write code once and run it on various distributed processing backends, like Apache Flink, Apache Spark, and Google Cloud Dataflow, offering flexibility and avoiding vendor lock-in. Beam simplifies complex data processing tasks by providing a high-level abstraction, enabling developers to focus on the logic of their transformations without worrying about the underlying infrastructure.</p><ul><li>Create a virtual environment to run Apache Beam within:</li></ul><pre>mkdir venv<br>cd venv<br>python3 -m venv beam-env<br>source beam-env/bin/activate<br><br>pip install --upgrade pip<br>pip install wheel<br>pip install apache-beam[gcp]<br>cd ..</pre><p>For the Apache Beam subscription service in the Python script beam_stream_bikesharing.py</p><pre>def run():<br>    with beam.Pipeline(options=beam_options) as p:(<br>        p | &quot;Read from Pub/Sub&quot; &gt;&gt; beam.io.ReadFromPubSub(subscription=INPUT_SUBSCRIPTION)<br>        | &#39;Decode&#39; &gt;&gt; beam.Map(lambda x: x.decode(&#39;utf-8&#39;))<br>        | &quot;Parse JSON&quot; &gt;&gt; beam.Map(json.loads)<br>        | &#39;Write to Table&#39; &gt;&gt; beam.io.WriteToBigQuery(OUTPUT_TABLE,<br>                        schema=&#39;trip_id:STRING,start_date:TIMESTAMP,start_station_id:STRING,bike_number:STRING,duration_sec:INTEGER&#39;,<br>                        write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)<br>    )</pre><pre>python3 beam_stream_bikesharing.py \<br>        --project=resounding-hope-414923 \<br>        --region=us-central1 \<br>        --runner=DataflowRunner \<br>        --temp_location=gs://streaming_bikeshare_bcuket_felipe/temp</pre><p>This will automatically create a BigQuery Table and a Dataflow job waiting for streaming data.</p><p>2- BigQuery Table</p><p>3- Publisher sending streaming data. Similar to part 1 python3 pubsub_publisher.py</p><p><strong>Execution:</strong></p><ul><li>Run the publisher script: python3 pubsub_publisher.py</li><li>Dataflow reads Data from Pub/sub</li><li>Decodes data into utf-8</li><li>Parse data in json format</li><li>Write to BigQuery table</li></ul><p>All previous steps can be better appreciated in the Graph view of the Dataflow job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*7O_Pxjqpg7jgH47xRSzMQQ.png" /></figure><p>After running the publisher script, I‘m getting the following metrics for input and output data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*VLFn_656cL5Juw9HE68R1A.png" /></figure><p>100 elements were added to BigQuery.</p><p>Following all previous steps, I’ve successfully created a streaming data pipeline on Dataflow.</p><h3>Conclusion: A Foundation for Real-Time Data Processing</h3><p>This project has provided a hands-on introduction to utilizing Pub/Sub and Dataflow for real-time data processing. Through practical exercises, we know how to:</p><ul><li>Establish Pub/Sub topics and subscriptions for data ingestion and distribution.</li><li>Construct Dataflow pipelines to process streaming data in real-time.</li><li>Apply necessary transformations to extract valuable insights from your data streams.</li></ul><p><strong>Resources:</strong></p><ul><li><a href="https://www.cloudskillsboost.google/paths/16/course_templates/52">https://www.cloudskillsboost.google/paths/16/course_templates/52</a></li><li><a href="https://www.packtpub.com/product/data-engineering-with-google-cloud-platform/9781800561328?utm_source=github&amp;utm_medium=repository&amp;utm_campaign=9781800561328">https://www.packtpub.com/product/data-engineering-with-google-cloud-platform/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631e6082c94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ETL Project: Python, Mage and Google Cloud to handle football data]]></title>
            <link>https://medium.com/@ofelipefernandez/mage-etl-to-google-cloud-and-bigquery-72d79e9b5f33?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d79e9b5f33</guid>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[mage]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 03:48:59 GMT</pubDate>
            <atom:updated>2024-03-10T15:44:47.619Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is orchestration?</strong></p><ul><li>Orchestration is the process of dependency management facilitated through Automation. It is used in data engineering to manage the scheduling, triggering, monitoring and even resource allocation for data engineering workflows.</li><li>A good orchestrator should handle workflow management, automation, error handling and recovery, monitoring and alerting, resource optimization, observability, debugging, and compliance or auditing.</li><li>A good orchestrator prioritizes developer experience, which includes flow state, feedback loops, and cognitive load.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*AQxhrR0Qf-8XYohf5xmdng.png" /></figure><h3>Start project:</h3><p>The docker-compose.yml file is a YAML file defining services, networks, and volumes for a Docker application.</p><pre>version: &#39;3&#39;<br>services:<br>  magic:<br>    image: mageai/mageai:latest<br>    command: mage start ${PROJECT_NAME}<br>    env_file:<br>      - .env<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    environment:<br>      USER_CODE_PATH: /home/src/${PROJECT_NAME}<br>      POSTGRES_DBNAME: ${POSTGRES_DBNAME}<br>      POSTGRES_SCHEMA: ${POSTGRES_SCHEMA}<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>      POSTGRES_HOST: ${POSTGRES_HOST}<br>      POSTGRES_PORT: ${POSTGRES_PORT}<br>    ports:<br>      - 6789:6789<br>    volumes:<br>      - .:/home/src/<br>      - ~/Documents/secrets/personal-gcp.json:/home/src/personal-gcp.json<br>    restart: on-failure:5<br>  postgres:<br>    image: postgres:14<br>    restart: on-failure<br>    container_name: ${PROJECT_NAME}-postgres<br>    env_file:<br>      - .env<br>    environment:<br>      POSTGRES_DB: ${POSTGRES_DBNAME}<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>    ports:<br>      - &quot;${POSTGRES_PORT}:5432&quot;</pre><p>the .env file is used to set environment variables for the magic and postgres services. These variables include database credentials and configuration (like POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DBNAME, etc.), the project name (PROJECT_NAME), and others.</p><pre>PROJECT_NAME=magic-zoomcamp<br>POSTGRES_DBNAME=postgres<br>POSTGRES_SCHEMA=magic<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=postgres<br>POSTGRES_HOST=postgres<br>POSTGRES_PORT=5432</pre><p>Start the services:</p><p>docker-compose up</p><p>go to URL: <a href="http://localhost:6789/">http://localhost:6789</a></p><h3><strong>Creating a simple pipeline using Mage user interface:</strong></h3><p>Mage makes building data pipelines really efficient. It does this by letting you break down your tasks into smaller, reusable pieces called <strong>Blocks</strong>.</p><ul><li><strong>Data Loaders:</strong> These grab data from wherever it lives, like a website or a file.</li><li><strong>Transformers:</strong> These clean, organize, and tweak the data to make it perfect for its final destination.</li><li><strong>Data Exporters:</strong> These take the finished data and put it where you need it, like a database or another program.</li></ul><h3><strong>Part 1: Loading data to PostgreSQL</strong></h3><p>Before coding our pipeline, we must tell Mage how to connect to our PostgreSQL database. This involves adding information to a file called io_config.yml</p><ol><li>Open the io_config.yml file in the Mage GUI&#39;s web interface.</li><li>Scroll to the bottom of the file.</li><li>Add a new line with the following content:</li></ol><pre>dev:<br>  POSTGRES_CONNECT_TIMEOUT: 10<br>  POSTGRES_DBNAME: &quot;{{ env_var(&#39;POSTGRES_DBNAME&#39;) }}&quot;<br>  POSTGRES_SCHEMA: &quot;{{ env_var(&#39;POSTGRES_SCHEMA&#39;) }}&quot;<br>  POSTGRES_USER: &quot;{{ env_var(&#39;POSTGRES_USER&#39;) }}&quot;<br>  POSTGRES_PASSWORD: &quot;{{ env_var(&#39;POSTGRES_PASSWORD&#39;) }}&quot;<br>  POSTGRES_HOST: &quot;{{ env_var(&#39;POSTGRES_HOST&#39;) }}&quot;<br>  POSTGRES_PORT: &quot;{{ env_var(&#39;POSTGRES_PORT&#39;) }}&quot;</pre><p>env_var()<strong>:</strong> When writing your data exporter code, you use env_var() to access the specific piece of information you need from the .env file</p><h3><strong>Create a simple batch pipeline:</strong></h3><p>Edit requirements.txt within folder magic_zoomcamp\requirements.txt to add all the libraries you need, in my case I need soccer_data, statsbombpy</p><p><strong>Data Loader:</strong></p><p>Write your code for fetching data from a remote source or loading it from a disk.</p><ul><li>Add data loader block called: load_soccer_data</li></ul><pre>import io<br>import pandas as pd<br>import requests<br>from pandas import DataFrame<br>import soccerdata as sd<br>from statsbombpy import sb<br><br><br>if &#39;data_loader&#39; not in globals():<br>    from mage_ai.data_preparation.decorators import data_loader<br>if &#39;test&#39; not in globals():<br>    from mage_ai.data_preparation.decorators import test<br><br><br>@data_loader<br>def load_data_from_api(**kwargs) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Template for loading data from API<br>    &quot;&quot;&quot;<br>    events = sb.events(match_id=3923881) #Final match of the 2024 AFCON<br>    return  events<br><br><br>@test<br>def test_output(df) -&gt; None:<br>    &quot;&quot;&quot;<br>    Template code for testing the output of the block.<br>    &quot;&quot;&quot;<br>    assert df is not None, &#39;The output is undefined&#39;</pre><p>This code will return a DataFrame of shape 2699 rows x 89 columns containing all information related to the recent final match of the 2024 AFCON between Côte d’Ivoire and Nigeria, identified by match_id=3923881.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*b5iPviWWKTZTTJ-UkwhUMQ.png" /></figure><p><strong>Transformer:</strong></p><p>Use these blocks to clean, transform, and enhance data from other blocks.</p><ul><li>Add a transformer block called: transformations</li></ul><pre>@transformer<br>def transform_df(df: DataFrame, *args, **kwargs) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    This function filters the DataFrame for shots and selects relevant columns.<br>    &quot;&quot;&quot;<br>    # Define the columns to keep<br>    columns_to_keep = [<br>        &#39;player&#39;, &#39;team&#39;, &#39;location&#39;, &#39;shot_aerial_won&#39;,<br>        &#39;shot_body_part&#39;, &#39;shot_end_location&#39;, &#39;shot_first_time&#39;,<br>        &#39;shot_freeze_frame&#39;, &#39;shot_key_pass_id&#39;, &#39;shot_one_on_one&#39;,<br>        &#39;shot_outcome&#39;, &#39;shot_statsbomb_xg&#39;, &#39;shot_technique&#39;, &#39;shot_type&#39;<br>    ]<br>    <br>    # Filter rows where type is &#39;Shot&#39;<br>    shots_df = df[df[&#39;type&#39;] == &#39;Shot&#39;]<br>    <br>    # Select the relevant columns<br>    transformed_df = shots_df[columns_to_keep]<br><br>    return transformed_df</pre><p>With the block defined, we apply a series of filters to the data we’ve loaded.</p><p>The key transformation in this function is the creation of shots_df, which filters out any row in the dataset where the event type is not ‘Shot’. This is done with df[df[&#39;type&#39;]==&#39;Shot&#39;</p><p>Next, we select specific columns related to the shot event. This selection is done with shots_df[columns_to_keep]</p><p>The resulting DataFrame, transformed_df, which has 23 rows and 14 columnsonly includes shot events and the selected columns. This DataFrame is then returned to be passed to the next block in the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZOfgyIrElhW8yaewhxGmw.png" /></figure><p>Finally a <strong>Data Exporter block:</strong></p><p>These types of blocks are used to store that data or to train models and store those models elsewhere.</p><p>Inside the function, set up some configuration variables: schema_name, table_name, config_path, config_progile. These are used to specify the schema and table where the data will be exported, and to load the database configuration from a YAML file.</p><pre>@data_exporter<br>def export_data_to_postgres(df: DataFrame, **kwargs) -&gt; None:<br><br>    schema_name = &#39;statsbomb_data&#39;  # Specify the name of the schema to export data to<br>    table_name = &#39;events_data&#39;  # Specify the name of the table to export data to<br>    config_path = os.path.join(get_repo_path(), &#39;io_config.yaml&#39;)<br>    config_profile = &#39;dev&#39;<br><br>    with Postgres.with_config(ConfigFileLoader(config_path, config_profile)) as loader:<br>        loader.export(<br>            df,<br>            schema_name,<br>            table_name,<br>            index=False,  # Specifies whether to include index in exported table<br>            if_exists=&#39;replace&#39;,  # Specify resolution policy if table name already exists<br>        )</pre><p>Trigger the complete pipeline by clicking on “Execute with all upstream blocks” option in the Data Exporter block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*eEW8F-wd3nfLtm6p27LCmQ.png" /></figure><p><strong>Testing that all data was successfully loaded to PostgreSQL:</strong></p><p>Creating another Data loader block, this time using PostgreSQL connection and selecting dev environment.</p><p>With a simple SQL command, we can retrieve the data from the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*DIVE3CHIn-x35zTwe1cm6Q.png" /></figure><p>Successfully verifying that all data is present in the schema we defined.</p><h3>Part 2: Loading data to Google Cloud.</h3><p>I’m building based on the steps I detailed in my previous article on creating Google Cloud resources using Terraform. Once these resources are successfully created, I will replicate the pipeline that was constructed in Part 1. The only modification will be in the final block, which will be renamed as expoter_gcp.</p><p>In this new block, I’m using the pyarrow library to export data to Google Cloud Storage in Parquet format, a columnar storage file format optimized for use with big data processing frameworks.</p><pre>import pyarrow as pa<br>import pyarrow.parquet as pq<br>import os<br><br># Access credentials securely from environment variables<br>os.environ[&quot;GOOGLE_APPLICATION_CREDENTIALS&quot;] = &quot;/home/src/mycreds.json&quot;<br>bucket_name = &quot;terraform-mage-bucket&quot;<br>object_key = &quot;statsbomb_events.parquet&quot;<br>root_path = f&quot;{bucket_name}/{object_key}&quot; <br><br>@data_exporter<br>def export_data(data, *args, **kwargs):<br><br>    table = pa.Table.from_pandas(data)<br><br>    gcs = pa.fs.GcsFileSystem()<br><br>    pq.write_to_dataset(<br>        table,<br>        root_path=root_path,<br>        filesystem=gcs<br>    )<br><br></pre><p>In this block, I’m using the os library to securely access credentials from environment variables. The pyarrowlibrary is used to convert the pandas DataFrame to a PyArrow Table, which is then written to a Parquet file in the Google Cloud Storage bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhd6_eClnFK78SjYRvorOw.png" /></figure><p><strong>Adding a new trigger:</strong></p><p>Once I’m happy with my pipeline, I’m creating a schedule to trigger it, this process includes detailing:</p><ul><li>trigger type</li><li>Frequency</li><li>Start and End date</li><li>Name and description</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4Y7A6YBsduAZ0vvVFv-Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*p0cz6Z7G_XHj0HaIzirLiQ.png" /></figure><p><strong>Next steps:</strong></p><ul><li>Use BigQuery to analyze my data within Google Cloud.</li></ul><h3>Resources:</h3><ul><li><strong>Data Engineering Zoomcamp 2024 — Mage orchestration</strong></li></ul><p><a href="https://www.youtube.com/playlist?list=PL_ItKjYd0DsggZs-aPVsZMkJOOGeHaXge">https://www.youtube.com/playlist?list=PL_ItKjYd0DsggZs-aPVsZMkJOOGeHaXge</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d79e9b5f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Terraform on Windows to Create Resources in Google Cloud]]></title>
            <link>https://blog.devops.dev/running-terraform-on-windows-to-create-resources-in-google-cloud-297fb0e8cfae?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/297fb0e8cfae</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[installation]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 05:48:08 GMT</pubDate>
            <atom:updated>2024-02-28T17:08:57.548Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is Terraform?</strong></h3><p>Terraform is an infrastructure as a code (IaaC) tool that allows you to define both cloud and on-prem resources in human-readable configuration files. These files can be versioned, reused, and shared. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle.</p><p>Here are some of the benefits of using Terraform:</p><ul><li><strong>Simplicity:</strong> Keeping track of your infrastructure by defining it in a file.</li><li><strong>Collaboration:</strong> Easily collaborate with others by pushing your Terraform files to a repository like GitHub.</li><li><strong>Reproducibility:</strong> Easily recreate infrastructure in different environments.</li><li><strong>Ensure resources are removed:</strong> Easily remove resources that you are no longer using.</li></ul><p>Here are some things that Terraform is not:</p><ul><li>It does not manage or update code on infrastructure.</li><li>It does not give you the ability to change immutable resources.</li><li>It is not used to manage resources not defined in your Terraform files.</li></ul><p>Terraform is a powerful tool that can help you to easily provision and manage your infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*alnxQGf-oZhtXX329FH-QQ.png" /><figcaption>Basic Terraform — Cloud connection</figcaption></figure><p><strong>Key terraform commands:</strong></p><ol><li>terraform init: This command is used to initialize a working directory containing Terraform configuration files. It is the first command that should be run after writing a new Terraform configuration or cloning an existing one. It installs the necessary providers and sets up the backend for storing your state.</li><li>terraform plan: This command creates an execution plan. It determines what actions are necessary to achieve the desired state defined in the Terraform configuration files. This command is a dry run and shows what will happen when you apply your configuration.</li><li>terraform apply: This command applies the changes required to reach the desired state of the configuration. It will prompt you for confirmation before making any changes.</li><li>terraform destroy: This command destroys the Terraform-managed infrastructure. It will remove all resources that exist in the current state. It&#39;s the opposite of terraform apply.</li></ol><p><strong>Installation:</strong></p><p>There are several methods to install Terraform on your local machine:</p><ol><li><strong>Manual Download</strong>: You can download the Terraform binary from the official HashiCorp downloads page. After downloading, you need to unzip the package and move the binary to a directory in your system’s PATH.</li><li><strong>Package Managers</strong>: If you’re using a Unix-based system like Linux or macOS, you can use package managers to install Terraform. For macOS, you can use Homebrew and run brew install terraform. For Linux, the package manager depends on the distribution. For example, on Ubuntu, you can use snap with the command sudo snap install terraform.</li><li><strong>Chocolatey (Windows)</strong>: If you’re using Windows, you can use Chocolatey, which is a package manager for Windows. You can install Terraform by running choco install terraform.</li><li><strong>ASDF Version Manager</strong>: ASDF is a version manager that can manage multiple language runtime versions on a per-project basis. It supports Terraform and many other languages and tools. After installing ASDF, you can add the Terraform plugin and install Terraform with asdf install terraform &lt;version&gt;.</li></ol><p><strong>Steps:</strong></p><p>I chose the Manual Download, I found the appropriate package for my system and downloaded it as zip.</p><p><a href="https://developer.hashicorp.com/terraform/install">1- Download Terraform</a></p><p>2- Extract the .exe from the ZIP file to a folder, in my case.</p><p>C:\Terraform</p><p>3- Add the folder location to your PATH variable, go to: Control Panel -&gt; System -&gt; System settings -&gt; Environment Variables</p><p>4- In System Variables, select Path &gt; edit &gt; new &gt; Enter the location of the Terraform .exe, in my case:</p><p>C:\Terraform then click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*BfmaNum6FfzC8vItG3-2Vg.png" /></figure><p>Make sure Terraform is working by using the command terraform --help, you should get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkYIKSw9Y_uxB_md0viHDw.png" /></figure><p>Once Terraform is installed, we can Set up GCP</p><h3>Set up GCP:</h3><p>Create a service account:</p><ul><li>Click “Create Service Account”.</li><li>Give it any name you like and click “Create”.</li><li>Add roles to this service account, in my case: Cloud storage, Bigquery and Compute engine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*2HYv8WvPqNbtmwGE9UtICQ.png" /></figure><p>After you create your service account, download your service account key.</p><ul><li>Select your service account from the list.</li><li>Select the “Keys” tab.</li><li>In the drop-down menu, select “Create new key”.</li><li>Leave the “Key Type” as JSON.</li><li>Click “Create” to create the key and save the key file to your system.</li></ul><h3>The Terraform File configuration</h3><p>The Terraform configuration file used in this project is named main.tf. This file contains the necessary code to create and manage the desired resources on Google Cloud.</p><h3>Step 1: Define the Provider</h3><p>The first part of the file defines the required provider, which is Google Cloud in this case.</p><pre>terraform {<br>  required_providers {<br>    google = {<br>      source  = &quot;hashicorp/google&quot;<br>      version = &quot;4.51.0&quot;<br>    }<br>  }<br>}</pre><p>This block specifies that the Google Cloud provider is required and that version 4.51.0 of the provider should be used.</p><h3>Step 2: Configure the Provider</h3><p>The next part of the file configures the Google Cloud provider with the necessary credentials, project, region, and zone.</p><pre>provider &quot;google&quot; {<br>    credentials = &quot;mycreds.json&quot;<br>    project = &quot;resounding-hope-414923&quot;<br>    region = &quot;us-east1&quot;<br>    zone = &quot;us-east1-b&quot;<br>}</pre><p>The credentials field should point to a JSON file that contains your Google Cloud credentials. The project field is the ID of your Google Cloud project. The region and zone fields specify the default region and zone where your resources will be created.</p><h3>Step 3: Define the Resources</h3><p>The rest of the file defines the resources that will be created: a Google Cloud Storage bucket and a Google Compute Engine instance.</p><p>The Google Cloud Storage bucket is defined as follows:</p><pre>resource &quot;google_storage_bucket&quot; &quot;bucket&quot; {<br>    name = &quot;terraform-mage-bucket&quot;<br>    location = &quot;US&quot;<br>}</pre><p>This block creates a storage bucket named “terraform-mage-bucket” in the US location.</p><p>The Google Compute Engine instance is defined as follows:</p><pre>resource &quot;google_compute_instance&quot; &quot;default&quot; {<br>  name         = &quot;terraform-mage-instance&quot;<br>  machine_type = &quot;e2-micro&quot;<br><br>  boot_disk {<br>    initialize_params {<br>      image = &quot;debian-cloud/debian-11&quot;<br>    }<br>  }<br><br>  network_interface {<br>    network = &quot;default&quot;<br><br>    access_config {<br>      // Ephemeral IP<br>    }<br>  }<br>}</pre><p>This block creates a compute instance named “terraform-mage-instance” with the machine type “e2-micro”. The instance uses a Debian 11 image and is connected to the default network with an ephemeral IP.</p><h3>Initialize the directory:</h3><p>initialize the directory with terraform init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDBpf_XgITYmvOkrj-czYw.png" /></figure><p>Terraform downloads the google provider and installs it in a hidden subdirectory of your current working directory, named .terraform. The terraform init command prints the provider version Terraform installed. Terraform also creates a lock file named .terraform.lock.hcl, which specifies the exact provider versions used to ensure that every Terraform run is consistent. This also allows you to control when you want to upgrade the providers used in your configuration.</p><p><strong>Create infrastructure:</strong></p><p>Apply the configuration now with the terraform apply command and will print output to verify the plan.</p><pre>An execution plan has been generated and is shown below.<br>Resource actions are indicated with the following symbols:<br>  + create<br><br>Terraform will perform the following actions:</pre><p>If the plan looks right, type yes to proceed. It may take a few minutes for Terraform to provision the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8H1gPaay_QVWkfr0ll7uA.png" /></figure><p>Verifying that resources were correctly created.</p><p>Then a terraform.tfstate file will be created, which is a file that Terraform generates after applying your configuration. This file contains the state of your managed infrastructure and configuration. It uses this information to map resources in your configuration to real-world resources, to persist metadata about your resources, and to improve performance for large infrastructures.</p><p><strong>Verifying resources created.</strong></p><p>Bucket and compute engine details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*I8dH9Ce2sXVdRFfLnG2-gQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*A-DXBnTvDngigXzpQtMXYg.png" /></figure><p><strong>Destroy resources</strong></p><p>To avoid incurring charges I will destroy the resources created using terraform destroy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QikNS39c_EGC4AdqIuEpnA.png" /></figure><p>All resources were successfully destroyed just using one command.</p><p>Terraform seems magic, it’s a great tool to control your resources and keep a consistent and reproducible infrastructure.</p><h3>Conclusion</h3><p>Terraform provides a powerful and flexible way to manage cloud resources in a version-controlled, reproducible manner. This project demonstrated how to use Terraform to create and manage a Google Cloud Storage bucket and a Google Compute Engine instance. By defining your infrastructure as code with Terraform, you can ensure that your infrastructure is always in the desired state and can easily be recreated if necessary.</p><p><strong>Resources:</strong></p><p><a href="https://developer.hashicorp.com/terraform/tutorials/gcp-get-started/google-cloud-platform-build">https://developer.hashicorp.com/terraform/tutorials/gcp-get-started</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=297fb0e8cfae" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/running-terraform-on-windows-to-create-resources-in-google-cloud-297fb0e8cfae">Running Terraform on Windows to Create Resources in Google Cloud</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ETL project using Docker, PostgreSQL, Airflow and Azure storage: Football data from fbref]]></title>
            <link>https://medium.com/@ofelipefernandez/etl-project-using-docker-postgresql-airflow-and-azure-storage-football-data-from-fbref-287c4a3a872f?source=rss-f6f5e20b4e8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/287c4a3a872f</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Felipe Fernandez]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 04:51:58 GMT</pubDate>
            <atom:updated>2024-02-16T04:51:58.650Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore how Docker, PostgreSQL, Apache Airflow, and Azure Storage can be combined to create a robust and scalable data pipeline for football data from fbref. We will start by setting up a Docker environment to run PostgreSQL and Airflow, then we will use Airflow to automate the process of fetching, processing, and storing football data from fbref. The data will be stored in a PostgreSQL database and Azure Storage, providing a flexible and reliable storage solution. Whether you’re a football enthusiast looking to analyze player performance, or a data engineer interested in building data pipelines, this guide will provide valuable insights and practical steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*9LxMGPpVzM2RwhIEMqw1pw.png" /></figure><h3>Steps:</h3><h4>- Start docker containers</h4><p>Run docker-compose up -d to start the containers in detached mode.</p><pre>version: &#39;3&#39;<br><br>services:<br>  webserver:<br>    image: apache/airflow:2.6.0-python3.9<br>    command: webserver<br>    entrypoint: [ &quot;/opt/airflow/script/entrypoint.sh&quot; ]<br>    #    restart: always<br>    depends_on:<br>      - postgres<br>    environment:<br>     - AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres:5432/airflow<br>    volumes:<br>      - ./dags:/opt/airflow/dags<br>      - ./script/entrypoint.sh:/opt/airflow/script/entrypoint.sh<br>      - ./requirements.txt:/opt/airflow/requirements.txt<br>      - ./data:/opt/airflow/data<br>      - ./pipelines:/opt/airflow/pipelines<br>    ports:<br>      - &quot;8080:8080&quot;<br>    healthcheck:<br>      test: [ &quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8080/health&quot; ]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 3<br><br>  postgres:<br>    image: postgres:14.0<br>    environment:<br>      - POSTGRES_USER=${POSTGRES_USER}<br>      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}<br>      - POSTGRES_DB=${POSTGRES_DB}<br>  pgadmin:<br>    image: dpage/pgadmin4<br>    restart: always<br>    environment:<br>      - PGADMIN_DEFAULT_EMAIL=${PGADMIN_DEFAULT_EMAIL}<br>      - PGADMIN_DEFAULT_PASSWORD=${PGADMIN_DEFAULT_PASSWORD}<br>    volumes:<br>      - pgadmin_data:/root/.pgadmin<br>    ports:<br>      - &quot;5050:80&quot;<br>    depends_on:<br>      - postgres<br><br>  scheduler:<br>    image: apache/airflow:2.6.0-python3.9<br>    #    restart: always<br>    depends_on:<br>      webserver:<br>        condition: service_healthy<br>    volumes:<br>      - ./dags:/opt/airflow/dags<br>      - ./requirements.txt:/opt/airflow/requirements.txt<br>      - ./data:/opt/airflow/data<br>      - ./pipelines:/opt/airflow/pipelines<br>    environment:<br>      - AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://airflow:airflow@postgres:5432/airflow<br>     command: bash -c &quot;pip install --no-cache-dir -r ./requirements.txt &amp;&amp; airflow db upgrade &amp;&amp; airflow scheduler&quot;<br>    <br><br>volumes:<br>  pgadmin_data:</pre><p>The docker-compose.yml file defines four services: webserver, postgres, pgadmin, and scheduler. Here&#39;s a brief explanation of each service:</p><ol><li>webserver: This service uses the apache/airflow:2.6.0-python3.9 image and is configured to run the Airflow webserver. It has several environment variables set, including the database connection string and the base URL for the webserver. It also mounts several volumes from the host to the container, including the directory containing the DAGs and the .env file.</li><li>postgres: This service uses the postgres:14.0 image and is configured to run a PostgreSQL database. The username, password, and database name are set through environment variables.</li><li>pgadmin: This service uses the dpage/pgadmin4 image and is configured to run pgAdmin, a web-based PostgreSQL database browser. The default email and password for pgAdmin are set through environment variables. The pgadmin_data volume is mounted to persist pgAdmin data.</li><li>scheduler: This service uses the apache/airflow:2.6.0-python3.9 image and is configured to run the Airflow scheduler. Like the webserver service, it has several environment variables set and mounts several volumes from the host to the container. The command for this service first installs the Python packages listed in requirements.txt, then upgrades the Airflow database, and finally starts the Airflow scheduler.</li></ol><p>In addition to these services, the docker-compose.yml file also defines two volumes: logs and pgadmin_data. These volumes are used to persist data across container restarts</p><p>Once the services have started, Docker Desktop should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ki2IwRZnCqzE8gHxl-qwEQ.png" /></figure><h3>Start pgadmin:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Toq3um0TJUGR16e8yQ6Qg.png" /></figure><p>Register server and database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fIOeaactpRxuO6-E2TFeA.png" /></figure><p>Check for databases created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*5P8lO2gt8G69IW9SXcmtgg.png" /></figure><p>The Airflow database will have around 42 tables with all data from airflow services.</p><p>Clicking on postgres database will activate it, which will be empty. Our goal is to use this database and populate it with scraped football data.</p><h3>Start airflow webserver</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBGU_GBiLI34Kpg6FqTdkA.png" /></figure><ul><li>Store variables:</li></ul><p>Go to Admin&gt;Variables and store your variables, which will be used within the DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdk8guEtEhApOfiGvvO2Ug.png" /></figure><p>Within the Python flow, this section gets the values from variables and executes the task.</p><pre>leagues = Variable.get(&quot;leagues&quot;, default_var=&quot;Big 5 European Leagues Combined&quot;)<br>seasons = Variable.get(&quot;seasons&quot;, default_var=&quot;2022&quot;)<br>stat_type = Variable.get(&quot;stat_type&quot;, default_var=&quot;standard&quot;)<br><br>fbref = sd.FBref(leagues=leagues, seasons=seasons)<br><br>extract_team_season_stats = PythonOperator(<br>    task_id=&#39;process_team_season_stats&#39;,<br>    python_callable=process_team_season_stats,<br>    provide_context=True,<br>    op_args=[fbref, stat_type],  <br>    dag=dag<br>)<br><br>extract_team_season_stats</pre><ul><li><strong>Trigger dag in webserver:</strong></li></ul><p>Go to the DAG tab and click on your flow. There you can manually trigger your DAG and wait for the Python script to get the data from fbref, make some transformations, and Load it into PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQcT1VK2DiPjtKuK56OlSQ.png" /></figure><p>As you can see there were some failures before I made it work.</p><ul><li><strong>Check for data in pgAdmin:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzHA6UoOuwDlgOQJS8hFGg.png" /></figure><p>There are two tables now created, one for each type of stats: Keeper and Standard.</p><p>Once you change your variables into the Airflow webserver, it will Extract, Transform and Load (ETL) into the Database.</p><h3>Send Data to Azure Data Lake Storage (ADLS) using Azure CLI</h3><p>Azure Data Lake Storage (ADLS) is a highly scalable and secure data lake service from Microsoft Azure. It allows you to store and analyze large amounts of data, structured or unstructured, and is built to handle high-speed data streaming and real-time analytics.</p><p><strong>Steps:</strong></p><ol><li>Login to azure account using Azure CLI</li></ol><pre>az login</pre><p>2. Create resource group</p><pre>az group create --name resourcegroup-football-project --location eastus</pre><p>3. Create storage account</p><pre>az storage account create \<br> -- name staccfelipefootball \<br> -- resource-group resourcegroup-football-project \<br> -- location eastus \<br> -- kind StorageV2 \<br> -- sku Standard_LRS \<br> -- hierarchical-namespace true</pre><p>4. Create a filesystem in the storage account:</p><pre>az storage fs create --name myfilesystem --account-name staccfelipefootball</pre><p>5. Create folder directory:</p><pre>az storage fs directory create --name mydirectory --file-system myfilesystem --account-name staccfelipefootball</pre><p>6. Get string and replace in python script</p><pre>abfs://&lt;filesystem-name&gt;@&lt;account-name&gt;.dfs.core.windows.net/&lt;directory-name&gt;</pre><p>In my case:</p><pre>abfs://myfilesystem@staccfelipefootball.dfs.core.windows.net/mydirectory</pre><p>7. Get your storage account key:</p><pre>az storage account keys list --account-name staccfelipefootball --resource-group resourcegroup-football-project --query &quot;[0].value&quot; --output tsv</pre><p>8. Send to Azure Data Lake Storage-2 By Triggering the DAG again once you have made the changes within “fbref_getting_data_pipeline.py”</p><pre>storage_account_key = &lt;your_torage_account_key&gt;<br>azure_blob_connection_string = &lt;your_azure_blob_connection_string&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hpr7vt_Y4Qjg94pJ667jzQ.png" /></figure><p>Github repository can be found at:</p><p><a href="https://github.com/felipefe20/Azure-Dataeng-Football-Project">https://github.com/felipefe20/Azure-Dataeng-Football-Project</a></p><h3>Conclusion:</h3><p>We’ve explored how Docker, PostgreSQL, Apache Airflow, and Azure Storage can be leveraged to build a robust and scalable data pipeline for football data from fbref.</p><p>We’ve seen how Docker provides a consistent and isolated environment for our applications, how PostgreSQL serves as a reliable database solution, how Airflow automates and manages our data pipeline, and how Azure Storage offers a secure and scalable storage solution.</p><p>This combination of technologies provides a powerful platform for handling, analyzing, and storing large amounts of football data. Whether you’re a football enthusiast, a data scientist, or a data engineer, the knowledge and skills you’ve gained from this guide will undoubtedly prove useful in your future data projects.</p><p><strong>Notes:</strong></p><p>This is a project based on this amazing well-documented project, also on github:</p><p><a href="https://github.com/airscholar/FootballDataEngineering">https://github.com/airscholar/FootballDataEngineering</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=287c4a3a872f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>