Or pip install git+https://github.com/dbt-athena/dbt-athena.git
Prerequisites
To start, you will need an S3 bucket, for instance my-bucket and an Athena database:
CREATE DATABASE IF NOT EXISTS analytics_dev
COMMENT 'Analytics models generated by dbt (development)'
LOCATION 's3://my-bucket/'
WITH DBPROPERTIES ('creator'='Foo Bar', 'email'='foo@bar.com');
Notes:
Take note of your AWS region code (e.g. us-west-2 or eu-west-2, etc.).
You can also use AWS Glue to create and manage Athena
databases.
Credentials
Credentials can be passed directly to the adapter, or they can
be determined automatically based
on aws cli/boto3 conventions.
You can either:
Configure aws_access_key_id and aws_secret_access_key
Configure aws_profile_name to match a profile defined in your AWS credentials file.
Checkout dbt profile configuration below for details.
Configuring your profile
A dbt profile can be configured to run against AWS Athena using the following configuration:
Option
Description
Required?
Example
s3_staging_dir
S3 location to store Athena query results and metadata
Required
s3://bucket/dbt/
s3_data_dir
Prefix for storing tables, if different from the connection's s3_staging_dir
Optional
s3://bucket2/dbt/
s3_data_naming
How to generate table paths in s3_data_dir
Optional
schema_table_unique
s3_tmp_table_dir
Prefix for storing temporary tables, if different from the connection's s3_data_dir
Optional
s3://bucket3/dbt/
region_name
AWS region of your Athena instance
Required
eu-west-1
schema
Specify the schema (Athena database) to build models into (lowercase only)
Required
dbt
database
Specify the database (Data catalog) to build models into (lowercase only)
Required
awsdatacatalog
poll_interval
Interval in seconds to use for polling the status of query results in Athena
Optional
5
debug_query_state
Flag if debug message with Athena query state is needed
Optional
false
aws_access_key_id
Access key ID of the user performing requests
Optional
AKIAIOSFODNN7EXAMPLE
aws_secret_access_key
Secret access key of the user performing requests
Optional
wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
aws_profile_name
Profile to use from your AWS shared credentials file
Optional
my-profile
work_group
Identifier of Athena workgroup
Optional
my-custom-workgroup
skip_workgroup_check
Indicates if the WorkGroup check (additional AWS call) can be skipped
Optional
true
num_retries
Number of times to retry a failing query
Optional
3
num_boto3_retries
Number of times to retry boto3 requests (e.g. deleting S3 files for materialized tables)
Optional
5
num_iceberg_retries
Number of times to retry iceberg commit queries to fix ICEBERG_COMMIT_ERROR
Optional
3
spark_work_group
Identifier of Athena Spark workgroup for running Python models
Optional
my-spark-workgroup
seed_s3_upload_args
Dictionary containing boto3 ExtraArgs when uploading to S3
Optional
{"ACL": "bucket-owner-full-control"}
lf_tags_database
Default LF tags for new database if it's created by dbt
Optional
tag_key: tag_value
connection_manager
Which connection manager implementation to use (use to enable legacy PyAthena mode)
If set, the full S3 path to which the table will be saved
Works only with incremental models
Does not work with Hive table with ha set to true
partitioned_by (default=none)
An array list of columns by which the table will be partitioned
Limited to creation of 100 partitions (currently)
bucketed_by (default=none)
An array list of columns to bucket data, ignored if using Iceberg
bucket_count (default=none)
The number of buckets for bucketing your data, ignored if using Iceberg
table_type (default='hive')
The type of table
Supports hive or iceberg
ha (default=false)
If the table should be built using the high-availability method. This option is only available for Hive tables
since it is by default for Iceberg tables (see the section below)
format (default='parquet')
The data format for the table
Supports ORC, PARQUET, AVRO, JSON, TEXTFILE
write_compression (default=none)
The compression type to use for any storage format that allows compression to be specified. To see which options are
available, check out CREATE TABLE AS
field_delimiter (default=none)
Custom field delimiter, for when format is set to TEXTFILE
table_properties: table properties to add to the table, valid for Iceberg only
native_drop: Relation drop operations will be performed with SQL, not direct Glue API calls. No S3 calls will be
made to manage data in S3. Data in S3 will only be cleared up for Iceberg
tables see AWS docs. Note that
Iceberg DROP TABLE operations may timeout if they take longer than 60 seconds.
seed_by_insert (default=false)
Default behaviour uploads seed data to S3. This flag will create seeds using an SQL insert statement
Skip creating the table as CTAS and run the operation directly in batch insert mode
This is particularly useful when the standard table creation process fails due to partition limitations,
allowing you to work with temporary tables and persist the dataset more efficiently
unique_tmp_table_suffix (default=false)
For incremental models using insert overwrite strategy on hive table
Replace the __dbt_tmp suffix used as temporary table name suffix by a unique uuid
Useful if you are looking to run multiple dbt build inserting in the same table in parallel
temp_schema (default=none)
For incremental models, it allows to define a schema to hold temporary create statements
used in incremental model runs
Schema will be created in the model target database if does not exist
enabled (default=False) whether LF tags management is enabled for a model
tags dictionary with tags and their values to assign for the model
tags_columns dictionary with a tag key, value and list of columns they must be assigned to
lf_inherited_tags (default=none)
List of Lake Formation tag keys that are intended to be inherited from the database level and thus shouldn't be
removed during association of those defined in lf_tags_config
i.e., the default behavior of lf_tags_config is to be exhaustive and first remove any pre-existing tags from
tables and columns before associating the ones currently defined for a given model
This breaks tag inheritance as inherited tags appear on tables and columns like those associated directly
lf_tags and lf_tags_columns configs support only attaching lf tags to corresponding resources.
> We recommend managing LF Tags permissions somewhere outside dbt. For example, you may use
> terraform or
> aws cdk for such purpose.
data_cell_filters management can't be automated outside dbt because the filter can't be attached to the table
> which doesn't exist. Once you enable this config, dbt will set all filters and their permissions during every
> dbt run. Such approach keeps the actual state of row level security configuration actual after every dbt run and
> apply changes if they occur: drop, create, update filters and their permissions.
Any tags listed in lf_inherited_tags should be strictly inherited from the database level and never overridden at
the table and column level
> - Currently dbt-athena does not differentiate between an inherited tag association and an override of same it made
> previously
e.g. If an inherited tag is overridden by an lf_tags_config value in one DBT run, and that override is removed
prior to a subsequent run, the prior override will linger and no longer be encoded anywhere (in e.g. Terraform
where the inherited value is configured nor in the DBT project where the override previously existed but now is
gone)
Table location
The location a table is saved to is determined by:
If external_location is defined, that value is used
If s3_data_dir is defined, the path is determined by that and s3_data_naming
If s3_data_dir is not defined, data is stored under s3_staging_dir/tables/
Here all the options available for s3_data_naming:
It's possible to set the s3_data_naming globally in the target profile, or overwrite the value in the table config,
or setting up the value for groups of model in dbt_project.yml.
Note: when using a workgroup with a default output location configured, s3_data_naming and any configured buckets
are ignored and the location configured in the workgroup is used.
insert_overwrite (default): The insert overwrite strategy deletes the overlapping partitions from the destination
table, and then inserts the new records from the source. This strategy depends on the partitioned_by keyword! If no
partitions are defined, dbt will fall back to the append strategy.
append: Insert new records without updating, deleting or overwriting any existing data. There might be duplicate
data (e.g. great for log or historical data).
merge: Conditionally updates, deletes, or inserts rows into an Iceberg table. Used in combination with unique_key.
Only available when using Iceberg.
On schema change
on_schema_change is an option to reflect changes of schema in incremental models.
The following options are supported:
The adapter supports table materialization for Iceberg.
To get started just add this as your model:
{{ config(
materialized='table',
table_type='iceberg',
format='parquet',
partitioned_by=['bucket(user_id, 5)'],
table_properties={
'optimize_rewrite_delete_file_threshold': '2'
}
) }}
select 'A' as user_id,
'pi' as name,
'active' as status,
17.89 as cost,
1 as quantity,
100000000 as quantity_big,
current_date as my_date
Iceberg supports bucketing as hidden partitions, therefore use the partitioned_by config to add specific bucketing
conditions.
Iceberg supports several table formats for data : PARQUET, AVRO and ORC.
It is possible to use Iceberg in an incremental fashion, specifically two strategies are supported:
append: New records are appended to the table, this can lead to duplicates.
merge: Performs an upsert (and optional delete), where new records are added and existing records are updated. Only
available with Athena engine version 3.
unique_key(required): columns that define a unique record in the source and target tables.
incremental_predicates (optional): SQL conditions that enable custom join clauses in the merge statement. This can
be useful for improving performance via predicate pushdown on the target table.
delete_condition (optional): SQL condition used to identify records that should be deleted.
update_condition (optional): SQL condition used to identify records that should be updated.
insert_condition (optional): SQL condition used to identify records that should be inserted.
incremental_predicates, delete_condition, update_condition and insert_condition can include any column of
the incremental table (src) or the final table (target).
Column names must be prefixed by either src or target to prevent a Column is ambiguous error.
delete_condition example:
{{ config(
materialized='incremental',
table_type='iceberg',
incremental_strategy='merge',
unique_key='user_id',
incremental_predicates=["src.quantity > 1", "target.my_date >= now() - interval '4' year"],
delete_condition="src.status != 'active' and target.my_date < now() - interval '2' year",
format='parquet'
) }}
select 'A' as user_id,
'pi' as name,
'active' as status,
17.89 as cost,
1 as quantity,
100000000 as quantity_big,
current_date as my_date
update_condition example:
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key=['id'],
update_condition='target.id > 1',
schema='sandbox'
)
}}
{% if is_incremental() %}
select * from (
values
(1, 'v1-updated')
, (2, 'v2-updated')
) as t (id, value)
{% else %}
select * from (
values
(-1, 'v-1')
, (0, 'v0')
, (1, 'v1')
, (2, 'v2')
) as t (id, value)
{% endif %}
insert_condition example:
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key=['id'],
insert_condition='target.status != 0',
schema='sandbox'
)
}}
select * from (
values
(1, 0)
, (2, 1)
) as t (id, status)
Highly available table (HA)
The current implementation of the table materialization can lead to downtime, as the target table is
dropped and re-created. To have the less destructive behavior it's possible to use the ha config on
your table materialized models. It leverages the table versions feature of glue catalog, creating
a temp table and swapping the target table to the location of the temp table. This materialization
is only available for table_type=hive and requires using unique locations. For iceberg, high
availability is the default.
{{ config(
materialized='table',
ha=true,
format='parquet',
table_type='hive',
partitioned_by=['status'],
s3_data_naming='table_unique'
) }}
select 'a' as user_id,
'pi' as user_name,
'active' as status
union all
select 'b' as user_id,
'sh' as user_name,
'disabled' as status
By default, the materialization keeps the last 4 table versions, you can change it by setting versions_to_keep.
HA known issues
When swapping from a table with partitions to a table without (and the other way around), there could be a little
downtime.
If high performances is needed consider bucketing instead of partitions
By default, Glue "duplicates" the versions internally, so the last two versions of a table point to the same location
It's recommended to set versions_to_keep >= 4, as this will avoid having the older location removed
Update glue data catalog
Optionally persist resource descriptions as column and relation comments to the glue data catalog, and meta as
glue table properties
and column parameters.
By default, documentation persistence is disabled, but it can be enabled for specific resources or
groups of resources as needed.
For example:
models:
- name: test_deduplicate
description: another value
config:
persist_docs:
relation: true
columns: true
meta:
test: value
columns:
- name: id
meta:
primary_key: true
The adapter supports snapshot materialization. It supports both timestamp and check strategy. To create a snapshot
create a snapshot file in the snapshots directory. If the directory does not exist create one.
Timestamp strategy
To use the timestamp strategy refer to
the dbt docs
{{ config(
materialized='table'
) }}
select row_number() over() as id
, *
, cast(from_unixtime(to_unixtime(now())) as timestamp(6)) as refresh_timestamp
from {{ ref('employment_indicators_november_2022_csv_tables') }}
Incremental Iceberg models - Sync all columns on schema change can't remove columns used for partitioning.
The only way, from a dbt perspective, is to do a full-refresh of the incremental model.
Tables, schemas and database names should only be lowercase
Snapshot does not support dropping columns from the source table. If you drop a column make sure to drop the column
from the snapshot as well. Another workaround is to NULL the column in the snapshot definition to preserve history
AWS Lake Formation integration
The adapter implements AWS Lake Formation tags management in the following way:
You can enable or disable lf-tags management via config (disabled by default)
Once you enable the feature, lf-tags will be updated on every dbt run
First, all lf-tags for columns are removed to avoid inheritance issues
Then, all redundant lf-tags are removed from tables and actual tags from table configs are applied
Finally, lf-tags for columns are applied
It's important to understand the following points:
dbt does not manage lf-tags for databases
dbt does not manage Lake Formation permissions
That's why you should handle this by yourself manually or using an automation tool like terraform, AWS CDK etc.
You may find the following links useful to manage that:
Spark execution role granted access to Athena, Glue and S3
The Spark workgroup is added to the ~/.dbt/profiles.yml file and the profile to be used
is referenced in dbt_project.yml
Spark-specific table configuration
timeout (default=43200)
Time out in seconds for each Python model execution. Defaults to 12 hours/43200 seconds.
spark_encryption (default=false)
If this flag is set to true, encrypts data in transit between Spark nodes and also encrypts data at rest stored
locally by Spark.
spark_cross_account_catalog (default=false)
When using the Spark Athena workgroup, queries can only be made against catalogs located on the same
AWS account by default. However, sometimes you want to query another catalog located on an external AWS
account. Setting this additional Spark properties parameter to true will enable querying external catalogs.
You can use the syntax external_catalog_id/database.table to access the external table on the external
catalog (ex: 999999999999/mydatabase.cloudfront_logs where 999999999999 is the external catalog ID)
spark_requester_pays (default=false)
When an Amazon S3 bucket is configured as requester pays, the account of the user running the query is charged for
data access and data transfer fees associated with the query.
If this flag is set to true, requester pays S3 buckets are enabled in Athena for Spark.
Spark notes
A session is created for each unique engine configuration defined in the models that are part of the invocation.
A session's idle timeout is set to 10 minutes. Within the timeout period, if there is a new calculation
(Spark Python model) ready for execution and the engine configuration matches, the process will reuse the same session.
The number of Python models running at a time depends on the threads. The number of sessions created for the
entire run depends on the number of unique engine configurations and the availability of sessions to maintain
thread concurrency.
For Iceberg tables, it is recommended to use table_properties configuration to set the format_version to 2.
This is to maintain compatibility between Iceberg tables created by Trino with those created by Spark.
Python models can only reference or write to tables with names meeting the
regular expression: ^[0-9a-zA-Z_]+$. Dashes and special characters are not
supported by Spark, even though Athena supports them.
Incremental models do not fully utilize Spark capabilities. They depend partially on existing SQL-based logic which
runs on Trino.
Snapshot materializations are not supported.
Spark can only reference tables within the same catalog.
For tables created outside of the dbt tool, be sure to populate the location field or dbt will throw an error
when trying to create the table.
Contracts
The adapter partly supports contract definitions:
data_type is supported but needs to be adjusted for complex types. Types must be specified
entirely (for instance array<int>) even though they won't be checked. Indeed, as dbt recommends, we only compare
the broader type (array, map, int, varchar). The complete definition is used in order to check that the data types
defined in Athena are ok (pre-flight check).
The adapter does not support the constraints since there is no constraint concept in Athena.