<?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 DataVizWiz on Medium]]></title>
        <description><![CDATA[Stories by DataVizWiz on Medium]]></description>
        <link>https://medium.com/@metin_63020?source=rss-7bd025fe3a63------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XFtGKOds5gst-Erg</url>
            <title>Stories by DataVizWiz on Medium</title>
            <link>https://medium.com/@metin_63020?source=rss-7bd025fe3a63------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:00:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@metin_63020/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[Rust: A Practical Guide to Building an ETL Pipeline]]></title>
            <link>https://medium.com/@metin_63020/rust-a-practical-guide-to-building-an-etl-pipeline-179691ba5a83?source=rss-7bd025fe3a63------2</link>
            <guid isPermaLink="false">https://medium.com/p/179691ba5a83</guid>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[DataVizWiz]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 09:20:09 GMT</pubDate>
            <atom:updated>2024-10-26T09:20:09.773Z</atom:updated>
            <content:encoded><![CDATA[<p>The modern tech stack in the data space is full of many exciting tools however, the fact you’ve sought out this article likely means you have started to wonder if a language, whose primary purpose is game development, cryptocurrency and system programming can play a part in data engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t9EexOrD2s3KbV370TE5A.jpeg" /><figcaption>With a little help from DALL-E, Ferris brings data processing to life.</figcaption></figure><p>The aim of this article is to provide exposure to what an ETL pipeline could look like in Rust. I will demonstrate how to,</p><ul><li>Read CSV files into memory</li><li>Apply mapping and filtering transformations</li><li>Modularize your code</li><li>Handle errors elegantly</li><li>Insert the data into a PostgreSQL database</li></ul><h3>Prerequisites</h3><p>You will need some basic familiarity with Rust. You will need to understand why we are using Rust; the advantages and benefits it brings with memory efficiency and performance as well as knowledge of these topics.</p><ul><li>Setting up a project</li><li>Crates</li><li>Modules</li><li>Structs</li><li>Methods</li><li>Implementations</li><li>Data types</li><li>Immutability</li><li>Serialization/deserialization</li></ul><h3>Business Scenario</h3><p>Using the <a href="https://www.kaggle.com/datasets/rounakbanik/the-movies-dataset">Movies dataset</a>, we are going to map the ratings to the metadata and create a data mart for five star romances.</p><p>This pipeline will mimic a simple version of an end-to-end ETL delivery; extracting data, applying transformations and then inserting the records to a database where it will be consumed by data analysts/scientists.</p><h4>Pipeline Steps</h4><p>There are 6 simple steps we will achieve in this tutorial:</p><ol><li>Step up our project and install our crates</li><li>Define our utilities</li><li>Define our data structure and vector for movies metadata</li><li>Define our data structure and mapping for ratings</li><li>Define our methods for PostgreSQL</li><li>Bring it together in main.rs</li></ol><h3>Setup</h3><p>Set up your project and add the required crates.</p><pre>cargo new movies<br>cargo add chrono -F serde<br>cargo add csv<br>cargo add postgres -F with-chrono-0_4<br>cargo add serde -F derive</pre><p>Using this folder structure, make our modules publicly available.</p><pre>src/<br>  movies/<br>    metadata.rs<br>    mod.rs<br>    ratings.rs<br>  utils/<br>    io.rs<br>    mod.rs<br>  lib.rs<br>  main.rs</pre><p>Inside lib.rs define movies and utils.</p><pre>// lib.rs<br>pub mod movies;<br>pub mod utils;</pre><p>Inside movies/mod.rs define metadata and ratings.</p><pre>// movies/mod.rs<br>pub mod metadata;<br>pub mod ratings;</pre><p>Inside utils/mod.rs define io.</p><pre>// utils/mod.rs<br>pub mod io;</pre><h3>Reading the CSV Files</h3><p>We will handle reading the files in io.rs. Using our csv crate, we define our builder and read from the file path where the path is our parameter of the function. We return a Result&lt;T, E&gt; allowing us to propagate our builder errors using ?.</p><pre>// io.rs<br>use csv::{Reader, ReaderBuilder, Trim, Error};<br>use std::fs::File;<br><br>pub fn read_csv(file: &amp;str) -&gt; Result&lt;Reader&lt;File&gt;, Error&gt; {<br>    let mut builder = ReaderBuilder::new();<br><br>    builder.delimiter(b&#39;,&#39;).has_headers(true).trim(Trim::All);<br><br>    let result = builder.from_path(file)?;<br>    Ok(result)<br>}</pre><h3>Movies Metadata</h3><h4>Defining Types</h4><p>Now we start to get into defining the struct and methods for movies_metadata.csv. We start by bringing our modules in scope. We use crate to bring read_csv into scope.</p><pre>// metadata.rs<br>use crate::utils::io::read_csv;<br>use chrono::NaiveDate;<br>use postgres::{Client, NoTls};<br>use serde::Deserialize;<br>use std::env;<br>use std::error::Error;</pre><p>When defining our types, we use Option to handle any fields where there are empty records, this allows us to return either a value or None. Furthermore, to use our fields in main.rs we must ensure both our struct and its attributes are public.</p><p>It is important to note that rating is not part of this source, however, as we will be mapping this field from another source and utilizing it in this struct, we can define it here for future use.</p><pre>// metadata.rs<br>#[derive(Deserialize, Debug)]<br>pub struct Movie {<br>    pub id: i32,<br>    pub budget: i32,<br>    pub genres: String,<br>    pub popularity: f32,<br>    pub release_date: Option&lt;NaiveDate&gt;,<br>    pub revenue: f32,<br>    pub runtime: Option&lt;f32&gt;,<br>    pub title: String,<br>    pub vote_average: f32,<br>    pub vote_count: i32,<br>    pub rating: Option&lt;f32&gt;,<br>}</pre><p>There are far more fields in the source data, but we only need to define the fields we want to use in the pipeline.</p><h4>Defining Methods</h4><p>We start with our Movie implementation. When we carry out our transformations in main.rs we will be working with vectors. To set us up for this as_vec reads our CSV into our reader, then looping each record in our reader, we deserialize our result using Movie to define our data structure, then append the resulting struct to a vector.</p><p>Both line 3 and 7 return results, whereby the error is then propagated using ?. As both variables can result in a csv error, we can explicitly define this in the return of the function. The Ok variant returns a vector of structs.</p><pre>// metadata.rs<br>impl Movie {<br>    pub fn as_vec() -&gt; Result&lt;Vec&lt;Movie&gt;, csv::Error&gt; {<br>        let mut reader = read_csv(&quot;data/movies_metadata.csv&quot;)?;<br>        let mut movies: Vec&lt;Movie&gt; = Vec::new();<br><br>        for result in reader.deserialize() {<br>            let movie: Movie = result?;<br>            movies.push(movie);<br>        }<br>        Ok(movies)<br>    }</pre><p>To link this to some familiarity in the data engineering world, think of this as your Pandas DataFrame.</p><h3>Ratings</h3><p>Our pipeline will map the rating of the movie to the metadata and to do so we will create a HashMap (key-value pair) of movie id’s and their rating.</p><p>Once again define our struct. The field in our source file is movieId, notice how we are using Serde to rename this attribute to comply with Rust’s idiomatic snake case naming.</p><p>We only require two fields from our CSV, let’s only define the two we need, otherwise, we end up with warnings for unused fields.</p><pre>// ratings.rs<br>use crate::utils::io::read_csv;<br>use serde::Deserialize;<br>use std::collections::HashMap;<br><br>#[derive(Deserialize)]<br>pub struct Rating {<br>    #[serde(rename(deserialize = &quot;movieId&quot;))]<br>    movie_id: i32,<br>    rating: f32,<br>}</pre><p>To create our mapping, we define our reader for ratings_small.csv, then initialize an empty HashMap. It is good practice to define the types of our HashMap entries, in our case our key will be of type i32 and our value will be of type f32.</p><p>Looping our deserialized reader, we define our data structure as Rating and then insert each row as a key-value pair in our HashMap. Once again propagating our errors.</p><p>Our resulting Ok variant will return our mapping from the function and upon errors, a csv error.</p><pre>// ratings.rs<br>impl Rating {<br>    pub fn as_map() -&gt; Result&lt;HashMap&lt;i32, f32&gt;, csv::Error&gt; {<br>        let mut reader = read_csv(&quot;data/ratings_small.csv&quot;)?;<br><br>        let mut map: HashMap&lt;i32, f32&gt; = HashMap::new();<br><br>        for result in reader.deserialize() {<br>            let rating: Rating = result?;<br>            map.insert(rating.movie_id, rating.rating);<br>        }<br>        Ok(map)<br>    }<br>}</pre><h3>Insert to PostgreSQL</h3><p>The last component before progressing onto our main function is our capability to insert into our PostgreSQL database. I have managed this in metadata.rs as all of the fields we need are defined in the Movie struct, it makes sense to keep it here.</p><p>Carrying on after as_vec, we define our database client. There is no need to make this method public as we do not require it outside of the module it resides in.</p><pre>// metadata.rs<br>...<br>      Ok(movies)<br>    }<br><br>    fn db_client() -&gt; Client {<br>        let conn_string = env::var(&quot;DB_CONN_STRING&quot;).expect(&quot;Key not found&quot;);<br>        Client::connect(&amp;conn_string, NoTls).unwrap()<br>    }</pre><p>I have set my connection string as an environment variable but this is an example of what it could look like.</p><pre>postgresql://myuser:mypassword@localhost:5432/movies</pre><p>Finally, we create our method to insert our data. As our function parameter, we pass in our vector of referenced movies (a vector of referenced structs). Ensure to use Self to access other methods of our implementation.</p><p>As we are using f32 types, we are required to use the SQL type REAL or FLOAT4 — FLOAT will <em>not</em> work and you will run into type mismatch errors.</p><pre>    // metadata.rs<br>    pub fn insert_rows(rows: Vec&lt;&amp;Movie&gt;) {<br>        let mut client = Self::db_client();<br><br>        client<br>            .batch_execute(<br>                &quot;<br>        CREATE TABLE IF NOT EXISTS five_star_romance (<br>            id                  SERIAL PRIMARY KEY,<br>            title               VARCHAR NOT NULL,<br>            release_date        DATE,<br>            budget              INT,<br>            popularity          REAL,<br>            revenue             REAL,<br>            runtime             REAL,<br>            vote_average        REAL,<br>            vote_count          INT,<br>            rating              REAL<br>        )<br>        &quot;,<br>            )<br>            .unwrap();<br><br>        for param in rows {<br>            client<br>            .execute(<br>                &quot;INSERT INTO five_star_romance (<br>                    title, release_date, budget, popularity, revenue, runtime, vote_average, vote_count, rating<br>                ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)&quot;,<br>                &amp;[<br>                    &amp;param.title,<br>                    &amp;param.release_date,<br>                    &amp;param.budget,<br>                    &amp;param.popularity,<br>                    &amp;param.revenue,<br>                    &amp;param.runtime,<br>                    &amp;param.vote_average,<br>                    &amp;param.vote_count,<br>                    &amp;param.rating,<br>                ],<br>            )<br>            .unwrap();<br>        }<br>    }<br>}</pre><h3>Main ETL</h3><p>Up till now we have just been defining our components for use in our transformation. main.rs will bring these components together to apply the mapping and load the final result to the database.</p><p>Previously, we used crate to bring the modules into scope. Now we are using pipeline. In simple terms, this is because when running something from main.rs you are at the top level, i.e. you are “outside” the project and you want to call something “inside” the project. However, we use crate because we are already “inside” the project when we bring a module into scope.</p><pre>// main.rs<br>use pipeline::movies::metadata::Movie;<br>use pipeline::movies::ratings::Rating;<br>use std::error::Error;</pre><p>Define our movies vector and ratings mapping by calling methods on our implementations. Once again propagating the errors.</p><pre>// main.rs<br>fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {<br>    let mut movies: Vec&lt;Movie&gt; = Movie::as_vec()?;<br>    let ratings_map = Rating::as_map()?;</pre><p>We are going to loop our vector of structs, however, we are going to need to modify the ratings field, so we want a <em>mutable reference</em> to each Movie. Why? We are saying, we want to <em>temporarily borrow</em> Movie so we can <em>change</em> rating. We <strong><em>do not</em></strong> want to transfer ownership, ownership must remain with the vector.</p><pre>// main.rs<br>...<br>    for movie in &amp;mut movies {</pre><p>.get() returns an Option that holds a reference to rating. To mitigate risks with any potential None values, we use if let but to ensure our condition matches we need to use Some(&amp;rating).</p><pre>// main.rs<br>...<br>        if let Some(&amp;rating) = ratings_map.get(&amp;movie.id) {<br>            movie.rating = Some(rating);<br>        } else {<br>            movie.rating = None;<br>        }<br>    }</pre><p>Then finally, we filter on films that are five star romances. movies is a collection, so we can apply the .iter() method to apply an action on all elements in the vector.</p><p>.iter() is part of the standard library from the Iterator trait, which has the method, .filter(). We apply our conditions, then use .collect() to return a new collection.</p><pre>    let fv_star_rom: Vec&lt;&amp;Movie&gt; = movies<br>        .iter()<br>        .filter(|&amp;movie| movie.rating == Some(5.0))<br>        .filter(|&amp;movie| movie.genres.contains(&quot;Romance&quot;))<br>        .collect();<br><br>    Movie::insert_rows(fv_star_rom);<br>    Ok(())<br>}</pre><p>Once we have our final results, we insert these records by passing in the filtered results as an argument to insert_rows().</p><p>Lastly, I want to bring your attention to the return of the function. As we scale this pipeline we will run into many errors as a result of many methods doing different things. To manage the various errors, we use Box to return a generic standard error.</p><p>To run the pipeline from your terminal.</p><pre>cargo run</pre><h3>Conclusion</h3><p>Hopefully, this has provided some insight on how Rust can be used for building data engineering pipelines. Borrowing and immutability are steep learning curves however, as this pipeline scales it is certain that having more control over how variables are owned and borrowed in the program reduces risks and ensures, not just memory efficiency but the safety of our data. Feel free to check out the source code in my <a href="https://github.com/DataVizWiz/rust-movies-etl/tree/medium-article">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=179691ba5a83" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>