<?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 Andrés Felipe Mesa David. on Medium]]></title>
        <description><![CDATA[Stories by Andrés Felipe Mesa David. on Medium]]></description>
        <link>https://medium.com/@andresf.mesad?source=rss-15b976bf670f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DrA1TgT6A2W0wH69t9jhYA.jpeg</url>
            <title>Stories by Andrés Felipe Mesa David. on Medium</title>
            <link>https://medium.com/@andresf.mesad?source=rss-15b976bf670f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:52:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andresf.mesad/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[An ELT pipeline with Airflow and GCP]]></title>
            <link>https://medium.com/@andresf.mesad/elt-pipeline-with-airflow-and-gcp-74954dd288fe?source=rss-15b976bf670f------2</link>
            <guid isPermaLink="false">https://medium.com/p/74954dd288fe</guid>
            <category><![CDATA[dataproc]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Andrés Felipe Mesa David.]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 05:48:34 GMT</pubDate>
            <atom:updated>2023-01-13T15:45:04.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>As a final project for a Data Engineer course, I have created an ELT pipeline moving data from a PostgreSQL database (running on Digital Ocean), implementing a Delta Lake with GCP services such as Cloud Storage, BigQuery, Dataproc and Data Studio. And to manage all the workflow and schedule the pipeline, we get Airflow running hosted on a Digital Ocean&#39;s Droplet (virtual machine) and with Docker.</p><p>This article will be divided into four sections:</p><ol><li>Talk about the Database.</li><li>How to run Airflow with Docker.</li><li>Let&#39;s talk about the pipeline itself.</li><li>Budget</li></ol><p>And to give a taste of how the pipeline looks, this is its structure.</p><figure><img alt="ELT pipeline schema" src="https://cdn-images-1.medium.com/max/1024/0*vfs-KQ1gt8uY4JqY.png" /><figcaption>ELT Pipeline Schema</figcaption></figure><h3>PostgreSQL Database</h3><p>To create a data pipeline, we need at least one data source. And this data source could be structured or not structured. This time I have selected a structured data source, a relational database.</p><p><a href="https://www.postgresqltutorial.com/postgresql-getting-started/postgresql-sample-database/">This database</a>, called dvdrental, is a PostgreSQL sample database provided by <a href="https://www.postgresqltutorial.com/">PostgreSQL Tutorial</a> (an excellent site to learn about PostgreSQL), which ERM is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*6GezXzG8GUsIXAxD.png" /><figcaption>ERM DVD rental</figcaption></figure><p>The DVD rental database represents the business processes of a DVD rental store. The DVD rental database has many objects, including 15 tables, which we will use to move to several layers in our data lake and BigQuery in a batch process, just as the previous diagram showed.</p><h3>Running Airflow with Docker on a Virtual Machine</h3><p>Orchestration and managing workflows could be a real pain in the ass, so a good option to work with this is Airflow. Airflow is an open-source platform for developing, scheduling, and monitoring batch-oriented workflows (just what we are looking for, right?).</p><p>But getting Airflow running could be tricky; you&#39;ll have to get up and running the web server, the scheduler and the airflow database. If only we could use some platform to containerize all our dependencies and, with a couple of commands, get this running without worrying too much about anything else.</p><p>Here is where Docker comes in handy. You can follow <a href="https://airflow.apache.org/docs/apache-airflow/stable/howto/docker-compose/index.html">this</a> tutorial to get Airflow running on your machine, or if you are more fan of videos, follow this tutorial; that&#39;s the one I used.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK9AnJ9_ZAXE%3Flist%3DPLwFJcsJ61oujAqYpMp1kdUBcPG0sE0QMT&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK9AnJ9_ZAXE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FK9AnJ9_ZAXE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb9d4a36dd25c05dbe90034cbb00b7ef/href">https://medium.com/media/bb9d4a36dd25c05dbe90034cbb00b7ef/href</a></iframe><p>We could have used Composer from GCP, but it&#39;s expensive, and we don&#39;t have many DAGs to include in Composer.</p><blockquote>Consider Composer if you want to implement this in a production environment with more pipelines and jobs to schedule. And if you have more budget, for sure.</blockquote><p>By the way, this is how our Airflow UI should look if you follow the steps on the README.md</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9y6vAmdmZRr81gaf-FOvIA.png" /><figcaption>Airflow UI</figcaption></figure><h3>Finally: The Pipeline</h3><p>Finally, after we have our data sources and orchestration platform, it&#39;s time to create each of the tasks that will be the pipeline&#39;s steps. But first, we&#39;ll need to:</p><ul><li>Create the GCS project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*fa3VTyH7cr6_OB1Ni41sKw.png" /><figcaption>GCP Project</figcaption></figure><ul><li>Create an account service in the GCP project with enough permissions to Dataproc, Cloud Storage and BigQuery (follow <a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts">the GCP docs</a>). I just gave it Editor privileges, but this is not a good practice.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*xgc3ZEAfn7fouZf8h72nTQ.png" /><figcaption>Account Service account</figcaption></figure><ul><li><a href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys#creating">Generate a key for that Service Account</a>, and store that JSON file someplace safe (you&#39;ll need to add this to Airflow Connections)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3uuVGkkWB3LK2b-znZxeDQ.png" /></figure><ul><li>Create google_cloud_default connection in Airflow in the Admin &gt; Connections panel. Put the JSON from the previous step in the Keyfile JSON field, fill in the project_id field, and then test the connection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*--ErpUPj-Sgbt8y99DBH7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KppR7AbIWFkXy13G6Z7E8Q.png" /></figure><ul><li>Now you need to create the connection to the PostgreSQL database, with the host, port, user and password to connect to the database. Make sure that user just has read privileges. You don&#39;t need anything more than that.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*AXdG5p_2NkJvD8ypyrVLHQ.png" /></figure><p>Now, let&#39;s discuss how the pipeline is defined. And what better way than with our DAG?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1klHG-lwjF8cQrtrmeVwA.png" /><figcaption>DAG Graph</figcaption></figure><p>You can see in the DAG that we have seven tasks (1 task and 6 task groups — the ones in blue). Let&#39;s talk about some of them briefly:</p><h4>bash_task</h4><p>This task generated a unique identifier for each run; this way, it is easier to track the logs.</p><pre>bash_task = BashOperator(<br>        task_id=&quot;bash_task&quot;,<br>        bash_command=&#39;echo &quot;[Date: $TODAY]&quot; with uuid: $UUID&#39;,<br>        env={&#39;TODAY&#39;: str(datetime.today().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)), &#39;UUID&#39;: uuid_run}<br>    )</pre><h4>move_tables_to_raw_bucket</h4><p>This TaskGroup loops over all 15 tables in the source PostgreSQL database and copy all its data (check the SQL argument) to GCS and move it to GCS. A bucket we have defined to store raw data. We do this with the PostgresToGCSOperator.</p><pre>with TaskGroup(group_id=&#39;move_tables_to_raw_bucket&#39;) as move_tables_to_raw_bucket:<br>        for table in SOURCE_TABLES:<br>            PostgresToGCSOperator(<br>                task_id=f&#39;move_{table}_to_raw_bucket&#39;,<br>                postgres_conn_id=POSTGRES_CONNECTION_ID,<br>                sql=f&#39;SELECT * FROM {table};&#39;,  # TODO: Execute specific query for each table.<br>                bucket=GCS_BUCKET,<br>                filename=f&#39;{table}/{table}.{FILE_FORMAT}&#39;,<br>                export_format=&#39;csv&#39;,<br>                gzip=False,<br>                use_server_side_cursor=False,<br>            )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*i8RAhW2zZ6urTjDVfWt0KA.png" /><figcaption>Raw data Bucket</figcaption></figure><h4>create_tables_in_dtlk_raw</h4><p>After storing our raw data in the bucket defined to keep it, we need to move it to our Data Lake: BigQuery. For this, we&#39;ll use GCSToBigQueryOperator. This operator enables us to transfer data from Cloud Storage and create a Table or append rows to a table in BigQuery. That&#39;s why we created another TaskGroup to execute this operator.</p><pre>with TaskGroup(group_id=&#39;create_tables_in_dtlk_raw&#39;) as create_tables_in_dtlk_raw:<br>        for table in SOURCE_TABLES:<br>            GCSToBigQueryOperator(<br>                task_id=f&#39;load_{table}_to_raw_dtlk&#39;,<br>                bucket=f&quot;{GCS_BUCKET}/{table}&quot;,<br>                source_objects=[&#39;*&#39;],  # all objects in that bucket<br>                source_format=&#39;CSV&#39;,<br>                skip_leading_rows=1,  # first row has header, ignore it<br>                # Big query fields<br>                destination_project_dataset_table=f&#39;{DATASET_RAW}.{table}&#39;,<br>                create_disposition=&#39;CREATE_IF_NEEDED&#39;,<br>                write_disposition=&#39;WRITE_TRUNCATE&#39;,<br>                gcp_conn_id=GOOGLE_CONN<br>            )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*qKr6I9bxOBiXJK2RMZIQ9A.png" /></figure><h4>raw_to_quality_layer</h4><p>Now, we have the data in our Data Lake, and as we would like to implement a Delta Lake, the following step is to move the data from the raw to the quality layer. But, we need to do a couple of transformations here using PySpark, and to use Apache Spark in GCP, you need to use Dataproc.</p><p>But where are the python scripts that use PySpark to transform the data? In the <a href="https://github.com/andresmesad09/airflow_with_docker">repo</a> (you&#39;ll find those files under the pyspark folder), but for Dataproc to use them, they need to be in a Cloud Storage Bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-5x_psNy5pZHqFKFEaX1w.png" /><figcaption>Dataproc bucket</figcaption></figure><p>Here is the 0_raw_to_quality.py.</p><pre>#!/usr/bin/python<br>from pyspark.sql import SparkSession<br><br>bucket = &#39;spark-final-project-bucket&#39;<br>DATASET_SOURCE = &#39;final_dtlk_raw&#39;<br>DATASET_TARGET = &#39;final_dtlk_quality&#39;<br>SOURCE_TABLES = [<br>    &#39;actor&#39;,<br>    &#39;address&#39;,<br>    &#39;category&#39;,<br>    &#39;city&#39;,<br>    &#39;country&#39;,<br>    &#39;customer&#39;,<br>    &#39;film&#39;,<br>    &#39;film_actor&#39;,<br>    &#39;film_category&#39;,<br>    &#39;inventory&#39;,<br>    &#39;language&#39;,<br>    &#39;payment&#39;,<br>    &#39;rental&#39;,<br>    &#39;staff&#39;,<br>    &#39;store&#39;<br>]<br>QUERY_MOVER = {<br>    &#39;actor&#39;: &#39;SELECT * FROM actor&#39;,<br>    &#39;address&#39;: &#39;SELECT address_id, address, district, city_id, postal_code, phone, last_update FROM address&#39;,<br>    &#39;category&#39;: &#39;SELECT * FROM category&#39;,<br>    &#39;city&#39;: &#39;SELECT * FROM city&#39;,<br>    &#39;country&#39;: &#39;SELECT * FROM country&#39;,<br>    &#39;customer&#39;: &#39;SELECT * FROM customer&#39;,<br>    &#39;film&#39;: &#39;SELECT * FROM film&#39;,<br>    &#39;film_actor&#39;: &#39;SELECT * FROM film_actor&#39;,<br>    &#39;film_category&#39;: &#39;SELECT * FROM film_category&#39;,<br>    &#39;inventory&#39;: &#39;SELECT * FROM inventory&#39;,<br>    &#39;language&#39;: &#39;SELECT * FROM language&#39;,<br>    &#39;payment&#39;: &#39;SELECT * FROM payment&#39;,<br>    &#39;rental&#39;: &#39;SELECT * FROM rental&#39;,<br>    &#39;staff&#39;: &#39;SELECT * FROM staff&#39;,<br>    &#39;store&#39;: &#39;SELECT * FROM store&#39;,<br>}<br><br>spark = (<br>    SparkSession<br>    .builder<br>    .master(&#39;yarn&#39;)<br>    .appName(&#39;bigquery_raw_to_quality&#39;)<br>    .getOrCreate()<br>)<br><br><br>spark.conf.set(&#39;temporaryGcsBucket&#39;, bucket)<br><br>for table in SOURCE_TABLES:<br>    print(table)<br>    spark_df = (<br>        spark<br>        .read<br>        .format(&#39;bigquery&#39;)<br>        .option(&#39;table&#39;, f&#39;{DATASET_SOURCE}.{table}&#39;)<br>        .load()<br>    )<br><br>    spark_df.createOrReplaceTempView(table)<br><br>    # actor is a pretty clean table, we could just move it to qty<br>    df_to_quality = spark.sql(QUERY_MOVER[table])<br><br>    df_to_quality.show()<br>    df_to_quality.printSchema()<br><br>    # Spark saving<br>    (<br>        df_to_quality.write.format(&#39;bigquery&#39;)<br>        .option(&#39;table&#39;, f&#39;{DATASET_TARGET}.{table}&#39;)<br>        .mode(&#39;overwrite&#39;)<br>        .save()<br>    )<br>    print(f&quot;Done with: {table}&quot;)</pre><p>After you have double-checked the logic on the script and uploaded that file to the Dataproc/Spark bucket, we can create our TaskGroup that would be in charge of creating a cluster with two workers (you can change this), submit a PySpark job to that cluster and after those two are done (failed or succeeded) delete the cluster (if you left the cluster running, it would be expensive).</p><pre>    with TaskGroup(group_id=&#39;raw_to_quality_layer&#39;) as raw_to_quality_layer:<br>        create_cluster_raw = DataprocCreateClusterOperator(<br>            task_id=&#39;create_cluster_raw&#39;,<br>            project_id=PROJECT_ID,<br>            cluster_name=CLUSTER_RAW,<br>            num_workers=2,<br>            # we need a bucket to store files from the cluster<br>            storage_bucket=SPARK_BUCKET,<br>            region=REGION,<br>        )<br><br>        pyspark_job_raw_to_qty = {<br>            &#39;reference&#39;: {<br>                &#39;project_id&#39;: PROJECT_ID,<br>                &#39;job_id&#39;: f&quot;raw_to_qty_{uuid_run}&quot;<br>            },<br>            &#39;placement&#39;: {<br>                &#39;cluster_name&#39;: CLUSTER_RAW<br>            },<br>            &#39;labels&#39;: {<br>                &#39;airflow-version&#39;: &#39;v2-4-1&#39;<br>            },<br>            &#39;pyspark_job&#39;: {<br>                # this is given by Google<br>                &#39;jar_file_uris&#39;: [&#39;gs://spark-lib/bigquery/spark-bigquery-latest_2.12.jar&#39;],<br>                # Python script that uses PySpark<br>                &#39;main_python_file_uri&#39;: &#39;gs://spark-final-project-bucket/0_raw_to_quality.py&#39;<br>            }<br>        }<br><br>        tables_from_raw_to_quality = DataprocSubmitJobOperator(<br>            task_id=&#39;tables_from_raw_to_quality&#39;,<br>            project_id=PROJECT_ID,<br>            region=REGION,<br>            job=pyspark_job_raw_to_qty,<br>            gcp_conn_id=GOOGLE_CONN<br>        )<br><br>        delete_cluster_raw = DataprocDeleteClusterOperator(<br>            task_id=&#39;delete_cluster_raw&#39;,<br>            project_id=PROJECT_ID,<br>            cluster_name=CLUSTER_RAW,<br>            region=REGION,<br>            trigger_rule=&#39;all_done&#39;<br>        )<br><br>        create_cluster_raw &gt;&gt; tables_from_raw_to_quality &gt;&gt; delete_cluster_raw</pre><p>The missing tasks are similar to the last but involve different PySpark jobs, scripts and layers. Finally, it&#39;ll create all the tables in the datasets in BigQuery (make sure to create the datasets first.)</p><p>After you have all the tasks defined, you need to set the dependencies of those tasks, and you do that in this manner.</p><pre># Order all task<br>(<br>    bash_task &gt;&gt; move_tables_to_raw_bucket &gt;&gt;  # noqa: W504<br>    create_tables_in_dtlk_raw &gt;&gt; raw_to_quality_layer &gt;&gt;  # noqa: W504<br>    quality_to_access_layer &gt;&gt; access_to_stage_layer &gt;&gt; stage_to_bus_layer<br>)</pre><p>Eventually, when you have curated tables and views in the business layer, you can use those as a source in Data Studio to create a dashboard and generate insights for the business stakeholders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWX9T0Tto4fpqUNt6UkDaA.png" /><figcaption>Dashboard</figcaption></figure><h3>How much did we spend, and how much will we spend?</h3><p>Here we will measure the money (or credits, in this case) spent in GCS because I assume you already have a budget for the data sources and that you&#39;ll run Airflow locally; but if you want to use a real virtual machine as the pros do, use <a href="https://m.do.co/c/80f26a159362">this link</a> to earn 200 USD in credits in Digital Ocean as create your Droplet.</p><blockquote>Earn 200USD on Digital ocean: <a href="https://m.do.co/c/80f26a159362">Here</a></blockquote><p>I developed this pipeline in 13 days, and I had to turn it off some days because I couldn&#39;t test it or I was struggling with a new feature, connection or Airflow task. So, how much did we spend on the development process? Although this billing report is not too useful, we could get an idea of which services we used and how much we could spend per month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B380R8OQaZAsXbKjH8_d1w.png" /></figure><p>Nevertheless, we could use the <a href="https://cloud.google.com/products/calculator">Google Cloud Pricing Calculator</a> to estimate our budget with the current data&#39;s volume and create an additional budget when the volume is ten times higher.</p><h4>Current volume</h4><p><a href="https://cloud.google.com/products/calculator/#id=bf06098e-5741-40b0-ac18-751cbc675f3f">Here</a> you can see the details of the budget. And no worries if you can&#39;t reach that link; in the budgets folder under the <a href="https://github.com/andresmesad09/airflow_with_docker">repo</a>, you can find the PDF generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR6kvJ3_vDn82zWski69tA.png" /></figure><h4>10x Current Volume</h4><p><a href="https://cloud.google.com/products/calculator/#id=d78baf87-82f2-42a7-9dc3-135958029600">Here</a> you can see the budget details for ten times the current volume; this will require more processing time in the Compute Engines that Dataproc needs, double the workers (from two workers to four), and probably the cluster will be running for doubled the hours (probably more or less, depending on how efficient the scripts are).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Gx_A-dqukIkN9BrJH2jcwg.png" /></figure><h3>Wrapping up</h3><p>This was a simple but powerful end-to-end ELT pipeline where we could use several GCP services and orchestrate everything with Airflow.</p><blockquote><a href="https://github.com/andresmesad09/airflow_with_docker">Here</a> is the repo with all code and PySpark scripts</blockquote><p>Stay tuned for more.</p><p>Follow me for more on <a href="https://www.youtube.com/@andresmesad">YouTube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74954dd288fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyze Data with PySpark]]></title>
            <link>https://medium.com/@andresf.mesad/analyze-data-with-pyspark-ae6ea91584fe?source=rss-15b976bf670f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae6ea91584fe</guid>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Andrés Felipe Mesa David.]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 22:14:02 GMT</pubDate>
            <atom:updated>2022-10-08T00:59:04.488Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you heard much about Spark but have no idea what it is? And, to keep it simple:</p><blockquote>Spark lets you spread data and computations over <em>clusters</em> with multiple <em>nodes</em> (think of each node as a separate computer)</blockquote><p>I plan to teach you how to analyze a sample data set in this article. Still, first, we’ll need to set up our environment to work with PySpark (And if you would like to complement this tutorial, FreecodeCamp has <a href="https://www.youtube.com/watch?v=_C8kWso4ne4">this</a> excellent video).</p><p>Nevertheless, installing Spark could be incredibly complicated; that’s why we will use Databricks, as this tool already has everything in place for you to start working right away.</p><p>If you want to create a free account, you can use the community edition <a href="https://www.databricks.com/try-databricks">here</a>.</p><p><strong>Note: </strong>Make sure to click on the Community Edition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC4z2ohksktXmQL6IZJPBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*l2LOODVOSlx5DylZKHVnPA.png" /></figure><p>And you should get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_xOMe4W_IoAqeiawDL0yw.png" /></figure><p>Before going into the details, you can watch a tutorial on my Youtube channel and why not, subscribe?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FetbaLvkoKdA&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DetbaLvkoKdA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/527ef6f06e342217213a936a35cfbc8f/href">https://medium.com/media/527ef6f06e342217213a936a35cfbc8f/href</a></iframe><p>Alright! It’s time to begin. But first, we need the data (that, of course, you can find on <a href="https://github.com/andresmesad09/analyze_data_pyspark/tree/main/data">my Github</a>). These tree files are part of a pretty small DB created to practice PySpark, and the ER model is the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxVcYEwk89YNqTJfVEi8sw.png" /></figure><blockquote><a href="https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/269241463296902/3213733448712832/4532987408519436/latest.html">Here</a> you can get the final Notebook in case you want to jump directly to the final result</blockquote><p>Now, you may wonder how to upload these files to Databricks. And you can do that by going into the sidebar &gt; Data &gt; Create Table (in the upper right)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UWB_Kcfk_0tx-uXqNYrKA.png" /></figure><p>And then upload these three files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kL2EJwUXx5__i4hDAAsoA.png" /></figure><p>We have imported all the necessary files in the FileStore (a particular folder within the Databricks File System (DBFS) where you can save files and have them accessible to your web browser). Check more details <a href="https://docs.databricks.com/dbfs/index.html">here</a>.</p><p>The files are in <strong>/FileStore/tables/project,</strong> and you can list them with the following command.</p><pre>%fs ls /FileStore/tables/project</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1PKjG74ZfLFmzjL8N_2-A.png" /></figure><h3>Let’s jump to analyze the data.</h3><p>Suppose that you want to answer the following questions:</p><ol><li>How much each customer spent in the restaurant?</li><li>How many days has each client visited the restaurant?</li><li>Which was the first item each client bought?</li></ol><p>But you need to import this data into your SparkSession (aka spark), and we are going to do that after importing all the necessary libraries</p><pre># Import sql types to define our schemas<br>from pyspark.sql.types import *<br># Import all SQL functions as F to clean and transform data<br>import pyspark.sql.functions as F<br># To do window functions<br>from pyspark.sql.window import Window</pre><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>I’m going to create the sales_df for you, and I’ll leave it up to you to create member_df and menu_df(remember you have the complete solution <a href="https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/269241463296902/3213733448712832/4532987408519436/latest.html">here</a> or in the <a href="https://github.com/andresmesad09/analyze_data_pyspark">repo</a>, and even more transformations and actions)</p><pre># Create a dictionary for the file locations<br>files = {<br>&#39;menu&#39;: &#39;/FileStore/tables/project/menu.csv&#39;,<br>&#39;members&#39;: &#39;/FileStore/tables/project/members.csv&#39;,<br>&#39;sales&#39;:&#39;/FileStore/tables/project/sales.csv&#39;}</pre><pre># Define the proper schema<br>sales_schema = StructType([<br>StructField(&#39;customer_id&#39;, StringType(), <strong>False</strong>),<br>StructField(&#39;order_date&#39;, DateType(), <strong>False</strong>),<br>StructField(&#39;product_id&#39;, IntegerType(), <strong>False</strong>),<br>])</pre><pre># Create the file pyspark DataFrame</pre><pre>sales_df = (<br>spark<br>.read.format(&#39;csv&#39;)<br>.options(header=<strong>True</strong>)<br>.schema(sales_schema)<br>.load(files[&#39;sales&#39;])<br>)</pre><pre>#Then do a display or show on the DataFrame<br>display(sales_df) # this is from Databricks, you can use .show() in pySpark</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wakru-GF17c1akSU8j_nRw.png" /></figure><p>After having all the data frames, let’s answer the first question.</p><pre>result_1_dataframe = (<br>    sales_df<br>    .join(<br>        menu_df,<br>        sales_df.product_id ==  menu_df.product_id,<br>        &quot;inner&quot;)<br>    .groupBy(&#39;customer_id&#39;)<br>    .agg(<br>        F.sum(&#39;price&#39;).alias(&#39;Total spend&#39;)<br>    )<br>    .orderBy(F.col(&#39;Total Spend&#39;).desc())<br>)<br>result_1_dataframe.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*vOJ7jXhGXXt9Gdx4rc3VdA.png" /></figure><p>We can graph this with pandastoo. How does it work? With the toPandas() method.</p><pre>result_1_dataframe = result_1_sql.toPandas()<br>sns.set(&#39;notebook&#39;)<br>sns.set_style(&#39;white&#39;)<br>fig, ax = plt.subplots()</pre><pre>sns.barplot(<br>    data=result_1_pandas,<br>    x=&#39;customer_id&#39;,<br>    y=&#39;total_spend&#39;,<br>    ax=ax<br>)<br>fig.suptitle(&#39;$Total Spend by each customer&#39;, fontsize=20)<br>plt.xlabel(&#39;Customer&#39;, fontsize=18)<br>plt.ylabel(&#39;$ Total Spend&#39;, fontsize=16)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBzcQC8kzGjj9tni2eiA7A.png" /></figure><p>We could have generated the same DataFrame with PySpark SQL but we need to create temporary views on DataFrame/Dataset by using createOrReplaceTempView() and using SQL to select and manipulate the data.</p><pre># Create the temporary views<br>sales_df.createOrReplaceTempView(&#39;sales&#39;)<br>members_df.createOrReplaceTempView(&#39;members&#39;)<br>menu_df.createOrReplaceTempView(&#39;menu&#39;)</pre><pre>#create the SQL logic as a string<br>result_1_query = &quot;&quot;&quot;<br>SELECT <br>     s.customer_id<br>    ,SUM(m.price) AS total_spend <br>FROM sales AS s<br>INNER JOIN menu AS m<br>    ON s.product_id = m.product_id<br>GROUP BY s.customer_id<br>ORDER BY total_spend DESC<br>&quot;&quot;&quot;</pre><pre># generate a PySpark DataFrame<br>result_1_sql = (<br>    spark<br>    .sql(result_1_query)<br>)</pre><pre># Show the result<br>result_1_sql.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*E6hR36IOIw3R7USyHtf03w.png" /></figure><p>As you just saw, we could transform our pyspark.dataframe.DataFrame into a pandas.core.frame.DataFrame and use Seaborn and Matplotlib to graph our data.</p><p>Also, we could use the cool features of Databricks to visualize our data to keep it simple. I aim to hand you as many tools as possible to handle real-life scenarios.</p><p>I’ll leave the other two questions as a challenge.</p><p>Finding it too complicated? Go to the solution I already provided.</p><p>Stay tuned for more.</p><p>Follow me for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae6ea91584fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Mesh and Data Fabric]]></title>
            <link>https://medium.com/@andresf.mesad/data-mesh-and-data-fabric-b7596f3d5cc4?source=rss-15b976bf670f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7596f3d5cc4</guid>
            <category><![CDATA[data-mesh]]></category>
            <category><![CDATA[data-fabric]]></category>
            <dc:creator><![CDATA[Andrés Felipe Mesa David.]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 01:57:25 GMT</pubDate>
            <atom:updated>2022-09-13T01:57:25.658Z</atom:updated>
            <content:encoded><![CDATA[<p>After a couple of articles about Google Cloud services, I&#39;d like to dive deep into two terms I have heard and read nowadays: Data Mesh and Data Fabric. So, let&#39;s start but first, here are the link to the two articles I talked to you about:</p><ul><li><a href="https://medium.com/@andresf.mesad/data-analytics-in-googlecloud-lets-dive-deep-into-it-37d9c0a3d86d">Data Analytics in GoogleCloud: Let’s dive deep into it</a></li><li><a href="https://medium.com/@andresf.mesad/a-glimpse-of-multi-cloud-databases-and-bi-platforms-5bf9bf716eda">A glimpse of multi-cloud: Databases and BI platforms.</a></li></ul><h3>Data Mesh</h3><p><strong>Why do we need a data mesh?</strong></p><p>Say we have a central data lake and a data team to drive their business based on data, but the data team becomes a bottleneck because they cannot process all the requirements quickly enough. Also, they need to learn domain knowledge and meet with Subject Matter Experts (SMEs) to give meaningful insights.</p><p>The domain and central data teams become worse with the organization&#39;s eventual growth. A way out of the issue is to shift the responsibility for data from the central data team to the domain teams. The previous idea is the core behind the data mesh concept: <strong>Domain-oriented decentralization for analytical data</strong>. A data mesh architecture enables domain teams to perform cross-domain data analysis on their own and interconnects data, similar to APIs in a microservice architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFZMBSK8VD6u7BaA6IzcbA.png" /></figure><p>A data mesh architecture is a decentralized approach that enables domain teams to perform cross-domain data analysis independently. The domain has its response team and operational and analytical data at its core. The domain team ingests operational data and builds analytical data models to perform their analysis. It uses analytical data to create data products based on other domains&#39; needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xisNzfo8lnkClDtBgppL4A.png" /></figure><h3>Data Fabric</h3><p>It is an architecture and set of data services that provide consistent capacities across various endpoints transiting hybrid multi-cloud providers.</p><p>It is a robust architecture that standardizes data management practices and practicalities across the cloud, on-premises, and edge devices. Among the many advantages a data fabric affords, data visibility and insights, data access and control, data protection, and security quickly rise to the top.</p><p><strong>Why do we need a data fabric?</strong></p><p>Data Fabric is what we are looking for if we need to monitor and manage our data and applications, regardless of where they live.</p><p>A data fabric is, at its heart, an integrated data architecture that&#39;s adaptive, flexible, and secure. In many ways, a data fabric is a new strategic approach to your enterprise storage operation, one that unlocks the best of cloud, core, and edge. While remaining centrally governed, it can reach anywhere, including on-premises, public and private clouds, and edge and IoT devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QfE2-5SXOAnebbl4G-s3mA.png" /><figcaption>Data Fabric</figcaption></figure><p>I hope this is of some help to you.</p><p>Follow me for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7596f3d5cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analytics in GoogleCloud: Let’s dive deep into it]]></title>
            <link>https://medium.com/@andresf.mesad/data-analytics-in-googlecloud-lets-dive-deep-into-it-37d9c0a3d86d?source=rss-15b976bf670f------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d9c0a3d86d</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Andrés Felipe Mesa David.]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 01:21:18 GMT</pubDate>
            <atom:updated>2022-09-13T01:21:18.250Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a lot of cloud services across all cloud providers, that’s is kind of difficult to pick just one or maybe tell the difference between them. This article aims to give a taste of all the services that Google Cloud provides in the sense of collecting, storing and analyzing data, i.e. Data Analytics.</p><p>Google Cloud has developed <a href="https://googlecloudcheatsheet.withgoogle.com/">this</a> cheat sheet where you can get an idea of which services there are and if they are related to computing, AI, storage, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLLWfsz_E-tT_FWwlo-qCA.png" /><figcaption>Data Analytics in Google Cloud</figcaption></figure><p>And I’d like to talk to you about Dataflow and BigQuery, a data warehouse and a data processing service, respectively.</p><h4>Dataflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*navUiVs6glCd4daP.png" /><figcaption>Dataflow</figcaption></figure><p>If you need to process extensive datasets or data stream processing, Apache beam is the tool that can process with a unified, portable, and extensible programming model. It’s a serverless, fast, cost-effective service for executing various data processing patterns. BigQuery it’s one of the runners you can choose from when you run data processing pipelines. At this time of writing, you can implement it in languages Java, Python, and Go.</p><p><strong>Use cases of Dataflow</strong></p><ul><li>Stream Analytics</li><li>Real-Time AI</li><li>Sensor and Log Data Processing</li></ul><p><strong>Characteristics</strong></p><ul><li>Vertical autoscaling</li><li>Right fitting</li><li>Smart diagnostics</li><li>Streaming Engine</li><li>Horizontal autoscaling</li><li>Dataflow SQL</li></ul><p>And there is more that you can find out <a href="https://cloud.google.com/dataflow">here</a>.</p><h4>BigQuery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o0AerokpiStHfQVJ.png" /><figcaption>BigQuery</figcaption></figure><p>Google BigQuery is a cloud-based big data analytics web service for processing extensive read-only data sets.</p><p>It’s designed for exploring and analyzing data on the order of billions of rows, using a SQL-like syntax. It runs on the Google Cloud Storage infrastructure and can be accessed with a REST-oriented application program interface.</p><p>Bigquery is a highly scalable, serverless and cost-effective multi-cloud data warehouse designed for business agility where you can:</p><ul><li>Build and operationalize ML models</li><li>Do interactive data analysis with BigQuery BI Engine</li><li>And you could bring any data to BigQuery to make your analytics easier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nlezTdYCKdkOzrEB3IZMw.png" /></figure><p>Now, let’s list a couple of its features:</p><ul><li>Serverless</li><li>Multicloud capabilities</li><li>Natural language processing</li><li>Built-in ML and AI integrations</li><li>Real-time analytics</li></ul><p>And, of course, there is more <a href="https://cloud.google.com/bigquery">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d9c0a3d86d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A glimpse of multi-cloud: Databases and BI platforms.]]></title>
            <link>https://medium.com/@andresf.mesad/a-glimpse-of-multi-cloud-databases-and-bi-platforms-5bf9bf716eda?source=rss-15b976bf670f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf9bf716eda</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[gateway]]></category>
            <category><![CDATA[postgressql]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Andrés Felipe Mesa David.]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 00:49:42 GMT</pubDate>
            <atom:updated>2022-09-13T00:49:42.897Z</atom:updated>
            <content:encoded><![CDATA[<p>What is the best analytic and Business Intelligence Platform? Should a company always use Power BI? We have seen Microsoft and Power BI leading Gartner’s BI and analytics magic quadrant yearly. It has many advantages over its competitors, and DAX will enable us to enhance our dashboards. Nevertheless, we use Google Cloud SQL to manage our relational data from a PostgreSQL database, so it might be better to use Looker.</p><p>Situations like the one described in the previous paragraph could happen in several technical meetings across several companies, but it is far from the truth. Even if Power BI and Cloud SQL belong to different providers, business users can use this BI tool to connect to and report from Cloud SQL PostgreSQL databases (also SQL Server and MySQL).</p><p>In this article, anyone will find guidance to configure Power BI reporting from Cloud SQL PostgreSQL. The steps are similar for MySQL and SQL Server, and if more details are needed, they will live within this Google article which is the source of inspiration for this one:</p><p><a href="https://cloud.google.com/blog/products/data-analytics/reporting-and-analytics-using-google-cloud-sql-and-microsoft-power-bi">https://cloud.google.com/blog/products/data-analytics/reporting-and-analytics-using-google-cloud-sql-and-microsoft-power-bi</a></p><p>There will be a couple of assumptions across the article to make it simple. One assumes that the creation of the Cloud SQL instance involved a Private IP address. Nevertheless, the necessary steps and documentation to do that will be <a href="https://cloud.google.com/sql/docs/postgres/private-ip">here</a>.</p><p>Later, create a Windows <a href="https://cloud.google.com/compute/docs/instances/create-start-instance">VM</a> in the same VPC as the Cloud SQL instances. Furthermore, install and configure the Power BI Gateway and the required ODBC connectors in this VM.</p><p>As the example provided here is for PostgreSQL, you can download the required ODBC connector here.</p><ul><li>Postgres: <a href="https://www.postgresql.org/ftp/odbc/versions/msi/">https://www.postgresql.org/ftp/odbc/versions/msi/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hHxpuqYeFgknNA_0.jpg" /><figcaption>PostgreSQL ODBC</figcaption></figure><p>There is no need to worry about the security of the traffic between the CloudSQL instance and the VM we just created because it is all encrypted via <a href="https://cloud.google.com/docs/security/encryption-in-transit">Encryption in Transit in Google Cloud</a>. But you could add another layer of security with CloudSQL <a href="https://cloud.google.com/sql/docs/mysql/configure-ssl-instance">SSL/TLS certificates</a>.</p><p>The next step is downloading, installing, and configuring the <a href="https://docs.microsoft.com/en-us/data-integration/gateway/service-gateway-communication">Power BI Gateway</a>. But do we need that Power BI Gateway? If you want to refresh your dashboards published to the Power BI workspace that will rely on the data from that Cloud SQL instance, then the simple answer is yes. No need to worry about it; this article will cover it straightforwardly, and this <a href="https://www.youtube.com/watch?v=i1W5kISMF50">video</a> may give you more details about this exciting topic in the leader BI tool: Power BI Gateway.</p><p>The creation of an on-premises data gateway (An on-premises data gateway is software that you install in an on-premises network. The gateway facilitates access to data in that network) involves the following steps.</p><ul><li>Create a new on-premises data gateway</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ovCPBJoa8vcd4d4v.jpg" /></figure><ul><li>Validate Gateway Configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Q5Sxaio8NE1FkFzu.jpg" /></figure><ul><li>Review logging settings</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*MUfepohvOnTo2mF0.jpg" /></figure><ul><li>Review HTTPS mode</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*ne7uiPlOjS2aEcg9.jpg" /></figure><p>And, of course, <a href="https://docs.microsoft.com/en-us/data-integration/gateway/service-gateway-install">this</a> will give you detailed screenshots and recommendations.</p><p>The second assumption, of course, is that the VM has Power BI Desktop installed. If not, this would be the suggested step to be able to log into Power BI and select “Settings” -&gt; “Manage gateways” to configure data sources.</p><figure><img alt="Manage Gateways" src="https://cdn-images-1.medium.com/max/600/0*L1mkIBgQGRxtI_4d.jpg" /><figcaption>Manage gateways</figcaption></figure><p>Then, in the Manage gateways window, we’ll add a data source for our Cloud SQL instance (or for each needed database instance) and click Apply. Or, before clicking Apply, you could test your connections to ensure everything is working correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*reU8Do83Dua1ptE-.jpg" /><figcaption>Adding data sources</figcaption></figure><p>Now, one might ask: when will we visualize the data? Are we going to create visualizations at some point? But of course. Now it is time.<br>Open the Power BI desktop again. Next, we’ll add data sources and create a report. For this, we must select “Get data” and add ODBC connections for CloudSQL SQL PostgreSQL, then create a sample report with data from that instance.</p><p>The following steps are the following:</p><ul><li>Publish the report to the Power BI service. And after publishing, update the data sources in the Power BI workspace to point to the data gateway data sources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*qb-cnBi32sPev0dy.jpg" /><figcaption>Publish to Power BI Service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hYHC6mtvGYD-rcgb.jpg" /><figcaption>Point to the data gateway sources</figcaption></figure><p>Then, you can set a refreshing time, update the data again and do a few tests to check everything was set up correctly.</p><p>Follow me for me.<br>Twitter: @andresmesad</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf9bf716eda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>