The world’s leading publication for data science, AI, and ML professionals.

AWS Athena + DBT Integration

In 15 minutes or less

Photo by Etienne Girardet on Unsplash
Photo by Etienne Girardet on Unsplash

Context

AWS Athena is serverless and intended for ad-hoc SQL queries against data on AWS S3. However, maintaining data lineage and dependency is tedious and error-prone (no difference in Data Warehouses though).

DBT (Data Build Tool) has recently become extremely popular as it can automatically draw data lineage/generate documentation of the data pipeline, not to mention its’ other features like Snapshot, Jinja & Macro support.

There are tons of references related to integrating DBT with Data Warehouses (Snowflake, Redshift, Databrick etc) but not Athena(Yes, it is not a Data Warehouse). However, there are many use cases and teams using Athena to generate BI reports etc:

  • The report has 20+ views generated from various AWS DataCatalog databases and tables.
  • Data lineage is important in order to understand business logic and it changes frequently.
  • The computation performance of Athena is satisfied.
  • Lack of resources/budget to implement/maintain Data Warehouses.

Is there any chance we could integrate DBT with Athena to provide an affordable solution?


Solution

Thanks to dbt-athena community who built a DBT Athena adapter, I used it to build a demo to verify how the integration works. All AWS infra resources are managed by Terraform and provided in my GitHub repo so you can build the same E2E demo in 15 minutes (or even less) **** for either POC(proof of concept), internal demo or self-learning purposes.

Raw Data

Women’s E-Commerce Clothing Reviews review data¹ (CC0: Public Domain license²) is used and details of the data statistical summary can be found on the Kaggle website.

Image by Author
Image by Author

In short, this data contains customer reviews on products and corresponding rates on products. A typical use case is to use this data to do sentiment analysis after proper featuring engineering (data transformation).

Dataflow

Under this demo, the raw data is stored in S3 with Glue services utilised to extract its schemas for Athena to query followed by DBT’s transformation.

Image by Author
Image by Author
  1. Glue crawler is manually triggered to infer data schema and update DataCatalog to Glue DataCatalog.
  2. Glue DataCatalog creates a reference to data (S3-to-Table) mapping, no data is moved.
  3. Query data in S3 using SQL, schema lookup in Glue Data Catalog, no data to load.
  4. DBT applies Software Engineering methodology to data transformation (SQL).

It is expected the reader would have some basic knowledge about Terraform, AWS and DBT otherwise this is also a good mini-project for a reader to learn about those services.


Implementation

Terraform Part

  • Install Terraform
  • git clone https://github.com/grhaonan/Athena-dbt-demo-tf-local
  • Make sure proper AWS user and permission are set up. For the sake of simplicity, my AWS user simply has an AdministratorAccess policy attached.
  • The profile name in Terraform main.tf should match the user profile, which is used to call AWS services, defined in "~./aws/credentials".

    Notes:

  • The region is set to "ap-southeast-2" by default, feel free to update it in variables.tf
  • Some AWS resources (s3 bucket etc) need to be globally unique, a random id generator is used in the Terraform to ensure uniqueness across different users. You will see several {16 digits id} conventions in this article and that refers to a random id.

Run the "terraform init" command to initiate the project.

Image by Author
Image by Author

Run the "terraform apply" command to apply all AWS resources

Image by Author
Image by Author

Manually trigger/run the crawler job (named "athena_dbt_demo_crawler" per this demo and configured in terraform) on AWS web console.

Image by Author
Image by Author

Once done you will find the table "women_clothes_reviews_raw_data" under database rawdata{16 random id} in Athena (Note: Please select the athena-dbt-demo-workgroup instead of primary). Now, this raw data is ready for query.

Image by Author
Image by Author

You will also see the source raw data under the following bucket in S3: Athena-dbt-demo-{16 random id}/raw_data/women_clothing_ecommerce_reviews.csv. This file is uploaded to S3 automatically during the Terraform Apply phase.

DBT Part

Image by Author
Image by Author
  • Instead, I would suggest installing it through a clean virtual environment (Through conda etc). Note: Rquirements.txt is under the folder "Athena-dbt-demo-dbt-demo"

    Once done, check the version, now we are good to go!

Image by Author
Image by Author

Create your DBT profile if it doesn’t exist (~/.dtb/profiles.yml) or add this project to your existing DBT profile

Note:

You should only update the following three values in the above file to match your case but keep the other values (per matching terraform configuration) untouched.

  • aws_profile_name: Same AWS profile name per configured in terraform main.tf and local AWS profile name.
  • s3_staging_dir: This is the s3 bucket created to store Athena query result, it is named "athena-dbt-demo-athena-query-result-bucket-{16 random id}" in your S3 bucket.
  • Schema: This is the database configured to export DBT models results and it should match athena_dbtmodels{16 digits id}

Lastly, update the database referenced in models/vw_women_clothes_reviews_rename_columns.sql to match the rawdata{16 digits id} created.

...
FROM "RAW_DATA_9f40f41fee84f437"."WOMEN_CLOTHES_REVIEWS_RAW_DATA"

About Data Transformation

Within DBT, we implemented three transformations (/models)on top of raw data.

  • (View) vw_women_clothes_reviews_rename_columns conducts the first transformation: selecting needed columns and renaming them
  • (View) vw_women_clothes_reviews_sentiments will create sentiment score based on pre-defined rule on column start_rating.
  • (View) vw_women_clothes_reviews_training_data will conduct some final filtering and serve as the transformed result.

DBT Run

Finally, run the command "dbt run" will compile all three models defined above and land results under AwsDataCatalog database "athena_dbtmodels{16 random id}" and you can also find it in Athena.

Image by Author
Image by Author

One key feature of DBT is to provide data lineage and documents.

  • Run command "dbt docs generate" will generate docs
  • Then set up a local web server through the command "dbt docs serve – port 8001" (it is two hyphens before port) to visualise docs.

Data Lineage:

  • women_clothes_reviews_training_data depends on vw_women_clothes_reviews_sentiments which is further based on vw_women_clothes_reviews_rename_columns.
Image by Author
Image by Author

Data Document:

Image by Author
Image by Author

Summary

Thanks for your interest and hope you enjoyed it. Despite the fact that Athena is normally used for ad-hoc query purposes, it can still benefit from DBT integration at a low cost.

Let’s have a quick recap of this article:

  • A product review data is loaded in S3 and "connected" to SQL query service Athena through AWS Glue services.
  • All AWS resources in this demo are managed by Terraform (IaC) so users can deploy/destroy them in seconds.
  • dbt-athena is a community-maintained DBT adapter to integrate DBT with Athena.
  • BI reports based on Athena will benefit a lot from DBT’s data lineage and documentation features.

Enjoying my content? Please consider becoming a member. Your support fuels my work. Thank you!

[1] Women’s E-Commerce Clothing Reviews https://www.kaggle.com/datasets/nicapotato/womens-ecommerce-clothing-reviews?resource=download

[2] CC0: Public Domain License https://creativecommons.org/publicdomain/zero/1.0/


Related Articles