Skip to content

Instantly share code, notes, and snippets.

@tvirot
Created September 29, 2017 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvirot/5060ecd0821b5beb0e8b8fca432e548b to your computer and use it in GitHub Desktop.
Save tvirot/5060ecd0821b5beb0e8b8fca432e548b to your computer and use it in GitHub Desktop.
Example: UDF in BigQuery
CREATE TEMPORARY FUNCTION allPairs(posts ARRAY<INT64>)
RETURNS ARRAY<STRUCT<post1 INT64, post2 INT64>>
LANGUAGE js AS """
const len = posts.length;
// assume `posts` are sorted
let i, j;
let pairs = [];
for(i=0; i < len-1; i++) {
for(j=i+1; j < len; j++) {
pairs.push({post1: posts[i], post2: posts[j]});
}
}
return pairs;
""";
SELECT
pairs
FROM (
SELECT
allPairs(ARRAY_AGG(post_id ORDER BY post_id)) AS pairs
FROM subscriptions.speaker_likes_2017
GROUP BY id
) t, t.pairs AS pairs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment