Say I have a table in BQ called rating
with a struct column called rating_record
. Schema as:
[
{
"name": "id",
"mode": "NULLABLE",
"type": "STRING",
"description": null,
"fields": []
},
{
"name": "rating_record",
"mode": "NULLABLE",
"type": "RECORD",
"description": null,
"fields": [
{
"name": "high_drop",
"type": "BOOLEAN",
"fields": []
},
{
"name": "medium_bump",
"type": "BOOLEAN",
"fields": []
}
]
rating_record
contains fields high_drop
and medium_bump
and there could be many fields with suffix _drop
and _bump
with true or false values. I want to iterate this record type (struct) field using a dbt macro to create two new columns against an id
called drop_reasons
& bump_reasons
- drop_reasons
in this case would be = 'high_drop'
if the value is true.
I tried to iterate the record with a sql_statement
and using dbt_utils.get_query_results_as_dict
to get the outcome but unable to create columns accordingly.
{% set sql_statement %}
select id, rating_record from {{ ref('source_table' }}
{% endset %}
{%- set ids_and_ratings = dbt_utils.get_query_results_as_dict(sql_statement) -%}
select
{% for id in ids_and_ratings['id'] | unique -%}
{% set bump_reasons = [] %}
{% set drop_reasons = [] %}
{% for rating_record in ids_and_ratings['rating_record'] | unique -%}
{% for key, value in fromjson(rating_record).items() -%}
{% if key.endswith('bump') and value is sameas true %}
{{ bump_reasons.append(key) }}
{% elif key.endswith('drop') and value is sameas true %}
{{ drop_reasons.append(key) }}
{% endif %}
{% endfor %}
{% endfor %}
{{ print(drop_reasons) }}
{% endfor %}
from {{ ref('source_table' }}