<?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 Sonny Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Sonny Nguyen on Medium]]></description>
        <link>https://medium.com/@nszoni?source=rss-81e3d7a06326------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WsMbBPdPe_rOujbknOHnqg.png</url>
            <title>Stories by Sonny Nguyen on Medium</title>
            <link>https://medium.com/@nszoni?source=rss-81e3d7a06326------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:52:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nszoni/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[dbt Docs as a Static Website]]></title>
            <link>https://medium.com/hiflylabs/dbt-docs-as-a-static-website-c50a5b306514?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/c50a5b306514</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 12:35:20 GMT</pubDate>
            <atom:updated>2023-03-16T12:35:20.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1XJdqbjK-Yw1Dlu" /><figcaption>Photo by <a href="https://unsplash.com/@hngstrm?utm_source=medium&amp;utm_medium=referral">Henry &amp; Co.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>powered by App Engine and GitHub Actions</p><h4>Introduction</h4><p>dbt Docs allow us to intuitively inspect our DAG and dbt project documentation. Along with many of its limitations, we often find ourselves wanting to <strong>share this knowledge outside dbt Cloud</strong> or our local machine.</p><p>Suppose we want to share this with our stakeholders. Then, they have to have a Cloud viewer login, which is <a href="https://www.getdbt.com/blog/dbt-cloud-package-update/">at least $100 a seat</a> as of today (assuming that you are a relatively small organization), and going through 4–5 steps just to get to the documentation, which is no good.</p><p>There should also be a solution for those who are only using dbt-core and handling scheduling and CI/CD with Airflow and co. plus any integration service. There must be something better than paying for an EC2 instance just to keep a static web server there, right?</p><p>The official dbt documentation gives you <a href="https://docs.getdbt.com/docs/collaborate/documentation#deploying-the-documentation-site">some options</a>, but none of them fits to a GCP* stack, and we still lack the A-Z guide for this.</p><p><em>This walkthrough was created with GCP in mind, but the same could be applied to all other cloud service vendors.</em></p><h4>Options</h4><p>Although it is still an <a href="https://github.com/dbt-labs/dbt-docs/issues/53">open issue</a>, luckily the community delivered again, and we are able to deploy our docs in a very straightforward way on a static website, where the cost of hosting is actually zero.</p><p>There are actually three ways to do this:</p><ol><li>Fast and easy way: <a href="https://cloud.google.com/appengine/docs/legacy/standard/python/getting-started/hosting-a-static-website"><strong>Hosting with App Engine</strong></a></li><li>Slow and more painful, but cleaner way: <a href="https://codelabs.developers.google.com/codelabs/cloud-webapp-hosting-gcs#0"><strong>Hosting a static website from GCS</strong></a><strong>.</strong></li><li>Fastest and easiest, but needs access to repo: <a href="https://docs.github.com/en/pages/getting-started-with-github-pages/creating-a-github-pages-site"><strong>GitHub Pages</strong></a></li></ol><p>The cost difference between all these? <strong>Close to zero. </strong>They are all free if you don’t have a lot of incoming network traffic.</p><p>For the rest of this article, I’m going to walk you through the process of deploying to App Engine. Here, we don’t have to register our custom domain, configure an <a href="https://cloud.google.com/load-balancing">HTTPS load balancer</a> or find alternatives for setting up <a href="https://cloud.google.com/iap">IAP</a> on backend buckets. All in all, there is no operational cost whatsoever on serverless products.</p><p>GitHub Pages is also ruled out in many cases, because if we want to make the documentation private, it’s going to only be accessible for those who also have access to the repository, therefore have GitHub accounts.</p><p>Just like with lots of other services, Google offers a <a href="https://cloud.google.com/free/docs/free-cloud-features#app-engine">free quota</a> for App Engine which you are not likely to use up, given that it is a static website and the deployment is going to happen now and then. Knowing this, GCP allocates the smallest virtual instance to do the light work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-C3mXRBCyG-8rxQJ9Dldg.png" /><figcaption>High-level deploy plan</figcaption></figure><h4>Step 1. Setup App Engine!</h4><blockquote><strong>Google App Engine</strong> is a cloud computing platform as a service for developing and hosting web applications in Google-managed data centers.</blockquote><p><strong>Requirements:</strong></p><ul><li>Google Cloud CLI: <a href="https://cloud.google.com/sdk/docs/install">https://cloud.google.com/sdk/docs/install</a></li><li>Deploy file app.yml in your dbt project’s root directory</li></ul><pre>service: default<br>runtime: python311<br><br>handlers:<br><br>- url: /<br>  static_files: public/index.html<br>  upload: public/index.html<br><br>- url: /<br>  static_dir: public<br><br>- url: /.*<br>  secure: always<br>  redirect_http_response_code: 301<br>  script: auto</pre><p>Translating what’s above,</p><ul><li>The deployment uses Python 3.11 in runtime,</li><li>Uploads and <a href="https://cloud.google.com/appengine/docs/standard/serving-static-files?tab=python#serving_from_your_application">serves static</a> index.html from the target directory, where you are storing the docs artifacts</li><li>Maps the root URL to the docs file.</li><li>The <strong>/.</strong>* handler matches all other URLs and directs them to your app.</li></ul><p>More on app.yml configurations <a href="https://cloud.google.com/appengine/docs/legacy/standard/python/config/appref">here</a>.</p><p><strong>Cost of hosting:</strong></p><p><a href="https://cloud.google.com/free/docs/free-cloud-features#app-engine">Free tier</a> (static website runs on ‘F’ instance)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyynB-pcpTsbCrTGE8iOqw.png" /><figcaption>App Engine Free Tier</figcaption></figure><p><a href="https://stackoverflow.com/questions/51854712/understanding-instance-hours-on-the-google-cloud-platform">Instance hours</a> are displayed here, which means you are charged for the <strong>time it’s active +15 minutes</strong> (every time an instance spins up), because it remains active after the last request.</p><p>If you have few requests, but they are spaced out evenly, your instance would shut down, and you’ll incur the 15-minute charge the next time the instance spins up again.</p><p>After you surpass the free tier limit, the following <a href="https://cloud.google.com/appengine/pricing">billing</a> scheme applies per hour (depending on the location).</p><p><em>In our case, there is no outgoing network traffic (egress), so feel free to ignore that part of the billing.</em></p><p>Tldr:</p><blockquote>28 hours of instance time per day for free, then a couple of cents per instance hour.</blockquote><p>It’s literally free for companies who rarely check the website. However, when queries requests are arriving in a way that we have to restart the instance each time, the quota can be easily surpassed, but let’s be honest the cost is still bearable.</p><h4>Standalone dbt docs</h4><blockquote>Huge thanks to <a href="https://data-banana.github.io/dbt-generate-doc-in-one-static-html-file.html">Data banana</a>!</blockquote><p>If you want the static docs to work locally without running a local web server, you can put the content of the JSON files (manifest, catalog) directly in index.html and remove network loading.</p><p>Now, you can:</p><ul><li>Directly open the index.html without <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a> restriction in local</li><li>Upload and host the documentation in some cloud storage, like Google Cloud Storage. As of this moment, this is not the case yet.</li><li>Easily distribute it to your stakeholders via email and co.</li></ul><pre>import json<br>import re<br>import os<br><br>PATH_DBT_PROJECT = &quot;&quot;<br><br>search_str = &#39;o=[i(&quot;manifest&quot;,&quot;manifest.json&quot;+t),i(&quot;catalog&quot;,&quot;catalog.json&quot;+t)]&#39;<br><br>with open(os.path.join(PATH_DBT_PROJECT, &#39;target&#39;, &#39;index.html&#39;), &#39;r&#39;) as f:<br>    content_index = f.read()<br>    <br>with open(os.path.join(PATH_DBT_PROJECT, &#39;target&#39;, &#39;manifest.json&#39;), &#39;r&#39;) as f:<br>    json_manifest = json.loads(f.read())<br><br># In the static website there are 2 more projects inside the documentation: dbt and dbt_bigquery <br># This is technical information that we don&#39;t want to provide to our final users, so we drop it<br># Note: depends on the connector, here we use BigQuery <br>IGNORE_PROJECTS = [&#39;dbt&#39;, &#39;dbt_bigquery&#39;]<br>for element_type in [&#39;nodes&#39;, &#39;sources&#39;, &#39;macros&#39;, &#39;parent_map&#39;, &#39;child_map&#39;]:  # navigate into manifest<br>    # We transform to list to not change dict size during iteration, we use default value {} to handle KeyError<br>    for key in list(json_manifest.get(element_type, {}).keys()):  <br>        for ignore_project in IGNORE_PROJECTS:<br>            if re.match(fr&#39;^.*\.{ignore_project}\.&#39;, key):  # match with string that start with &#39;*.&lt;ignore_project&gt;.&#39;<br>                del json_manifest[element_type][key]  # delete element<br>    <br>with open(os.path.join(PATH_DBT_PROJECT, &#39;target&#39;, &#39;catalog.json&#39;), &#39;r&#39;) as f:<br>    json_catalog = json.loads(f.read())<br><br># create single docs file in public folder<br>with open(os.path.join(PATH_DBT_PROJECT, &#39;public&#39;, &#39;index.html&#39;), &#39;w&#39;) as f:<br>    new_str = &quot;o=[{label: &#39;manifest&#39;, data: &quot;+json.dumps(json_manifest)+&quot;},{label: &#39;catalog&#39;, data: &quot;+json.dumps(json_catalog)+&quot;}]&quot;<br>    new_content = content_index.replace(search_str, new_str)<br>    f.write(new_content)</pre><h4>First Deploy</h4><p>Now that we have everything set up to make our first deploy manually, let’s see if it works!</p><p><em>You have to make sure that </em><em>index.html keeps updating in the </em><em>public/ folder with </em><em>glue-dbt-artifacts.</em></p><p>Authenticate with gcloud</p><pre>gcloud auth application-default login</pre><p>Deploy and inspect</p><pre>gcloud app deploy --project my-project --quiet<br>gcloud app browse --project my-project</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnHy82318EEr8Leka3_gBg.png" /><figcaption>Docs generate &gt; glue artifacts &gt; deploy &gt; browse</figcaption></figure><p>You should be prompted to a new browser tab with the dbt Docs which means your docs is live!</p><p>You can also set up your <a href="https://support.google.com/domains/answer/6009957?hl=en">custom domain</a>.</p><h4>Step 2. Manage Access with IAP!</h4><p>By now, your static website is live, but also open to the public, which is not what we want.</p><blockquote>Identity-Aware Proxy intercepts web requests sent to your application, authenticates the user making the request using the Google Identity Service, and only lets the requests through if they come from a user you authorize.</blockquote><p><a href="https://cloud.google.com/beyondcorp-enterprise/docs/securing-app-engine">Securing App Engine apps with IAP | BeyondCorp Enterprise | Google Cloud</a></p><p>For this, following Step 1. of the <a href="https://codelabs.developers.google.com/codelabs/user-auth-with-iap#2">codelabs</a> guide should be enough.</p><p>This guides you from having a public static website to full access control of Google IAM resources via OAuth.</p><p>It’s handy if your organization is Google Suite-first, because it is possible to add groups as well, meaning you can also restrict the access to your company’s domain. This is where Google Cloud Platform really shines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vw_UsJDppIMK3kCdxWR0pw.png" /><figcaption>You should see something like this with IAM switch on</figcaption></figure><h4>Step 3. Deploy with GitHub Actions!</h4><p>So, there you go, now you have a secured website. What’s next is to find out how to periodically deploy dbt Docs to App Engine. There are a handful of solutions that can work (e.g. scheduled custom script hitting the Cloud and AppEngine API), but some are cumbersome and don’t solve the issue for core-first users.</p><p><a href="https://github.com/features/actions">Github Actions</a> has been here for a while, and it’s free up to 2,000 CI/CD minutes/month (unlimited for public repositories) if your (small) organization is on the Free plan, which should be enough.</p><p>More on GitHub Actions billing <a href="https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions">here</a></p><p>The workflow below.</p><ol><li>Initializes secrets; you can <a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets">set your secrets on GitHub</a></li><li>Defines trigger strategy (on merge/push to the prod branch)</li><li>Use Ubuntu as base image, checkout out the repo, replicate key file for gcloud CLI</li><li>Install Python + dependencies</li><li>Generate dbt docs</li><li>Standalone index.html</li><li>Authenticate and deploy to App Engine</li></ol><p>Store this in .github/workflows/&lt;your_workflow_name&gt;</p><pre># This is a basic workflow to show using this action<br><br># name of the workflow<br>name: Deploy dbt docs to Google AppEngine<br><br>env:<br>  DBT_PROFILES_DIR: ./.github/<br>  DBT_GOOGLE_PROJECT_PROD: ${{ secrets.DBT_GOOGLE_PROJECT_PROD }}<br>  DBT_GOOGLE_BIGQUERY_DATASET_PROD: ${{ secrets.DBT_GOOGLE_BIGQUERY_DATASET_PROD }}<br>  # The DBT_GOOGLE_BIGQUERY_KEYFILE_PROD secret will be written to a json file below<br>  DBT_GOOGLE_BIGQUERY_KEYFILE_PROD: ./service-account.json<br><br># Controls when the workflow will run<br>on:<br>  push:<br>    branches: [ prod ]<br><br>  # Allows you to run this workflow manually from the Actions tab if needed<br>  workflow_dispatch:<br><br>jobs:<br>  deploy-docs:<br>    name: Deploy dbt docs to Google AppEngine<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: &#39;read&#39;<br>      id-token: &#39;write&#39;<br><br>    steps:<br><br>    - name: Checkout<br>      uses: actions/checkout@v3<br><br>    # get dbt service account keyfile<br>    - name: Get SA keyfile<br>      run: &#39;echo &quot;$KEYFILE&quot; &gt; ./service-account.json&#39;<br>      shell: bash<br>      env:<br>        KEYFILE: ${{ secrets.DBT_GOOGLE_BIGQUERY_KEYFILE_PROD }}<br><br>    - name: Setup Python<br>      uses: actions/setup-python@v4<br>      with:<br>        python-version: &#39;3.10.x&#39;<br><br>    - name: Install dependencies<br>      run: |<br>        pip install -r requirements.txt<br>        dbt deps<br><br>    # compile latest version of docs<br>    - name: Generate dbt docs<br>      run: |<br>        dbt docs generate<br><br>    # glue together index, manifest, catalog and run_results to a standalone html file<br>    - name: Glue dbt docs elements<br>      run: |<br>        python glue-dbt-artifacts.py<br><br>    # authenticate with appengine service account<br>    - name: Authenticate with SA<br>      uses: &#39;google-github-actions/auth@v1&#39;<br>      with:<br>        credentials_json: &#39;${{ secrets.GOOGLE_APP_ENGINE_DEPLOY_KEY }}&#39;<br><br>    - name: Deploy to AppEngine<br>      uses: &#39;google-github-actions/deploy-appengine@v1&#39;<br>      with:<br>        project_id: &#39;gcp-project-name&#39;<br>        flags: &#39;--quiet&#39;</pre><h4>Step 4. Test Your Workflow!</h4><p>When it comes to testing GitHub Actions, we can use act to generate test cases (imitate push event). Act spins up a Docker instance of your choice* and runs the actions in a context of what triggers it.</p><p><em>*You have to have </em><a href="https://docs.docker.com/get-docker/"><em>Docker installed</em></a><em> on your desktop</em></p><p><a href="https://github.com/nektos/act">GitHub - nektos/act: Run your GitHub Actions locally 🚀</a></p><p>We can supply GitHub secrets in multiple ways, but I chose to do so with a secret file (defined the same way as a .env file). Note, we have to do this because we are not touching the remote repository, so the secrets you have already set up are not within scope.</p><p>Those who are running this on Apple Silicon will likely experience some compatibility issues, so I suggest to spin up an AMD container instance instead.</p><pre>act — container-architecture linux/amd64 — secret-file ‘my.secret’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HygodqWh_k401W4jtz8cfQ.png" /><figcaption>You can also run act — dryrun to see the plan</figcaption></figure><h4>Limitations</h4><p><strong>Live metrics on artifact</strong></p><p>Deploying on each push to the main branch, we assumed that the documentation only changes at those events, but it is rarely the case.<strong> Table/model metadata evolves over time </strong>(rows, size, etc.) without changing anything in dbt inducing a push event.</p><p><strong>Displaying sensitive images in docs</strong></p><p>I still haven’t found a good way to display sensitive images referenced in dbt docs. I have tried hosting those images on GCS and restricting the access to the same Google group, but it seems that App Engine is not able to extrapolate the authentication.</p><h4>Conclusion</h4><p>In a nutshell, I just gave you an A-Z guide on how to host and test your dbt Docs on a GCP stack. It barely costs any money, and keeping the documentation up-to-date is seamless with GitHub Actions. Also, since you have a standalone .html file, you can make all other sorts of distributions within your organization. There are some limitations to it, but I think this is currently the best way to bring data democratization further in the dbt community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c50a5b306514" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/dbt-docs-as-a-static-website-c50a5b306514">dbt Docs as a Static Website</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Zen of Avoiding the Cloud Cost Fallacy]]></title>
            <link>https://medium.com/hiflylabs/the-zen-of-avoiding-the-cloud-cost-fallacy-807433407cb2?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/807433407cb2</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 09:38:05 GMT</pubDate>
            <atom:updated>2023-02-05T17:14:00.783Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://thedecisionlab.com/biases/the-sunk-cost-fallacy">Sunk cost</a> in the data space?</p><p>Let’s be honest, 2022 was a good year for data and a lot of companies moved closer to working with data (kinda induced by the pandemic). Also, you probably saw a lot more job openings on LinkedIn to kickstart an <a href="https://www.getdbt.com/what-is-analytics-engineering/">analytics engineering</a> team. There is still a lot to explore, but more and more companies start to realize how valuable data is in the first place and how dbt shortens the learning curve.</p><p>This also means that they probably got slapped with a big chunk of the budget as an investment into digitalization. What do you do when you have money? You SPEND, right?!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*I2rR0AuLNxQQyOcFiPuiCA.png" /><figcaption>Wake up Huel, we need to plan next year’s budget!</figcaption></figure><h4>Bad signs</h4><p>Improvements in data analytics in the last decade spoilt us in a way. Extremely cheap storage decoupled from compute completely gave the notion of “scalability” a different meaning and boundaries. On-demand pricing instead of hefty license fees back in the Oracle days gave us flexibility to only pay for what you use. You can always use more resources and increase our capacities to fit our scale. However, <a href="https://www.investopedia.com/terms/e/economiesofscale.asp">economies of scale</a> are different. You can’t keep up with the exponentially increasing costs as a function of data growth.</p><blockquote>“Sit back, enjoy the ride! We will pay the bills at the end of the month.” — Our inner devil</blockquote><p>As the data grows along with the business requirements, you start to see bills getting into a region where it needs to be seriously addressed. Boards are pulled together and Bill asks</p><blockquote>“Hmm why is there a big spike in Snowflake costs, Joe?” — Bill</blockquote><p>The team starts to nervously dig into parts of the code where you can cut costs, but oftentimes it seems like they are navigating unknown waters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WU7w1Lc7Y7jfeklsz3PM3g.png" /><figcaption>Data cloud costs if we don’t monitor them…</figcaption></figure><ul><li>Tools like dbt, Snowflake, BigQuery, etc. push down the cost of operations (which is awesome) but also make us get too comfortable.</li><li>It’s great to see a plethora of freemium tools, at the end of the day, they keep our warehouses active (not a great combo with Snowflake’s pricing model). Even what’s ‘free’ is only free in its own sense.</li><li>A data observability tool works usually well if it records the data more frequently, but then it keeps waking up the warehouse*. Many don’t know that <a href="https://docs.snowflake.com/en/user-guide/cost-understanding-compute.html">Snowflake bills for a minimum of 60 seconds</a> after firing up a compute resource (i.e. even if your query finishes in 1s, it bills for 60s).</li></ul><p>*does not use warehouse for information schema queries (row count, size, table type, etc) + cached queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wUtn5FYkNsAX9xIBchvgaQ.png" /><figcaption>Jim, come get your free tool!</figcaption></figure><ul><li><em>Do it well or do it fast.</em> Codebases are not perfectly polished anymore. Sufficient or good enough code works just fine, it is not worth perfectly optimizing something as long as it’s within our tolerance threshold. This is fine in such a fast-paced environment, as long as you keep track of all the tech debts.</li><li><a href="https://www.merriam-webster.com/dictionary/if%20it%20ain%27t%20broke,%20don%27t%20fix%20it">If it ain’t broke, don’t fix it</a>. Spaghetti code leads to indirect costs. (more time for onboarding and implementing a new feature).</li><li>Vendors are going to charge more. Although business-wise, the <a href="https://www.getdbt.com/blog/dbt-cloud-package-update/">dbt Cloud cost increase</a> made total sense, announcing it after most of us have agreed on our 2023 budget was a big slap. You should prepare for higher SaaS fees in the future, as the upside is still there to charge for.</li><li>We drive towards a data space where everyone wants to sell everything (i.e. data observability tools offering cataloguing and profiling). Even things you might even not need.</li></ul><blockquote><em>One tool to rule them all, one tool to bring them all — Me</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8FbGpkMFPc0XRaLXGP--mw.png" /><figcaption>“THE” data tool</figcaption></figure><h4>Good Signs</h4><p>So what else happened in 2022? The global economy got hit seriously and many tech companies overstaffed, and overestimated their productivity, so they started to do mass lay-offs. No, this is not a “good sign” by any means, but it really brought us back to reality to appreciate the cost limiting features of cloud data warehouses.</p><ul><li><strong>We started to care. </strong>Snowflake cost estimators are now often requested by our clients, and people in the community, raising awareness of cloud spending.</li><li><strong>We understood</strong> that to transparently analyze our costs, we might need to reach deeper into our pockets.</li><li><strong>We have more options now</strong>. <a href="https://docs.snowflake.com/en/user-guide/ui-query-profile.html">Snowflake</a>, <a href="https://cloud.google.com/bigquery/docs/query-insights">BigQuery</a> (finally!) both let us analyze query performance intuitively. This way we can identify where our query falls short (e.g. exploding joins, suboptimal partitions, concurrency issues, so on and so forth). Hopefully, these will also be accessible outside their GUI in the future.</li><li><strong>Sturdy barriers</strong>. We can set up a <a href="https://docs.snowflake.com/en/user-guide/resource-monitors.html">dogwatch</a> on our resources, and BigQuery’s on-demand pricing has a CPU time/data read ratio threshold to keep them profitable. This unconsciously forces us to optimize.</li></ul><h4>What can you do?</h4><p>If you abide to these laws, you can scale better as a team and have a better ROI to “recover” the sunk costs.</p><blockquote>Btw, Our CTO, Andras has already written a handy <a href="https://hiflylabs.com/2022/12/01/using-dbt-with-snowflake-optimization-tips-tricks-part-2/">article</a> about cutting costs in Snowflake.</blockquote><ul><li><strong>Appreciate all</strong> the great things vendors made available to us. Use <a href="https://medium.com/teads-engineering/bigquery-ingestion-time-partitioning-and-partition-copy-with-dbt-cc8a00f373e3">partitioning</a> and clustering to facilitate partition pruning. Use well what makes this space modern (e.g. ZCC, table clones, external tables, incremental loading, etc.)</li><li><strong>Don’t overdo</strong> partitioning and clustering! Partition on small and very large blocks doesn’t make any sense. Clustering is costly, but works well if you frequently hit the key in the BI tool.</li><li><strong>Combine well.</strong> Partitioning and clustering work well together, scan less data per query, and pruning is determined before query start time, embrace them!</li><li><strong>Don’t overuse</strong> dbt tests. They are amazing, but test <a href="https://docs.getdbt.com/blog/grouping-data-tests?hss_channel=lcp-10893210">only what’s needed </a>and test it once (don’t do unnecessary tests again downstream if the logic does not change). Never lose track of tests with warning severity, otherwise, they are redundant.</li><li><strong>Understand how </strong>your warehouse costs are generated by starting with the underlying <a href="https://select.dev/posts/snowflake-architecture">architecture</a> and <a href="https://teej.ghost.io/understanding-the-snowflake-query-optimizer/">query optimizer</a>. The pricing models of Snowflake and BigQuery are different, although both offer flat rate pricing. The former bills on warehouse activity, while the latter on the data processed.</li><li>BigQuery does a good job balancing performance &amp; price. Storage is inexpensive, and computing feels more flexible. BigQuery excels when query traffic is low. Snowflake doesn’t employ the pay-per-query paradigm, and turning on and off virtual warehouses isn’t quite the same thing.</li><li><strong>Choose the right</strong> warehouse, warehouse suspend strategy, table type for your use case.</li><li>Keep auto suspend at 60s, it’s likely you don’t need more. <a href="https://select.dev/posts/configuring-snowflake-warehouse-sizes-in-dbt">Use a set of warehouse</a> configurations for differing workloads.</li><li><strong>Ask the right questions. </strong>Know the expectations and tolerance of your business stakeholders. Does it bother them if a job runs for a bit long, using a smaller warehouse on Snowflake to save X$? How frequently do you need to see certain data refreshed? Does it make sense to build X times per day? Sometimes less is more.</li><li><strong>Evaluate alternatives.</strong> There is fierce competition in this space, and it might be the case that you can find something more suitable for your use-case and <a href="https://medium.com/@datajuls/why-i-moved-my-dbt-workloads-to-github-and-saved-over-65-000-759b37486001">save fortunes</a>. They might need more maintenance (=time=money), but most of these products are now made under the notion of ‘plug and play’.</li><li><strong>Tread carefully</strong>. Today, we live in an attention economy, where product usage is likely driven by FOMO and companies are pouring money into their marketing. Trying out new products is always fun, but never lose sight of the gains and losses.</li></ul><p>Do we have to care more about optimization ourselves and do our research, or is it fair to expect better query optimization and these advanced tools to identify our bottlenecks?</p><p>Either way, my prediction for 2023 is that cloud costs are going to be a counterpoint topic when these vendors go head-to-head, and we are going to see more companies on focusing pushing down the monthly bill.</p><h4><strong>Shameless plug </strong>🔌</h4><p>If cost optimization is a concern for your company, don’t miss our next Snowflake webinar!</p><p>On the 8th of February 2023, <a href="https://www.linkedin.com/in/ACoAAAFE5ioBCiRBGtMsWmANM0Vas5wBEdPpXjM?lipi=urn%3Ali%3Apage%3Ad_flagship3_feed%3B175x8KsyS5egStDD8KwT4Q%3D%3D">Andras Zimmer</a>, Head of Analytics Engineering at Hiflylabs is going to walk you through multiple real-life applicable tips &amp; tricks that can help your Snowflake costs plummet.</p><p>Book your seat <a href="https://us02web.zoom.us/webinar/register/WN_ySTuPCsFR-6UBqLLdiKerw">here</a>!</p><h4>Finally, a list of great resources:</h4><ul><li><a href="https://select.dev/posts/cost-per-query">https://select.dev/posts/cost-per-query</a></li><li><a href="https://select.dev/posts/introduction-to-snowflake-clustering">https://select.dev/posts/introduction-to-snowflake-clustering</a></li><li><a href="https://cloud.google.com/bigquery/docs/partitioned-tables">https://cloud.google.com/bigquery/docs/partitioned-tables</a></li><li><a href="https://hiflylabs.com/2022/12/01/using-dbt-with-snowflake-optimization-tips-tricks-part-2/">https://hiflylabs.com/2022/12/01/using-dbt-with-snowflake-optimization-tips-tricks-part-2/</a></li><li><a href="https://teej.ghost.io/understanding-the-snowflake-query-optimizer/">https://teej.ghost.io/understanding-the-snowflake-query-optimizer/</a></li><li><a href="https://teej.ghost.io/understanding-the-snowflake-query-profile/">https://teej.ghost.io/understanding-the-snowflake-q</a></li><li><a href="https://www.thoughtspot.com/blog/cloud-cost-optimization-4-steps-to-reduce-cloud-costs">https://www.thoughtspot.com/blog/cloud-cost-optimization-4-steps-to-reduce-cloud-costs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807433407cb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/the-zen-of-avoiding-the-cloud-cost-fallacy-807433407cb2">The Zen of Avoiding the Cloud Cost Fallacy</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gee, stop building into production!]]></title>
            <link>https://medium.com/hiflylabs/gee-stop-building-into-production-a91d9a61551a?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91d9a61551a</guid>
            <category><![CDATA[data-contract]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 11:51:13 GMT</pubDate>
            <atom:updated>2023-02-03T10:06:56.213Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I Learned to Stop Worrying and Love the Deployment</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXpM8o49P6kSnugDycbn-A.png" /><figcaption>“Deterrence is the art of producing, in the mind of the enemy… the fear to attack!” — Dr. Strangelove (1964)</figcaption></figure><h3>🌀Why all the fuss?</h3><p>Time and time again, we stumble upon issues not entirely dependent on us, such as missing source data provided by a third-party supplier. This can be either due to <strong>server downtime</strong>,<strong> rebuilding tables</strong>,<strong> schema/object name</strong> <strong>changes</strong>, <strong>missing access rights</strong> or <strong>expired access tokens </strong>given to the service accounts or the analytics team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcVFxjjOfnewpyaUvdk0JA.png" /><figcaption>So data is not trustworthy after all?</figcaption></figure><p>When this happens, it’s a <a href="https://en.wikipedia.org/wiki/Doomsday_device"><strong>doomsday machine</strong></a> because it’s either <a href="https://towardsdatascience.com/data-quality-garbage-in-garbage-out-df727030c5eb"><strong>garbage in, garbage out</strong></a>, or entire deployments are halted due to missing object references or test failures. Before we get into the specifics of production gatekeepers and source data replication, let’s go over how we got here.</p><ul><li>Benn recently <a href="https://benn.substack.com/p/data-contracts">wrote about</a> how data contracts can prevent us from <em>“serving bad food from the kitchen”</em> with a simple technical (within stack) solutions designed for data teams.</li><li>David, advocate of data quality, <a href="https://davidsj.substack.com/p/yet-another-post-on-data-contracts?utm_source=profile&amp;utm_medium=reader2">described</a> an optimal data contract and highlighted important points about the means of communication between parties.</li><li>Tristan wrote briefly about <a href="https://roundup.getdbt.com/p/contracts-have-consequences?r=125hnz&amp;utm_medium=ios&amp;utm_campaign=post">his concerns</a> on the responsibility side when the contracts are made.</li></ul><p>By no means, I’m an expert in this topic, but if I had to define the term, I would say that it’s the <em>means needed to bridge the gap between data providers and the data team</em>. Schemas?! Contracts can also be associated with the emerging trend of <a href="https://blog.rittmananalytics.com/the-dbt-semantic-layer-data-orchestration-and-the-modern-enterprise-data-stack-78d9d9ed5c18"><strong>semantic layer</strong></a>, which would allow us to <strong>robustly scale our codebase and centralize business metric definitions</strong>. Put simply, elements needed to avoid <strong>communication failure </strong>and to be on the same page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sl3x8dzxJQIhjFabeuI8gQ.png" /><figcaption>Gee, I wish we had one of them doomsday machines! — Gen. Buck</figcaption></figure><p>In terms of responsibility, <strong>who’s to blame?</strong> The committee, or the one who launches the doomsday machine? (And even if we find who to blame, the deployment is blown — and users are mad at us…)</p><p>My take on data contracts (agreeing with David) is that it was considered normal for a data engineer to fix a broken pipeline. Information can flow through organizations very slowly, especially <strong>when priorities do not align</strong> between the data provider and the analytics team. When that happens, we usually implement a <a href="https://twitter.com/changelog/status/1586882941963091969">“<strong>custom fix”</strong></a><strong> to amend the issue temporarily</strong> and move on with our life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL6_b7eCFMvyi4cW-rbnYQ.png" /><figcaption>Usually what happens when we took our eyes off the backlog for a moment.</figcaption></figure><p>This is completely fine <strong>if we are a fast-paced team</strong>, and we know that fixing the issue takes time. On the flip side, it <strong>hurts the core logic of our data model</strong> by introducing custom (oftentimes not well documented) logic — to be refactored in the future, slowing down future processes.</p><p>For myself, I like tackling the tech debt, but it’s hard to convince management that it is worth the investment…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ugt5qqywlpEpVJb2DJDY1w.png" /><figcaption>source: <a href="https://medium.com/u/ff6469251a0b">Vincent Déniel</a></figcaption></figure><p>So what can we do? In the last year, we have seen/developed many creative ways to overcome external dependencies and protect our production data on Snowflake and BigQuery from being infected with bad data.</p><h3>❄️ Snowflake</h3><h4>🟦🟩 Blue/Green Swapping</h4><p>This is probably the <em>de-facto</em> way for Snowlake and dbt users to deploy to production. Tldr: Blue just becomes green behind the scenes, but nothing about your queries would have to change. I don’t feel like elaborating much on this topic, as <a href="https://discourse.getdbt.com/t/performing-a-blue-green-deploy-of-your-dbt-project-on-snowflake/1349">the community</a> and <a href="https://blog.montrealanalytics.com/blue-green-deployment-with-dbt-and-snowflake-922f1c658011">folks from Montreal Analytics</a> have already discussed this profoundly:</p><p>⚠️ <strong>Limitations:</strong></p><p>As former productiontables get demoted to stagingvia the <a href="https://stephenallwright.com/snowflake-swap-table/">swap</a> feature, the next incremental load will build on top of obsolete tables in staging before swapping.</p><p><em>Let me break it down to you:</em></p><ol><li><strong>T:</strong> Imagine that our run fully refreshes the data in staging, then swaps it with the production database in <strong>T-1</strong></li><li><strong>T+1:</strong> A new production cycle is due, but only certain data sources have to be processed again, so you decide to go with an incremental refresh.</li><li><strong>T+1:</strong> You then wonder why all the information we updated in <strong>T</strong> is missing?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*O60_3I04xf-VAf0qUL2yMw.png" /><figcaption>How blue/green fails incremental build</figcaption></figure><p>Well, since we built on top of a production data in <strong>T-1 </strong>before swapping again, the information loss is the difference between staging and production in <strong>T</strong>!</p><h4>🧻 Production Rollbacks</h4><p>Sean has described <a href="https://discourse.getdbt.com/t/production-rollbacks/2513?u=sung">another alternative</a> for detecting bad data and restoring the previous version, which then later was <a href="https://www.loom.com/share/bcfd2cf3b4b5471683bfc5b24587db3d">demo-ed by Sun</a>g. Instead of swapping databases, (1) we copy the previous production data to a staging environment, (2) rebuild the tables under scope, then (3) clone it back to production.</p><p>This <strong>also works with incremental models,</strong> because we always clone back the latest production loading before building on top of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*3rmAhe3tHzClRz30T5eq5Q.png" /><figcaption>Production rollback example</figcaption></figure><h3>🔍 BigQuery</h3><p>Unfortunately, <strong>swapping is not possible</strong> (or cumbersome) on BigQuery, so the idea is to run &amp; test all models before loading it to the production environment instead. BigQuery is not able to rename datasets, therefore, <strong>swapping by renaming with subsequent commits is ruled out</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI0Ir-VxWcJWBxkfL4PU4g.png" /><figcaption>Sometimes we all miss Snowflake a bit (source: dbt slack)</figcaption></figure><h4>WAP</h4><p><a href="https://www.linkedin.com/in/clausherther/">Claus</a> has proposed a way a while ago to overcome these limitations. His solution is called <a href="https://calogica.com/assets/wap_dbt_bigquery.pdf">WAP</a> (Write-Audit-Publish).</p><ol><li>Builds all in an audit staging dataset</li><li><strong>Re-build only top level</strong> models under the activation (BI) layer in prod again (testing is optional here).</li><li>Traffic is stopped if the build failed in the audit environment.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*i5ig4efTWXE5QGvTqjgWLg.png" /><figcaption>Write-Audit-Publish by Catalogica</figcaption></figure><h4>WAC</h4><p>Since BigQuery <a href="https://cloud.google.com/bigquery/docs/release-notes#February_15_2022">announced</a> their Table Cloning feature this year, <a href="https://hiflylabs.com/">we</a> came up with an extended strategy called WAC (<strong>Write-Audit-Clone</strong>) — coined by Hiflylabs.</p><p>Instead of rebuilding with an additional cost, let’s <strong>clone the top-level tables</strong> with the mart tag from stagingto production !</p><p>Note that the prerequisite of cloning top-level tables is that you have a<strong> </strong><a href="https://www.getdbt.com/analytics-engineering/modular-data-modeling-technique/"><strong>well-layered project</strong></a> either with tags or clear-cut folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*mJW2pi8C1byxanK6ARxk9A.png" /><figcaption>Write-Audit-Clone by Hiflylabs</figcaption></figure><p>The full-blown macro below is able to implement this logic by following the steps below.</p><ol><li>Collecting top level tables ( mart ,utils ) by<strong> querying the </strong><a href="https://docs.getdbt.com/reference/dbt-jinja-functions/graph"><strong>graph context variable</strong></a> for <a href="https://docs.getdbt.com/reference/resource-configs/tags">tags</a> (you can also use relative paths).</li><li>Since sets are not supported in Jinja, we need either create a custom macro for finding any intersections between our chosen tags and tags compiled from the manifest.jsonor check element by element.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rJL7BIjx4KaiJbZr7vGAA.png" /><figcaption>Gee, hidden Dr. Strangelove quote, Josh?</figcaption></figure><p>3. Finally, we create or replace filtered tables (we can’t clone views!) in mart, utilsby cloning analytics_staging.</p><p>Note that there is a custom logic here. First, the macro was written in a way, so it is able to copy between different dataset (=schema) structures.</p><p>This has been tested and implemented on projects with <a href="https://docs.getdbt.com/docs/building-a-dbt-project/building-models/using-custom-schemas#an-alternative-pattern-for-generating-schema-names">advanced custom schema</a> strategies like generate_schema_name_for_env.</p><p><em>If you are using similar building in staging and production with the same custom schemas, feel free to reduce this code to a couple of lines!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbcbc8f44c272fd82b6ce855cc133e5e/href">https://medium.com/media/dbcbc8f44c272fd82b6ce855cc133e5e/href</a></iframe><p>Include list of tags to clone in project.yml</p><pre>vars:<br>  tags_to_clone: [&#39;mart&#39;, &#39;utils&#39;]</pre><p>Then you set the target.name to stagingand call the macro at the end of your production build.</p><pre>#build it in analytics_staging<br>dbt seed<br>dbt snapshot<br>dbt build</pre><pre>#copy marts and utils layer to production<br>dbt run-operation write_audit_publish</pre><p>Voilà, you have a robust, nearly <em>zero-additional-cost</em> way to deploy safely to production!</p><p>⚠️ <strong>Limitations:</strong></p><ul><li><strong>We can’t copy views </strong>(not usually the case for objects powering the BI layer)</li><li>Additional storage (negligible) cost incurred on the difference between clones and source tables</li><li>More on cloning limitations <a href="https://cloud.google.com/bigquery/docs/table-clones-intro#limitations">here</a></li></ul><h3>G2K: 🪞Mirror layer</h3><p>What if we just add another layer to our project that copies the source tables? That means that we are <strong>acting as pseudo data providers</strong>!</p><p>Structurally, the project would be extended with a raw layer just before staging which copies the source tables 1:1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*F5HSaIbQuoyp2FCklT0_vQ.png" /><figcaption>An additional layer bringing through the source data as it is.</figcaption></figure><p>In very simple terms, each model would just include a select * from the source and materialize it as a table.</p><pre>with source as (</pre><pre>    select * from {{ source(&#39;name&#39;, &#39;table&#39;) }}</pre><pre>),</pre><p>This layer then would be separated from the dev/production main build job and <strong>refreshed manually when needed</strong>. Yes, it doesn’t sound right, and oftentimes are not worthy to implement in cases where the data arrives in micro-batches or through streaming.</p><p>A <em>source data refresh job</em> would only build (and test) the source data again:</p><pre>#assuming that you have project tags<br>dbt build -s tag:raw</pre><p>The <em>production job</em> then would build from the staging layer.</p><pre>#build it from staging<br>dbt build -s tag:staging+</pre><p>⚠️ <strong>Limitations:</strong></p><ul><li>Reprocessing one additional layer without any change in data → <strong>Additional processing and storage costs</strong></li><li>Manual refreshing of source data → loss of automatically provisioned data</li><li>Can only be used on projects where the <strong>data is “slowly changing”</strong></li></ul><h3>💡 Why should you care?</h3><p>Because, w<a href="https://hiflylabs.com/">e</a> always find ways to make the dbt experience as smooth as possible.</p><p>Using WAC in production is not a mere concept, it was well tested, implemented by our team of analytics engineers and to this day, possibly the closest to blue/green deployment for BigQuery users, as it has <strong>no additional storage and compute costs on top of building your production data </strong>(*insert Snowflake swapping appreciation*).</p><p>Do share your experience with WAC, and don’t hesitate to hit us up if you have any questions! 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91d9a61551a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/gee-stop-building-into-production-a91d9a61551a">Gee, stop building into production!</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Pandemic Shaped Conspiracy Theories on Reddit?]]></title>
            <link>https://medium.com/codex/how-the-pandemic-changed-conspiracy-theories-on-reddit-7739209de425?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/7739209de425</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[conspiracy-theories]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[reddit]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Sat, 07 May 2022 21:49:21 GMT</pubDate>
            <atom:updated>2022-05-08T01:44:26.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9i-QX334ctvCdAgNk1mzQ.jpeg" /><figcaption>Credit: <a href="https://unsplash.com/@tomradetzki">Tom Radetzki</a></figcaption></figure><p>Sentiment and topic analysis of r/conspiracy</p><p><em>Codes are available in R and Python </em><a href="https://github.com/nszoni/reddit_conspiracy_theories"><em>here</em></a></p><h3>Hypothesis</h3><p>Since the breakout of the pandemic, conspiracy theories have resurfaced and misinformation/fakenews are booming. To confirm that hypothesis, my idea was to use the extensive tools of NLP and compare the posts in the r/conspiracy subreddit before and after COVID.</p><p>I expected to see a stronger negative sentiments as well as a shift towards topic connected to society, gender, race, rights, and social media.</p><h3>Data Collection</h3><h4>Scraping the Reddit API</h4><p>The traditional way of scraping Reddit is to use the API with the <a href="https://praw.readthedocs.io/en/stable/">PRAW</a> wrapper. However, the API is limited to 1000 requests per hour and is not able to scrape historical data defined by a window. This is not enough for our purpose while our data would be highly unbalanced and unrepresentative.</p><h4>Overcoming limitations with Pushift API</h4><p>Luckily there is a service which allows us to scrape historical data from Reddit. The service is called <a href="https://github.com/pushshift/api">Pushift API</a>. Briefly, it let’s you control the scraping window. The python wrapper of the API is called <a href="https://psaw.readthedocs.io/en/latest/">PSAW</a>, but there is also a multi-threaded version called <a href="https://github.com/mattpodolak/pmaw">PMAW</a> which is more efficient in high volumes close to hundreds of thousands of records.</p><h4>Scraping process</h4><p>I have used a methodology which blends together the usage of the classical PRAW and PSAW. With PSAW, we only get unique identifiers of submissions from the API bounded by time, which then I feeded into PRAW’s submission endpoint. This way, we can get more features offered by PRAW, but overcome its limitation of scraping historical data.</p><h3>Data Ingestion</h3><p>I have scraped 2500 submissions between 2018 and 2019 for the analysis of conspiracy theories and subreddit activity. For comparison, I also got the same amout of data between 2021 and 2022 which should be a decent baseline for proxying the aftermath of the global pandemic.</p><h3>Data Cleaning</h3><h4>Feature generation</h4><p>On Reddit, we you may have seen posts with deleted or removed content either because of the violation of user terms (let’s face it happens often in similar forums) or the author itself decided to delete them. This introduces many records which are not usable for the analysis.</p><p>I have decided to glue together the titles and bodies of each post. The limitation of this maneuver is that there are cases where the titles are just the first line of the body text, thus we would end up in information duplication.</p><pre># replace pattern delete and removed<br># with missing<br>rc &lt;- rc |&gt;<br>    mutate(body = gsub(&quot;\\[deleted\\]|\\[removed\\]&quot;,&quot;&quot;, body))<br><br># glue together titles and bodies<br>rc$text &lt;- paste(rc$title, rc$body, sep = &quot; &quot;)</pre><h3>Text Preprocessing</h3><h4>Extend stopwords corpus</h4><p>The tidytext stopwords corpus is much more extensive than let’s say the nltk stopword corpus in Python (thanks to the multiple of lexicons it uses).</p><p>However, I have still arbitrarily extended the corpus with words which does not add to the meaning of the text, but I expect to come up very often based on my experience with nltk.</p><pre># collect stopwords<br>data(stop_words)</pre><pre>extension &lt;- c(&quot;use&quot;, &quot;people&quot;, &quot;person&quot;,<br>    &quot;like&quot;, &quot;think&quot;, &quot;know&quot;, &quot;case&quot;, &quot;want&quot;,<br>    &quot;mean&quot;, &quot;one&quot;, &quot;many&quot;, &quot;well&quot;, &quot;two&quot;,<br>    &quot;say&quot;, &quot;would&quot;, &quot;make&quot;, &quot;get&quot;, &quot;go&quot;,<br>    &quot;thing&quot;, &quot;much&quot;, &quot;time&quot;, &quot;even&quot;, &quot;new&quot;,<br>    &quot;also&quot;, &quot;could&quot;)<br><br># create dataframe for extensions<br>extension_df &lt;- data.frame(word = extension, lexicon = rep(&quot;custom&quot;, length(extension))) </pre><pre># union<br>stop_words &lt;- rbind(stop_words, extension_df)</pre><p>I have created a text processer function which</p><ul><li>Cleans the text from noises (e.g. username handlers, hyperlinks, non-alphabetic elements, whitespaces, etc.)</li><li>Tokenizes the text</li><li>Removes stopwords</li><li>Lemmatizes the generated tokens</li><li>Filters out all the words which have less than three characters.</li></ul><pre>text_preprocesser &lt;- function(text) {<br><br>    # lowercase text<br>    text &lt;- tolower(text)<br><br>    # remove junk<br>    pattern &lt;- &quot;@[^\\s]+|http\\S+|\\W|\\s+[a-zA-Z]\\s+|\\d+|\\s+&quot;<br>    text &lt;- gsub(pattern, &quot; &quot;, text)<br><br>    # split to tokens<br>    tokens &lt;- unlist(strsplit(text, &quot;\\s+&quot;))<br><br>    # filter out stopwords<br>    tokens &lt;- tokens[!(tokens %in% stop_words$word)]<br><br>    # lemmatize tokens<br>    tokens &lt;- lemmatize_words(tokens)<br><br>    # filter out tokens with less than 3 characters<br>    tokens &lt;- tokens[length(tokens) &gt;= 3]<br><br>    # join words back together<br>    preprocessed_text &lt;- paste(tokens, collapse = &quot; &quot;)<br><br>    return(preprocessed_text)<br><br>}</pre><p>Applying the text preprocesser, we can see that it did a good job in overall as we managed to filter out stopwords and introduce standardized corpus of lemmatized words. Notice that by removing <em>in</em> from the first post, interpretations can change a lot.</p><pre>rc$cleaned &lt;- lapply(rc$text, text_preprocesser)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lveS39W_NLIySbztquP5_w.png" /><figcaption>Preprocessed Reddit data</figcaption></figure><h4>Extract emojis</h4><p>When analyzing social media data, we cannot skip past the fact that there is a trend towards people expressing themselves through emojis and it slowly replaces the means of communication through actual words.</p><p>My intention here was to prepare the dataset for analyzing the commonly used emojis across multiple segments (period or sentiment), therefore I have collected all the emojis a submission to a list and added a counter for each using the <a href="https://github.com/hadley/emo">emo package</a>.</p><pre>rc &lt;- rc |&gt;<br>    mutate(emoji = emo::ji_extract_all(text))<br><br>rc$emoji_count &lt;- sapply(rc$emoji, length)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpvcnvwgijjBdQ2_bewh1w.png" /></figure><h4>TF-IDF</h4><p>To see what key terms drive each submission by fitting a tf-idf model to the cleaned text.</p><blockquote>The idea of tf-idf is to find the important words for the content of each document by decreasing the weight for commonly used words and increasing the weight for words that are not used very much in a collection or corpus of documents</blockquote><p><em>Here’s a snippet for that:</em></p><pre>rc_tfidf &lt;- rc |&gt;<br>    unnest_tokens(word, cleaned) |&gt;<br>    count(label, word, sort = TRUE) |&gt;<br>    ungroup()<br><br>total_words &lt;- rc_tfidf |&gt;<br>    group_by(label) |&gt;<br>    summarize(total = sum(n))<br><br>rc_tfidf &lt;- left_join(rc_tfidf, total_words)</pre><pre>rc_tfidf &lt;- rc_tfidf |&gt;<br>    bind_tf_idf(word, label, n)<br><br>tfidf &lt;- rc_tfidf |&gt;<br>    arrange(desc(tf_idf)) |&gt;<br>    mutate(word = factor(word, levels = rev(unique(word)))) |&gt;<br>    group_by(label) |&gt;<br>    top_n(10) |&gt;<br>    ungroup() |&gt;<br>    ggplot(aes(word, tf_idf, fill = label)) +<br>    geom_col(show.legend = FALSE) + labs(x = NULL,<br>    y = &quot;tf-idf&quot;) + facet_wrap(~label, scales = &quot;free&quot;) +<br>    coord_flip()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwdIncLYvtrXHvfOgZf5EQ.png" /><figcaption>High tf-idf words</figcaption></figure><p>It seems that keywords connected to the Kevin Spacey scandal and political conflict (Chinese protest) were the most relevant words of submissions before COVID. After the pandemic, keywords of the vaccination has greatly emerged as the drivers of controversies.</p><h4>Sentiment Analysis</h4><p>To rank each word by the total sentiment contribute, I have used the AFINN lexicon, and summed up all the scores per label to get the total contribution of a word.</p><blockquote>The AFINN lexicon is a list of English terms manually rated for valence with an integer between -5 (negative) and +5 (positive) by Finn Årup Nielsen between 2009 and 2011.</blockquote><p>The below graph suggests that there is a considerable amount of overlap between positive and negative terms pre- and post-COVID.</p><p>If I had to pick out certain words which differ, they would be <em>abuse</em> because of all the sexual misconducts before the pandemic and <em>ban, pay</em> and <em>crisis</em> because of the follow-up economic decline after the pandemic and all words related to the sanctions towards Russia.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCmtGniC7IzRxyo81aTSxA.png" /><figcaption>Sentiment contribution (AFINN)</figcaption></figure><h4>Sentiment Categories</h4><p>We can also leverage other sentiment lexicons, such as NRC, which is great for identifying sentiment categories.</p><blockquote>The NRC Emotion Lexicon is a list of English words and their associations with eight basic emotions (anger, fear, anticipation, trust, surprise, sadness, joy, and disgust) and two sentiments (negative and positive). The annotations were manually done by crowdsourcing.</blockquote><p>We can see that the ranking between categories didn’t change much, except for there is relatively more words connected to <em>trust</em>. This is mildly connected to the amplified uncertainty after the vaccination myths, where people are questioning theories and fake news are here to stay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9KyevQaA9kwBOdUxXF_tg.png" /></figure><h4>Emoji Analysis</h4><p>Using the list of emojis collected in the text processing section, we can see how the most frequently used emojis have changed over time.</p><p>We can see that the top 2 emojis did not change, but there are more negative emojis in after COVID (e.g. skull, clown, suspicious eyes). National flags appear in both terms, from which the Albanian allegedly (had to Google myself) represents Dua Lipa’s tweet backing Albanian nationalism. The Ukrainian flag is there because of the war initiated by Russian aggressors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABBWJOgqCS24kZd5GZf8KQ.png" /><figcaption>Top emojis</figcaption></figure><h4>Wordclouds</h4><p>If we check the words associated with sentiments via the bing lexicon, we can see the most common ones in the word clouds below. Conspiracy is still the most used negative word, while Trump is the top positive.</p><blockquote>The bing lexicon categorizes words in a binary fashion into positive and negative categories.</blockquote><p>If we look closely at the words which are not overwhelming the rest, we can see that the difference is shifting from abuse, mysterious aliens, impeachment and prison (associated with Harvey Weinstein, UFO findings, Trump, and Jeffrey Epstein, respectively) to virus, bomb, and crisis. As far as positive shift is concerned, there is much less specificity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MSYfP4Te2r4KIK4dwTDf-Q.png" /></figure><h4>Bigram Analysis</h4><p>Extending the analysis to multiple words can be a good idea. Thus, I did a tf-idf analysis on bigrams within each submission. Tokens have been strongly connected with Epstein (<em>die suicide, epstein die, manhattan jail</em>) and alien-related controversies (<em>strange creature, creature forest</em>) while in the post-COVID period, bigrams are more dispersed in terms of topics ranging from vaccination through gender (<em>conceptual penis</em>) to cases of sexism (<em>amp amp</em>).</p><pre>rc_bigrams &lt;- rc |&gt;<br>    unnest_tokens(bigram, cleaned, token = &quot;ngrams&quot;,<br>        n = 2)<br><br>rc_bigrams_tfidf &lt;- rc_bigrams |&gt;<br>    count(label, bigram) |&gt;<br>    bind_tf_idf(bigram, label, n)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3fneOt1vaUz3ng69Y2wmQ.png" /><figcaption>Bigram analysis</figcaption></figure><p>We can even chain together elements of bigrams to see a network of words often mentioned together, creating a whole story. The largest web is around the topics discussing the existence of aliens (bottom-left corner), the Chinese protesters on the Tienanmen square, and the Epstein scandal. These are all from the pre-COVID period, while after the pandemic, there’s been fewer number of persistent stories.</p><p><em>Snippet:</em></p><pre>bigrams_separated &lt;- rc_bigrams |&gt;<br>    separate(bigram, c(&quot;word1&quot;, &quot;word2&quot;),<br>        sep = &quot; &quot;)<br><br># new bigram counts:<br>bigram_counts &lt;- bigrams_separated |&gt;<br>    count(word1, word2, sort = TRUE)<br><br>bigram_graph &lt;- bigram_counts |&gt;<br>    select(from = word1, to = word2, n = n) |&gt;<br>    filter(n &gt; 20) |&gt;<br>    graph_from_data_frame()<br><br>a &lt;- grid::arrow(type = &quot;closed&quot;, length = unit(0.15,<br>    &quot;inches&quot;))<br><br>ggraph(bigram_graph, layout = &quot;fr&quot;) + geom_edge_link(aes(edge_alpha = n),<br>    show.legend = FALSE, arrow = a, end_cap = circle(0.07,<br>        &quot;inches&quot;)) + geom_node_point(color = &quot;lightblue&quot;,<br>    size = 5) + geom_node_text(aes(label = name),<br>    vjust = 1, hjust = 1) + labs(title = &quot;Network of bigrams&quot;,<br>    subtitle = &quot;Long lineage about Epstein, the aliens, and protests&quot;) +<br>    theme_graph()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gMSE-82d7DYp2klJHwBn3A.png" /></figure><h4>Topic Modelling (LDA)</h4><p>Lastly, I wanted to identify topics of discussion before and after the pandemic using Latent Dirichlet Allocation (LDA).</p><blockquote>LDA, short for Latent Dirichlet Allocation is a technique used for topic modelling. Latent means hidden, something that is yet to be found. Dirichlet indicates that the model assumes that the topics in the documents and the words in those topics follow a Dirichlet distribution. Allocation means to giving something, which in this case are topics. LDA assumes that the documents are generated using a statistical generative process, such that each document is a mixture of topics, and each topics are a mixture of words.</blockquote><h4>Pre-COVID</h4><p>We can see that the topics are ranging from aliens to politics connected with Trump. There are a few topics I can label with mydomain knowledge.</p><ul><li>Topic 1: <a href="https://www.bbc.com/news/world-us-canada-48913377">The Epstein case</a></li><li>Topic 4: <a href="https://eu.usatoday.com/story/tech/2019/06/11/bizarre-creature-caught-on-security-camera-viral-video/1411177001/">Alien and UFO discoveries</a></li><li>Topic 6: <a href="https://www.technologyreview.com/2018/12/19/138307/how-google-took-on-china-and-lost/">Google vs. China</a></li><li>Topic 7: Social media censorship</li><li>Topic 8: <a href="https://en.wikipedia.org/wiki/First_impeachment_of_Donald_Trump">Trump’s impeachment</a></li><li>Topic 10: Religion and ethnicity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rccKIuDRnY_wmH3WWHMNig.png" /></figure><h4>Post-COVID</h4><p>After the pandemic, topics are now ranging from the Ukrainian war through vaccination to social sciences and gender. Other topics are not coherent enough to identify any labels. To name a few topics present here:</p><ul><li>Topic 1: <a href="https://en.wikipedia.org/wiki/Richard_Snell_(criminal)">Richard Wayne Snell</a> and <a href="https://en.wikipedia.org/wiki/Timothy_McVeigh">Timothy McVeigh</a> white supremacists and murderers</li><li>Topic 5: COVID related restrictions and politics (CDC, Canada truck protest)</li><li>Topic 6: US politics</li><li>Topic 7: Russian and Ukrainian conflict and a potential nuclear war</li><li>Topic 17: JFK’s assassination</li><li>Topic 19: Vaccination</li><li>Topic 13: Social sciences and gender</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*l4fT5IhNmUv4eo2ALx1Q9g.png" /></figure><h4>Conclusion</h4><p>For what is worth, I think we learnt a bunch of new things here and ultimately, my hypothesis held firmly.</p><p>Since the pandemic, there is an amplified uncertainty within the community. The relative frequency of words classified in the trust sentiment has increased as well as more and more emojis connected to doubt and negative words have emerged. Topics in the post-COVID period have been less consistent than in the pre-pandemic phase. Many discussions are now about the social science, gender, religion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7739209de425" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-the-pandemic-changed-conspiracy-theories-on-reddit-7739209de425">How the Pandemic Shaped Conspiracy Theories on Reddit?</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Environment-dependent Unit Testing in dbt]]></title>
            <link>https://medium.com/hiflylabs/environment-dependent-unit-testing-in-dbt-c081a0a5ff1e?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/c081a0a5ff1e</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[modern-data-stack]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 19:27:15 GMT</pubDate>
            <atom:updated>2022-06-20T13:03:22.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oy6-Ti0E-YfqVXlIn2IreQ.jpeg" /><figcaption>Source: Markus Winkler (Unsplash)</figcaption></figure><p><em>See the original version </em><a href="https://blog.hiflylabs.hu/en/2022/02/10/environment-dependent-unit-testing-in-dbt/"><em>here</em></a><em> on Hiflylabs’s blog.</em></p><p>I’ve been using dbt for a while now and I feel that most developer needs are covered with community-developed test suite packages like <a href="https://github.com/dbt-labs/dbt-utils#schema-tests">dbt_utils</a>, <a href="https://github.com/calogica/dbt-expectations">dbt-expectations,</a> or custom generic tests defined via the mix of Jinja and SQL.</p><p>However, <strong>growing business and data requirements demand an automated way of validating our transformations locally.</strong> Cherry-picking observations and manually doing regular check-ups on the transformations can increase the technical debt exponentially, especially when the complex procedures leading to the desired outcome are not trivial to the naked eye.</p><p>Lately it has been our priority to find a way of <strong>unit testing our “black boxes”</strong>, and make comparisons between the expected output and the output our sets of models have produced with respect to a static input. This way, we can ensure that the business logic is accurately transformed into code.</p><p>There are multiple ways of doing this in dbt, but I found that <strong>existing solutions neither fully exhibit the end-to-end testing, nor achieve the flexibility to run our tests dependent on the development environment.</strong></p><p>So here’s my quick take on solutions suggested by the community:</p><ul><li><a href="https://discourse.getdbt.com/t/testing-with-fixed-data-set/564"><strong>Testing with fixed data set</strong></a> — Maybe one of the most helpful discussions about unit testing with the capability of defining environment-dependent unit tests, but <strong>doesn’t fully demo the workflow</strong>.</li><li><a href="https://www.startdataengineering.com/post/how-to-test-sql-using-dbt/"><strong>How to unit test SQL transforms in dbt</strong></a> — Also an excellent resource with an example of running equality checks <strong>misses the flexibility to reduce the test scope to particular columns.</strong></li><li><a href="https://github.com/mjirv/dbt-datamocktool"><strong>dbt-datamocktool</strong></a> — packaged version of unit testing where you can define tests in a more structured way without touching the models. Works well, but <strong>lacks the possibility of defining test-specific environments</strong>.</li></ul><p>In short, all of the current resources apply great approaches, but my company needed were the following two core features:</p><ol><li><strong>Separate unit-testing from other environments (avoids running in daily jobs)</strong></li><li><strong>Ability to restrict the target columns in test arguments</strong></li></ol><p>Without further ado, this is how we have built our unit testing environment!</p><h4><strong>Step 1. Create a unit-testing environment</strong></h4><p>This is the environment we will use when defining our tests specifically for validating the transformation logic. How you configure the profile.yml is entirely up to you, just make sure that you <strong>reference this target when testing</strong>. You may mirror the development profile or opt for materializing unit test models in their own schema.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d59eb071ddaa72e8617fa35350a461/href">https://medium.com/media/18d59eb071ddaa72e8617fa35350a461/href</a></iframe><h4><strong>Step 2. Add mock data to the project</strong></h4><p>Next, we can now add our input which passes through all the transformations as well as an expected output mock data validating the end-product to the data folder (assuming that our project uses the <a href="https://docs.getdbt.com/reference/seed-configs">default seed path</a>).</p><p>An efficient way of doing a unit test is to <strong>assemble a mock input that raises all the possible edge scenarios the model should be able to handle</strong>. In other words, we should be able to spot-check every component of the business logic.</p><p>What we usually do is <strong>pick out a certain entity (account, organization, user, etc.) and manipulate the input accordingly.</strong> This way the comparison will be faster and more concise, rather than just feeding the large chunk of the data. The latter scenario also prompts for a larger expected output calculation.</p><p>To keep everything organized, I created a <strong>unit_testing</strong> folder under the seed folder. This way we can easily identify which seed files are there for mock testing, and which are in the traditional dbt sense. This is useful, especially if you do a lot of unit testing during the development making the project a morass of spaghetti. So, for the sake of your fellow developers, keep things tidy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*fzJBSeQ3i1JoYZ_W" /><figcaption>Seed folder structure</figcaption></figure><h4><strong>Step 3. Seed mock data</strong></h4><p>Make sure you seed both the input and expected output CSVs to the warehouse, so it will be accessible for the pipeline logic picking up the mock input on the fly and comparing the output to validate your expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKVo2u3q-S5FFath" /><figcaption>dbt seed</figcaption></figure><h4><strong>Step 4. Create a reference to the mock input</strong></h4><p>Here we tell dbt that <strong>when we are executing a test in the unit testing environment, then instead of picking up the source we are using throughout the project, take the mock data as the input</strong>, otherwise, just proceed with the production staging data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2e5a51b321f3d3fbfc67dd9315087a/href">https://medium.com/media/ed2e5a51b321f3d3fbfc67dd9315087a/href</a></iframe><h4><strong>Step 5. Define your test criteria</strong></h4><p>Next, we have to define the test we are planning to execute on the mock output and the model outcome table. In our instance, we wanted to check whether we got the same for a certain input calculated by a spreadsheet tool and dbt. <a href="https://github.com/dbt-labs/dbt-utils#equality-source">dbt_utils has an equality check test </a>out-of-the-box but <strong>doesn’t let you switch between environments</strong>.</p><p>Therefore, we had to write a custom test which, in essence, <strong>extends the base equality test logic with the possibility of running it only in a given environment</strong>. It is very likely that someone has already thought of similar checks (in our case dbt Labs), but there are a couple of things you want to shuffle. As a result, it is worthwhile checking out the source code behind the open-source test suite packages which can be an excellent reference to build upon additional features.</p><p>We simply extracted the relevant components of the default equality test macro and added a conditional statement checking the context we are currently testing.</p><p><strong>It accomplishes the followings:</strong></p><ol><li><strong>Retrieves the comparison model reference and the specified environment</strong> in the test YAML block (See Step 6.)</li><li>If the <strong>context target name matches the environment</strong> for unit testing then<br><strong>a. </strong>Checks whether there are specific columns defined by the user to be tested. If not, it takes all columns from the schema and concatenates these columns to a variable used later in the select statement<br><strong>b.</strong> Then executes the comparison between the model output and the expected CSV using the defined columns in (a.).</li><li><strong>If the context name differs</strong> from the defined one, it returns 0, and the test passes</li></ol><p>We can store our custom tests as macros or generic tests as per the <a href="https://docs.getdbt.com/docs/guides/writing-custom-generic-tests">dbt documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f36aa4d0df134115ee4f565cf64be92e/href">https://medium.com/media/f36aa4d0df134115ee4f565cf64be92e/href</a></iframe><h4><strong>Step 6. Add custom test to YAML block</strong></h4><p>Finally, we can use the custom test in our YAML blocks as the sample below:</p><p>We must first <strong>specify our comparative data as well as the context in which the test will be carried out</strong>. We may further reduce the number of columns to check by providing additional arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c4f3d3f187064396bcd5b6dac0f47bb/href">https://medium.com/media/5c4f3d3f187064396bcd5b6dac0f47bb/href</a></iframe><p>Ideally, we would define unit tests in separate schema YAML files but unfortunately, dbt does not allow us to have multiple model definitions for schema tests.</p><h4><strong>Step 7. Build and Profit!</strong></h4><p>Now that we have everything set up to do systematic checks in local development, we can simply <strong>run a dbt build command with rerouting the target to the unit test profile.</strong></p><p>It will apply the transformation on the mock input dataset and expose that to the expected output. <strong>If your checks have, you might want to review the utilized logic, but better safe than sorry when pushing false data into production.</strong></p><p>(You might as well want to <a href="https://docs.getdbt.com/reference/resource-configs/store_failures">store test failures in an audit schema</a> to make debugging easier instead of copy-pasting the compiled test)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5XobI91QVkhPSSQj" /><figcaption>Add custom test to schema.yml</figcaption></figure><h4><strong>Final Remarks</strong></h4><p>In this walkthrough, I have shown you how to set up an environment for unit testing and gave you an example of how we make sure that the correct business value is delivered to our clients through equality checks. The main takeaways are:</p><ol><li>Unit tests can provide a <strong>regression framework to minimize the chance of breaking what does work.</strong></li><li><strong>You may find additional edge cases</strong> which were missed during the development work</li><li>It is a good practice <strong>to validate questionable “black box” components</strong> of the pipeline.</li><li>It is important to<strong> find the right balance of unit testing</strong> and focus robustness checks on models which effectively create business value, otherwise the project can blow up.</li><li>Having a separate environment for unit testing in dbt <strong>does not create overhead in production.</strong></li></ol><p>I hope that you enjoyed this blogpost and feel free to share your testing best practices with us! Also, let us know how you would improve our unit testing framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c081a0a5ff1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/environment-dependent-unit-testing-in-dbt-c081a0a5ff1e">Environment-dependent Unit Testing in dbt</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reddit Text Mining with AWS AI Services and R]]></title>
            <link>https://medium.com/codex/reddit-text-mining-with-aws-ai-services-and-r-6b055c10725d?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b055c10725d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[reddit]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Wed, 24 Nov 2021 18:46:39 GMT</pubDate>
            <atom:updated>2021-11-25T01:26:33.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*S_u0rYaSnlDI76iHOgZkZw.png" /></figure><h4>Understanding r/hungary</h4><h3>Introduction</h3><p>I’ve always been captivated by the Reddit community, and I frequently find myself looking for solutions and project ideas in the large number of channels, which Redditors refer to as subreddits.</p><p>I realize this blogpost’s title is a bit of a departure from my past entries, but there’s a purpose for it. After just recently discovering the <a href="https://aws.amazon.com/machine-learning/ai-services/">AI Services</a> offered by AWS as a part of my university course, I was assigned to come up with a use-case where these tools can be handy enough.</p><p>So, combining my fondness for a primarily text-based social media platform with my university duties, I finally decided to give it a shot and do an <strong>entry-level text analysis of the </strong><a href="https://www.reddit.com/r/hungary/"><strong>r/hungary</strong></a><strong> subreddit</strong>.</p><p><em>(Please note that by no means I’m experienced in NLP and this is only a small gig of mine.)</em></p><p>But why r/hungary, you might wonder? Why not <a href="https://www.reddit.com/r/wallstreetbets/">r/wallstreetbets</a> or any other internationally known subs? Since I’m based in Budapest, not only this community has pretty much replaced all the Hungarian mainstream media for me, but also been my go-to place after a long workday.</p><p>In this tutorial/analysis, I will show you how to get quick-fire analytics and insights from any subreddits of your choice. Also, I will benchmark how AWS Translate and Comprehend perform on slang-powered texts.</p><p><strong>Strap yourselves in!</strong></p><blockquote>All the artifacts, including the R script behind this blogpost can be found on my <a href="https://github.com/nszoni/reddit-sentiments-aws">Github repo</a></blockquote><h3>Requirements</h3><h4>R</h4><p>To reproduce the workflow, you need to install the following packages to your R environment.</p><ul><li><strong>Data Manipulation and Visualization:</strong> <a href="https://www.tidyverse.org/"><em>tidyverse</em></a><em>, </em><a href="https://www.rdocumentation.org/packages/stringr/versions/1.4.0"><em>stringr,</em></a><em> </em><a href="https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.html"><em>data.table</em></a></li><li><strong>Text Mining:</strong> <a href="https://cran.r-project.org/web/packages/tm/tm.pdf"><em>tm</em></a><em>, </em><a href="https://cran.r-project.org/web/packages/tidytext/vignettes/tidytext.html"><em>tidytext</em></a><em>, </em><a href="https://cran.r-project.org/web/packages/SnowballC/SnowballC.pdf"><em>SnowballC</em></a></li><li><strong>AWS AI from </strong><a href="https://github.com/orgs/cloudyr/repositories"><strong>CloudyR</strong></a><strong>: </strong><em>aws.translate, aws.comprehend</em></li><li><strong>Accessing Reddit:</strong> <a href="https://github.com/ivan-rivera/RedditExtractor"><em>RedditExtractoR</em></a></li></ul><blockquote><em>Tip: You can install and load these libraries, with repeating </em>install.packages() <em>and </em>library()<em> commands, or let </em><a href="https://www.rdocumentation.org/packages/pacman/versions/0.5.1">pacman</a><em> deal with the project dependencies in a tidy way.</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f2824c65fcb50b0a0cb8eb3c7e1c364/href">https://medium.com/media/9f2824c65fcb50b0a0cb8eb3c7e1c364/href</a></iframe><h4>AWS</h4><p>You also need to set up our AWS credentials to be able to access our cloud resources.</p><blockquote>Note, that the below steps are working under the assumption that you already have an IAM user, if not, <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html">here</a> you can find how to do so.</blockquote><ol><li>Open the IAM console at <a href="https://console.aws.amazon.com/iam/">https://console.aws.amazon.com/iam/</a>.</li><li>On the navigation menu, choose <strong>Users</strong>.</li><li>Choose your IAM username.</li><li>Open the <strong>Security credentials</strong> tab, and then choose <strong>Create access key</strong>.</li><li>To see the new access key, choose <strong>Show</strong>. Your credentials should resemble the following examples:</li></ol><ul><li>Access key ID: AKIAIOSFODNN7EXAMPLE</li><li>Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY</li></ul><p>To download the key pair, choose <strong>Download .csv file</strong>. Store the .csv file with keys in the same directory as your R script.</p><p>Finally, load your credentials into the R session (make sure that your *accessKeys.csv is in your working directory):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796dade43e7b779c8049d0da94d4fe30/href">https://medium.com/media/796dade43e7b779c8049d0da94d4fe30/href</a></iframe><h3>Subreddit Processing</h3><h4>Reddit API</h4><p>The next step is to scrape data from the public Reddit API. As a shortcut, I used <a href="https://github.com/ivan-rivera/RedditExtractor"><strong>RedditExtractoR</strong></a>, which is a minimalistic wrapper for making Reddit API calls in R. In short, the package can extract, user data, subreddit posts, and find URLs to threads based on keywords.</p><pre>#monthly top entries<br>hungary1 &lt;- find_thread_urls(subreddit=&quot;hungary&quot;, sort_by=&quot;top&quot;, period = &quot;month&quot;)</pre><p>Peeking into the response data frame, you should see something with the similar structure to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVdOZgjDtGwFzQAPf7p1KA.png" /><figcaption>Raw subredddit table</figcaption></figure><p>I can already make some preliminary remarks on the data before I jump into processing the data.</p><ol><li>Encoding is a bit off as <strong>Hungarian “Ő”s were not parsed correctly</strong>. This is a limitation of our API wrapper, and there is no clear-cut way to remedy that.</li><li>It would be reasonable to <strong>glue together the titles and their texts</strong>, to minimize the information loss when mapping text detectors algorithms to a single column of strings.</li><li>Subreddit and URL columns are redunndat to my analysis, so let’s just exclude them.</li><li><strong>Posts without body texts should be dropped</strong>, because of ambiguity, and oftentimes titles are not long enough to adhere to the requirements of our analysis.</li><li><strong>Posts having URL links</strong> inside their title/body can cause future problems when processing.</li><li><strong>Too long, or too short texts would make AWS AI Services bail out</strong> due to their character processing limits (max 5,000 characters per request).</li></ol><p>Having that in mind, the snippet below should treat all but the first of these issues:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29570c761f6f99499cc8bd810ce1dc8f/href">https://medium.com/media/29570c761f6f99499cc8bd810ce1dc8f/href</a></iframe><p><strong>I started with 1,000 observations and ended up with 172</strong> after narrowing down the dataset to fit our needs. This should be enough to present my use case and respect the budget of my university.</p><h4>Super-function for Processing</h4><p>Now, I can start detecting the key sentiments and phrases of this subreddit.</p><p>For that, I created a <strong>super-function that loops through the rows of my data frame</strong> post-by-post and follows these steps:</p><ol><li><strong>Detects its language and translate</strong> foreign posts to English via <em>AWS Translate</em></li><li><strong>Preprocesses the text</strong> via the <em>tm</em> package (i.e., removes numbers, punctuation, whitespace, capitals, stop words, etc.).</li><li><strong>Detects the sentiment</strong> of the processed texts and <strong>extracts the key phrases </strong>with the highest confidence scores via <em>AWS Comprehend</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc771e4e2c8edb65e988ecb695f02b7/href">https://medium.com/media/bcc771e4e2c8edb65e988ecb695f02b7/href</a></iframe><p>I have also equipped the function with some <a href="https://github.com/daroczig/logger">logging</a> for debugging purposes, then fed my filtered data into the super-function:</p><pre>&gt; hungary_processed_test &lt;- subreddit_processer(hungary5)<br>INFO [2021-11-21 12:20:22] Preprocessing post No. 1<br>INFO [2021-11-21 12:20:22] Translating...<br>INFO [2021-11-21 12:20:22] Detect sentiments...<br>INFO [2021-11-21 12:20:23] Detect keyphrases...<br>INFO [2021-11-21 12:20:23] Post No. 1 processed!<br>INFO [2021-11-21 12:20:23] Preprocessing post No. 2</pre><p>The whole process <strong>took about 2.2 minutes to complete</strong>, and now I have something much more digestible to do my analytics on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iyHq7gXN6368LXhR1P4CQ.png" /><figcaption>Processed table with sentiment and keyphrases</figcaption></figure><p>As you can see, the super-function <strong>did a great job in getting rid of stop words, and all sorts of grammatical objects</strong> which can cause issues in our further data munging. However, I have noticed <strong>inconsistencies in translating heavily informal Hungarian texts</strong> to English as in certain cases, translations weren’t comparable to the original texts or didn’t make sense at all. This is also partly due the encoding issues mentioned before.</p><h4>Keyphrases</h4><p>To improve our insights about the sentiment of the subreddit, I constructed a <strong>word corpus out of the keyphrases recognized by AWS</strong>. The reason for doing it on keyphrases rather than the processed texts is that I wanted to double down on the filtering of common words which were not part of the out-of-the-box stop words dictionary (e.g. like, think, etc.).</p><p>For creating the corpus, I <strong>tokenized the column</strong> of key phrases, counted each word by frequency. After, I <strong>stemmed the list of words</strong> to avoid duplication of words with different suffix and prefixes, and finally added up the frequencies grouped by words to <strong>deduplicate word entries</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d31da4f51b3775a4b3740642ad6a9c9/href">https://medium.com/media/6d31da4f51b3775a4b3740642ad6a9c9/href</a></iframe><h4>Entities</h4><p><a href="https://gist.github.com/nszoni/1d7c7efc78ae6f259f8d920002ed76fc">Entity detection</a> is also part of AWS Comprehend, thereby, I can leverage that to see the <strong>Top 10 entities of the community</strong>. Just as with keyphrases, I had to create a frequency table for every entity appearing in the processed text.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f156bfad13b1ff1d6dda3a024f266b60/href">https://medium.com/media/f156bfad13b1ff1d6dda3a024f266b60/href</a></iframe><h3>DataViz</h3><p>After making sure that everything is in order, I used <a href="https://ggplot2.tidyverse.org/index.html">ggplot</a> to extract some visual insights from the views I have created in the previous steps.</p><h4>Character Distribution of Top Monthly Posts</h4><p>The distribution of the number of characters per post follows a <strong>right-skewed</strong> distribution, with the average being approximately <strong>746 characters long</strong>. Such statistics should give me more confidence in the reliability of the text analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0qWd-vYennRQJBaRsImVQ.png" /><figcaption>Character distribution of posts</figcaption></figure><h4>Keywords of the Subreddit</h4><p>To illustrate the most commonly used phrases in the r/hungary subreddit, I used the stemmed and tokenized key corpus. In my experience, this subreddit is <strong>somewhat politically fuelled</strong>, which reflects why <strong>topics like vaccination, political parties (e.g., <em>Fidesz</em>)</strong>, are falling under the most common discussions. In addition to controversial themes, members of the community are usually debating on<strong> family, school, social life and workplace-related </strong>opinions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*rJH7chcYlvaY85UNczTaxw.png" /><figcaption>Word cloud of commonly mentioned keyphrases</figcaption></figure><h4>Top Entities</h4><p>Let’s see what were the top entities among the hottest monthly posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLdOPfxGoRp7rIH7-myZpg.png" /><figcaption>Top entities mentioned by the community</figcaption></figure><p><em>Fidesz</em> as a political party also ranks in the top entries among generic entities directly associated to the nationality of the subreddit. Due to the nature of Reddit and improper encoding, I can already detect anomalies in word stemming and processing unstructured messages that are not grammatically correct.</p><h4>Weekly Activities in Last Month’s Top</h4><p>When I look at the weekly distribution of activity in articles sorted by “Last Month’s Top,” I can observe that <strong>Week 42 was relatively a quieter period in terms of comments under top posts</strong>. Meanwhile, the activities on the remaining weeks from last months have been hovering around five thousand comments.</p><p>What’s more, <strong>the average weekly number of comments among last month’s top contents was 4,489 </strong>which is impressive considering the size of the subreddit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMXs9NoQl_tgB7W_9eVTSA.png" /><figcaption>Weekly activity metrics</figcaption></figure><p>Unfortunately, it is not possible to retrieve the number of upvotes on each post from the Reddit API wrapper, which would have made a difference in the definition and standardization of the activity.</p><h4>Weekly Sentiments</h4><p>Now that I have seen the descriptive statistics about the community, let’s discuss what sentiments drove people towards interaction in the last month. The proportional stacked bar chart below indicates that <strong>positive posts are rarely making it to the top threads. </strong>Also, the <strong>most negative posts were in Week 43 and 44</strong>, <strong>while the least in Week 42</strong>. The negativity in the former-mentioned period could be attributed to the large political upheaval right after the October 26th March and the premiere of a film which have divided supporters of the two political sides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMg5e7R3JV07agPjasdoJQ.png" /><figcaption>Weekly sentiments</figcaption></figure><blockquote>In charts having multiple colors in the aesthetic, I used ggplot’s <a href="https://ggplot2.tidyverse.org/reference/scale_viridis.html">viridis</a> scale which is a colorblind-friendly color palette.</blockquote><h4>Top Negative Posts</h4><p>In the last two subsections, I will dwell on the most active negative and positive posts over the last month by top keyphrases.</p><p>Here’s the top 5 posts with the most comments having a negative sentiment assigned to them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwd_wsBgabZZ3pidwXAfmg.png" /><figcaption>Top negative posts by keywords</figcaption></figure><p>The negative post with the most activity (<em>“people” </em>as its keyword) goes like this:</p><blockquote>How do I find out my colleague that I’m not interested in religion and God-related things? … You don’t keep that respect that I have a different opinion. Is it even possible to get people like that not to make a pledge? …</blockquote><p>Unusual wording, but you get the idea. This also reflects the <strong>weaknesses of AWS Translate when handling text full of urban terms</strong>. Also, it’s debatable why religion isn’t the most prominent keyword associated with this passage.</p><h4>Top Positive Posts</h4><p>As I highlighted before, there’s not been much positivity in recent month’s top posts, apart from asking for literature recommendations and a member sharing his experience about being learning Hungarian as a foreigner for six years now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4sMA8NtxWeI07L4Dz_tnQ.png" /><figcaption>Top positive posts by keywords</figcaption></figure><p>Again, here’s a short snippet of the top positive post about the literature recommendation:</p><blockquote>Could you recommend a literature whose writer clearly understands science, philosophy of science, and that permeates the book? … I do not even mean that, say, detailed botanical facts arise, but …</blockquote><p>Again, <em>“botanical facts”</em> is a very specific keyphrase, but I wouldn’t say that it fully represents the post itself.</p><h3>Takeaways</h3><p>Overally, I have enjoyed working on this blogpost not only because of Reddit but also because I was able to demonstrate a use case for a handful of AWS’s unique services.</p><p>In retrospect, all of the components I utilized to analyze r/hungary were simple enough to get some quick-fire insights about the Reddit community. It is undeniable, that there is still room to improve both at the source and processing level, such as the lack of upvote data on posts, further preprocessing, and fine-tuning the extraction of key phrases from the data.</p><p>It is also worth investigating how AWS’ sentiment detection works with texts consisting of emojis, how it compares to offerings from other cloud services, and further analysing the performance gap between structured formal texts and texts I have shown you in this blogpost.</p><blockquote>I hope you liked this brief journey with me, and please feel free to leave a remark on your experience with these services!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b055c10725d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/reddit-text-mining-with-aws-ai-services-and-r-6b055c10725d">Reddit Text Mining with AWS AI Services and R</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Superset: A hidden gem in the heaps of BI tools? — Part II.]]></title>
            <link>https://medium.com/hiflylabs/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-ii-e1a1f1657308?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a1f1657308</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[superset]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Wed, 14 Jul 2021 08:45:27 GMT</pubDate>
            <atom:updated>2022-06-20T13:03:36.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Superset: A hidden gem in the heaps of BI tools? — Part II.</h3><p><em>The original article can be found on </em><a href="https://blog.hiflylabs.hu/en/2021/07/13/dbt2/"><em>Hiflylabs’ blog</em></a><em>.</em></p><blockquote>In <a href="https://nszoni.medium.com/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-i-1994c4430a35?source=your_stories_page-------------------------------------">Part I.</a>, we argued in favor of using Superset as a free and open-source solution. Make sure to check it out beforehand to understand our dedication and excitement towards the project.</blockquote><p>Now, let’s dig into how we have test-driven Superset on top of other fascinating technologies.</p><h4><strong>Setup</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdV9IP0Gf3ROAWwF61yMaQ.png" /><figcaption>How we set up our infrastructure</figcaption></figure><p>We set out to showcase how Superset can consume data from a centralized data store such as Snowflake and <strong>build a stack of promising technologies</strong>.</p><ol><li>For that purpose, we leveraged the generated TPC-DS sample data as described in the <a href="http://tpc.org/tpc_documents_current_versions/pdf/tpc-ds_v3.1.0.pdf">specification</a> on our S3 bucket and set it as a named external stage on our Snowflake.</li><li>After that, we transformed the raw data with <a href="https://www.getdbt.com/">dbt</a> models and tests within <a href="https://docs.getdbt.com/docs/dbt-cloud/cloud-overview">dbt Cloud</a> before loading it back to Snowflake via the dbt run command, thereby creating a data mart.</li><li>To finish our continuous pipeline, we established the connection between Snowflake and Superset and assembled an example dashboard of the data mart.</li></ol><p>The data mart of promotions followed a <strong>star schema</strong> approach, where the fact table consisted of approximately 5 million rows and 47 columns. Moreover, we also set up a modern-analytical <strong>wide table by flattening the star schema</strong> into one joined table to <strong>test the performance</strong> of Superset.</p><h4><strong>Why use dbt for the T in ELT?</strong></h4><p><strong>dbt </strong>can be considered as a <strong>perfect companion </strong>to Snowflake for <strong>data transformation:</strong></p><ul><li>dbt is a “more for less” solution as it is <strong>faster and cheaper</strong> than its predecessors</li><li><strong>Well-integrated</strong> with Snowflake</li><li>Models are written in the <strong>mix of SQL and JINJA templating</strong> which is friendly for non-data engineers, while makes it quite expressive and fairly easy for data engineers</li><li>Rich templating allows you to seamlessly write macros for your models and <strong>parametrize your environment</strong></li><li>Template-based SQL is a good combination with Snowflake’s warehouse auto-scaling, zero-copy clonings, streams, and support for semi-structured data features</li><li>It’s heavily oriented towards <strong>collaboration, sharing, and reusability</strong></li><li>The option for testing is handy when it comes to <strong>ensuring the data quality and avoiding the error proneness</strong></li></ul><h4><strong>Findings</strong></h4><p>Our assessment is manifested in various findings.</p><ul><li>After installing the appropriate drivers it <strong>was pretty straightforward to connect our Snowflake database with Superset</strong>, as again, the connection string was made in accordance with the SQLAlchemy engine syntax.</li><li>Having the dataset available within Superset, <strong>we could quickly create</strong> a dashboard with multiple charts which can offer credible answers for our promotions data inquiries and exhibit how it can be used for ad-hoc analysis.</li><li>To our experience, <strong>assembling the charts and dashboard was as clear</strong> as possible: Superset makes it easy by guiding you through the necessary parameters.</li><li>Unlike in other leading commercial platforms, the <strong>UI isn’t cluttered with many features </strong>and is easy on the eye given its simplicity. Put differently, it gets the job done in style and efficiency.</li></ul><p>Let us now evaluate the layers of Superset!</p><p><strong><em>1. SQL Lab:</em></strong></p><ul><li>In parallel to the <strong>simplicity and clarity</strong> of this tool, it has everything needed by default for <strong>ad-hoc data wrangling</strong>, while the feature set can be extended based on the needs.</li><li><strong>Queries run smoothly</strong> without any disruption, and the IDE is intuitive enough to be used at any level.</li></ul><p><strong><em>2. Data Exploration:</em></strong></p><ul><li>Independently from using a virtual or real table, <strong>shuffling between visualization types</strong> has never been more satisfying, especially considering the project’s maturity.</li><li>Also provides the possibility to shift between granularities at ease and either <strong>create new metrics or restructure</strong> the dataset.</li><li>Although we only used the default visualization plugins, creating <strong>custom apps and visualizations</strong> are relatively straightforward thanks to Superset’s architecture and the designated documentation.</li></ul><p><strong><em>3. Dashboarding:</em></strong></p><ul><li>Assembling a chart works as one would expect as we can <strong>drag and drop</strong> our charts onto the dashboards and scale them with the help of <strong>grid lines</strong>.</li><li>The CSS of the dashboard can be easily<strong> tailored to your tastes</strong>, and the default components allow us to beautify visualizations even with Markdown.</li><li>After publishing the dashboards, one can (bulk) <strong>export </strong>them manually as JSON files from the interface, and import them to any Superset instance given that it has access to the source database.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DSoc-c46toroINvFEr33g.jpeg" /><figcaption>A snapshot of how we set up our dashboard</figcaption></figure><h4><strong>Further remarks</strong></h4><p>Firstly, according to the official documentation, Superset <strong>isn’t officially supported on Windows</strong>. Thus, Windows users can only try out superset locally via an Ubuntu Desktop VM or using WSL(2). The former likely works, but it wasn’t efficient from our standpoint. Even though we iterated through the latter option, unfortunately, we bumped into unknown or known- but-unresolved issues. We eventually managed to initiate Superset locally by starting the DockerHub image step-by-step (instead of docker-compose), but <strong>we suggest you avoid installing it on Windows</strong>. That being said, we hope that sooner or later, it will be natively supported. It’s also important to highlight as a footnote that we self-hosted the <em>0.999.0dev</em> version of Superset throughout our testing.</p><p>Secondly, it’s <strong>advisable to index</strong> (or cluster) the source tables (or materialized views) of visualizations, <strong>optimize both vertically and horizontally</strong> the underlying virtual warehouse in Snowflake as well as performing a <strong>micro-partition pruning</strong> (or dimensionality reduction). Otherwise, slices and dashboard queries tend to <strong>timeout due to concurrency</strong>, especially if filters are applied to multiple slices on the dashboard. This can be verified by investigating the execution plan of each chart within Snowflake’s query profile section and checking whether TABLE SCANNING consumes the lion’s share of the resources. Since queries can be saved and also tracked back within Superset, we can always reuse previous queries. Note, that our top priority wasn’t to benchmark the query performance of Superset within Snowflake, although we gained a general sense of it during our work.</p><p>Thirdly, Superset stores the dashboard components (metadata, and slice configurations) within its dedicated database, thus, we decided to manually store and transfer dashboards between instances rather than mounting the database onto a host folder and glue together each particle of a dashboard. Just to refer back to what has been said in <a href="https://nszoni.medium.com/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-i-1994c4430a35?source=your_stories_page-------------------------------------">Part I.</a>, the Superset community is very close to a pull workflow solution where you can play with YAML files of dashboards through the API. To our understanding, Superset supports exporting individual dashboards with a CLI command, but as of now we also feel the urge to also develop a bulk export option.</p><h4><strong>Conclusion</strong></h4><p>Let us not quickly summarize what we have learned together!</p><p>Commercial BI tools have been ruling the market for years until cost-friendly open source candidates started to show up gradually. Among those, <strong>Superset is considered one of the most exciting project</strong>s, and it’s certainly worthy of keeping an eye on.</p><p>We exposed Superset to a stack of auspicious technologies, notably dbt which is also an important technology Hiflylabs is moving forward with. From our experience, <strong>the learning curve is shallow</strong>er compared to the feature-loaded counterparts, whereas we mustn’t skip past the <strong>beauty and simplicity </strong>of Superset’s visualizations. We are committed to both the dbt and Superset open-source projects and we look forward to extending our client base by offering services on both in the foreseeable future.</p><p>As there have been instances for Superset slowly overtaking costly BI tools, we also hope to contribute to the initiative to cut costs and leverage our expertise in supercharging Superset. Even though there are downsides of using Superset due to its recent graduation, we believe that the <strong>strong community</strong> and the committers behind the project can launch the product into highs matching its potential.</p><blockquote>Now that you have seen Apache Superset synthetizing with products such as Snowflake and dbt, what are your impressions on it being the “chosen one” among the free and open-source solutions? Do you see any possibility of Superset establishing its noticeable share in the overheated data visualization market? Let us know in the comment section below! 👇</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a1f1657308" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-ii-e1a1f1657308">Apache Superset: A hidden gem in the heaps of BI tools? — Part II.</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Superset: A hidden gem in the heaps of BI tools? — Part I.]]></title>
            <link>https://medium.com/hiflylabs/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-i-1994c4430a35?source=rss-81e3d7a06326------2</link>
            <guid isPermaLink="false">https://medium.com/p/1994c4430a35</guid>
            <category><![CDATA[superset]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Sonny Nguyen]]></dc:creator>
            <pubDate>Wed, 07 Jul 2021 17:07:24 GMT</pubDate>
            <atom:updated>2022-06-20T13:03:40.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Superset: A hidden gem in the heaps of BI tools? — Part I.</h3><p><em>The original article can be found on </em><a href="https://blog.hiflylabs.hu/en/2021/07/07/dbt/"><em>Hiflylabs’ blog</em></a></p><blockquote>This article is part of the short series. Part I. deals with demonstrating the strengths of <strong>Superset </strong>and how it’s situated in the diverse dataviz market, while the upcoming <a href="https://nszoni.medium.com/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-ii-e1a1f1657308">Part II.</a> will discuss our experience in implementing and testing Superset on the pipeline illustrated with the figure below.</blockquote><figure><img alt="How we set up our infrastructure" src="https://cdn-images-1.medium.com/max/1024/1*bdV9IP0Gf3ROAWwF61yMaQ.png" /><figcaption><em>How we set up our infrastructure</em></figcaption></figure><h4><strong>Introduction</strong></h4><p>When we talk about <strong>interactive data visualization</strong>, especially in the context of modern data stacks (e.g. data streamer (Stitch, Fivetran, Airbyte) + centralized cloud storage (AWS, Azure, GCP, Snowflake, Databricks) + transformation tool (dbt) + BI platforms), proprietary tools pop into our head such as Tableau, Power BI, and more recently Looker. These were considered as the mainstream solutions for quite a while, but now, emerging <strong>open-source alternatives</strong> are hungry enough to beat the market with their simplicity and cost-friendly approach. Among these promising technologies, Apache Superset is set to challenge its competitors in many ways, therefore, <a href="https://www.hiflylabs.hu/english.html">Hiflylabs</a> closely monitors the roadmap of the project.</p><p>Given the maturity and <strong>dynamism of the BI market</strong>, consolidations are more frequent than ever. Over the past few years, other commercial tools were acquired by companies such as <a href="https://www.tableau.com/about/press-releases/2019/salesforce-completes-acquisition-tableau">Tableau by Salesforce</a>, <a href="https://looker.com/blog/google-closes-looker-acquisition">Looker by Google Cloud</a>, or <a href="https://www.sisense.com/blog/sisense-and-periscope-data-merge-2/">Periscope by Sisense</a>, which can infer the risk of <strong>vendor lock-ins </strong>forcing customers to migrate and rebuild their assets (e.g. <a href="https://chartio.com/blog/atlassian/">Chart.io was downsized and shut down by Atlassian</a>). Conversely, open-source platforms such as Superset avoid vendor lock-ins since you can both switch between commercial open source (COSS) vendors, and host it yourself on-premise. A good example for the former would be <a href="https://preset.io/">Preset</a> (founded by the creator of Superset, Max Beauchemin), who offers a hassle-free and fully-managed cloud SaaS service to the platform.</p><h4><strong>So why is it relevant just now?</strong></h4><p>Well, as the name indicates, Superset started in the Apache incubator back in 2016 and quickly became one of its top priority projects coinciding with the recent stable release at the beginning of 2021. It’s a modern,<strong> lightweight, cloud-native, free, and open-source</strong> BI web application with an advantageous SQLAlchemy python backend, making it scalable and compatible with almost any database technology speaking SQL. To reflect its increasing popularity,<a href="https://github.com/apache/superset/blob/master/RESOURCES/INTHEWILD.md"> <strong>Airbnb, Twitter, Netflix, Amex, and many other companies</strong></a> have already started incubating Superset in their workflows, while <a href="https://dropbox.tech/application/why-we-chose-apache-superset-as-our-data-exploration-platform">Dropbox</a> managed to successfully exploit its advantages at an<strong> enterprise level</strong>. In addition, the growing community behind Superset further strengthens the argument that there is an undeniable potential in our sight.</p><p>Superset essentially stands on <strong>three main layers</strong>:</p><p><strong><em>1. Dashboarding:</em></strong></p><ul><li>Seamless interaction with a wide range of tooltips</li><li>Drag and Drop crafting</li><li>Multiple ways of sharing your dashboard/charts (JSON, email, URL)</li></ul><p><strong><em>2. Data Exploration (Slice &amp; Dice):</em></strong></p><ul><li>Code-free visualization builder to extract and present datasets</li><li>Intuitive interface</li><li>Apply dozens of preset and custom visualization plugins instantly</li><li>User-defined metrics with scalable semantic layering</li><li>Lets you view the SQL statement for each visualization</li></ul><p><strong><em>3. SQL Lab:</em></strong></p><ul><li>A feature-rich SQL IDE written in React</li><li>A multi-tab environment lets you work on multiple queries at once</li><li>Metadata browsing of tables, columns, indexes, and partitions</li><li>Supports long-running queries by persisting query results and dispatching handlers to workers (<a href="https://docs.celeryproject.org/en/stable/index.html">Celery</a>)</li><li>Equipped with interactive querying, autocomplete, scheduling, query history, user-defined parameters (with JINJA templating through dbt CLI and dbt Cloud), etc.</li></ul><h4><strong>How does it perform on the big stage?</strong></h4><ul><li>Given that it’s a web-based stack application unlike Tableau and Power BI, it was tailored for the consumption layer as the <strong>data isn’t stored on the platform</strong>. Hence, the heavy-lifting is rather done in the connected database, making it again more scalable than its competitors when it comes to an ad-hoc analysis.</li><li>Given its <strong>cloud-nativeness</strong>, we can choose between standards and abstractions of web servers, metadata engines, and caching strategies. Also, it’s possible (and not even difficult) to change Superset SaaS providers or move the system fully in-house.</li><li>We can’t emphasize enough how<strong> semantic layering</strong> contributes to the reusability of queries and the scalability of Superset.</li><li>The <strong>high level of customizability</strong> is also appealing for us developers in the company. We didn’t even discuss the security features, which in essence gives us <strong>control over custom granularity roles and row-level security filters</strong> while supporting multiple authentication options and cache strategies. Speaking of the latter, along with the metadata and chart caching, the architecture allows us to set an additional <strong>asynchronous query caching mechanism</strong> to avoid timeouts during long queries.</li><li>Other prominent features embrace the <strong>public REST API, the real-time compatibility</strong> (also with other Apache graduates such as <a href="https://airflow.apache.org/">Airflow</a> and <a href="https://druid.apache.org/">Druid</a>), the ecosystem of <strong>custom visualization plugins</strong>, mail, and Slack alert support, <strong>streamline data access</strong>, cross-team sharing and the list goes on.</li></ul><h4><strong>Head-to-head with Looker</strong></h4><p>We have seen many instances for pairing Looker with dbt, but the following arguments made us advocate for Superset:</p><ul><li>In contrast with Looker’s LookML, <strong>the learning curve of Superset is shallower thanks to its SQL-centric design </strong>being more approachable for the majority</li><li>Looker only supports about 15 different types of charts with standard customizations, and due to its closed-source model, the <strong>ecosystem of custom visualizations</strong> falls short compared to that of Superset.</li><li>Since Looker’s persistent derived tables (PDT) had their weaknesses in incremental rebuilds, the best practice was to either perform the data preparation at a database level or complement it with dbt. They have recently <a href="https://looker.com/blog/incremental-pdts?utm_term=world&amp;utm_content=buffer92ad3&amp;utm_medium=social&amp;utm_source=linkedin.com&amp;utm_campaign=buffer">addressed</a> the shortcomings, but it’s hard to imagine one leaving dbt and going back to PDT. Consequently, <strong>PDT is no longer a selling point for Looker</strong>, and it’s more reasonable to consider Superset as an alternative.</li><li>Lastly, although Looker is comparable with Superset due to its web application nature, it has an enterprise pricing structure similar to commercial tools, while <strong>Superset is entirely free</strong>.</li></ul><h4><strong>Why use Superset? — the case study of Dropbox</strong></h4><p>Let’s see a case study on how Superset was chosen to be implemented into enterprise-level production!</p><p>The table below was retrieved from a<a href="https://dropbox.tech/application/why-we-chose-apache-superset-as-our-data-exploration-platform"> Dropbox article</a> on Jan 19, 2021. Long story short, they desired to find one particular BI tool to <strong>replace multiple other solutions</strong>. The main emphasis was on the security, user-friendliness, maintainability, flexibility, and extensibility of the platform. Their choice also landed on Superset as it was the best match for their specific internal needs. As a part of their decision-making process, they provided a comparison table that shows that Superset is superior compared to its peers in terms of the number of features and compatibility.</p><p><strong>Data Visualization Platform Comparison Matrix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y06raH4fs4VcW8Npl2J6DQ.jpeg" /><figcaption>Source: Dropbox Tech — Why we chose Apache Superset as our data exploration platform</figcaption></figure><p>Dropbox explained ditching Metabase with the argument that it’s developed in Clojure rather than Python, while to their knowledge, it has shortcomings from many additional aspects compared to Superset, for example, it has less authentication and data backend support. Since Dropbox has many strong Python developers, they decided to pursue Superset instead of Metabase.</p><h4><strong>Limitations</strong></h4><p>Just as other tools, Superset also has its limitations.</p><ul><li>It doesn’t allow creating visualization from multiple tables within its Data Exploration layer. Simply put,<strong> tables have to be joined beforehand</strong> either at a database level or in the SQL Lab as a virtual table. We wouldn’t consider that as a missing feature but it can undoubtedly be inconvenient. However, it has generally been distilled as a best practice to prepare joins at the database level as much as possible (e.g. Looker’s LookML can do these joins but it has been found time and again that it shouldn’t be used for more than for quick prototypes.).</li><li>As long as <strong>SQL is needed</strong> to manipulate tables before applying visualization, a basic knowledge of SQL can be beneficial but not considered a necessity.</li><li>Being self-hosted is a double-edged sword: a blessing for flexibility but needs somewhat <strong>more effort on the maintenance</strong> side. We have found its maintenance needs well tolerable but it sure prompts for a Python web developer to be around.</li><li><strong>Cross-filtering between charts isn’t fully supported</strong> at the moment, but such should be available at any time now.</li><li>Although it has extensive connection support, it <strong>doesn’t support NoSQL</strong> data sources.</li><li><strong>Version control isn’t an explicit feature</strong> as Superset stores the components of a dashboard separately in its dedicated database. That being said, Preset teased an upcoming feature allowing users to version dashboards as <strong>YAML configurations</strong> and move between instances through the API. In <a href="https://nszoni.medium.com/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-ii-e1a1f1657308">Part II.</a>, we will also mention alternative ways to transfer dashboards between Superset instances.</li></ul><blockquote>Did Superset spark some interest in you or it still falls short of being a credible solution to your pipeline? What are the missing features which would elevate the product to a day-to-day alternative for you? Make sure that your voice is heard in the comment section below! 👇 Also, stay tuned for the second part of the series!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1994c4430a35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hiflylabs/apache-superset-a-hidden-gem-in-the-heaps-of-bi-tools-part-i-1994c4430a35">Apache Superset: A hidden gem in the heaps of BI tools? — Part I.</a> was originally published in <a href="https://medium.com/hiflylabs">Hiflylabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>