Skip to content

Instantly share code, notes, and snippets.

@relud
Last active November 13, 2018 22:58
Show Gist options
  • Save relud/ac8d95980bebf7b0f06c2f15f0f5e399 to your computer and use it in GitHub Desktop.
Save relud/ac8d95980bebf7b0f06c2f15f0f5e399 to your computer and use it in GitHub Desktop.
BigQuery UDF getKey
SELECT
metadata.document_id,
STRUCT(
getKey(payload.histograms, "b") AS b
) as histograms
FROM UNNEST([
STRUCT(
STRUCT(
"bcfa6d63-d0dc-4e4a-a086-8e3844fca9cc" AS document_id
) AS metadata,
STRUCT(
STRUCT(
[
STRUCT("a" AS key, "A" AS value),
STRUCT("b" AS key, "B" AS value)
] AS key_value
) AS histograms
) AS payload
)
])
[
{
"document_id": "bcfa6d63-d0dc-4e4a-a086-8e3844fca9cc",
"histograms": {
"b": "B"
}
}
]
CREATE TEMP FUNCTION getKey(map ANY TYPE, k ANY TYPE) AS (
(
SELECT key_value.value
FROM UNNEST(map.key_value) AS key_value
WHERE key_value.key = k
LIMIT 1
)
);
@relud
Copy link
Author

relud commented Nov 13, 2018

can be verified with cat UDF.sql query.sql | bq query --nouse_legacy_sql --format=prettyjson --quiet | diff -u - result.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment