Created
September 18, 2019 21:33
-
-
Save dyerrington/a3d283306318aaa73711825ca08b4621 to your computer and use it in GitHub Desktop.
Python code that will create, essentially a pivot from a nested big query set. Based on the original method in the google big query documentation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# fighting == most common event type | |
def build_udf_prototype(event_types): | |
null = "null" # default all types to null in the UDF function | |
PIVOT_FEATURES = str({"col_" + event_name.replace("-", "_"): null for event_name in event_types.tolist()}).replace("'null'", "null") | |
SQL_RETURN = "STRUCT<" | |
for event_type in event_types.tolist(): | |
event_type = event_type.replace("-", "_") | |
SQL_RETURN += f"col_{event_type} INT64, " | |
SQL_RETURN = SQL_RETURN[:-2] + ">" | |
tripple_boundary = '"""' | |
sql_template = """ | |
CREATE TEMP FUNCTION customGreeting(event ARRAY<STRUCT< name STRING, rec_count INT64>>) | |
RETURNS {SQL_RETURN} | |
LANGUAGE js AS {tripple_boundary} | |
var pivot = {PIVOT_FEATURES} | |
for(i = 0; i < event.length; i++) { | |
key_name = 'col_' + event[i]['name'] | |
if (pivot.hasOwnProperty(key_name)) { | |
pivot[key_name] = event[i]['rec_count']; | |
} | |
} | |
return pivot | |
{tripple_boundary}; | |
SELECT | |
key, | |
id, | |
date, | |
customGreeting(events) | |
FROM [your dataset] | |
LIMIT 100; | |
""" | |
sql_template = sql_template.replace("{PIVOT_FEATURES}", PIVOT_FEATURES) | |
sql_template = sql_template.replace("{tripple_boundary}", tripple_boundary) | |
sql_template = sql_template.replace("{SQL_RETURN}", SQL_RETURN) | |
print(sql_template) | |
events_df.apply(build_udf_prototype) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This creates an SQL statement: