Google bigquery 如何制作一个在单个列上运行的可重用UDF?
而不是像这样编写查询Google bigquery 如何制作一个在单个列上运行的可重用UDF?,google-bigquery,google-cloud-platform,Google Bigquery,Google Cloud Platform,而不是像这样编写查询 select * from xyz where mydomain IN ('foobar.com', 'www.example.com') 我想写一个函数,比如 select * from xyz where one_of_my_domains(select mydomain as from_site) 但我希望能够对多个表中的任意url重用此函数。目前,当我使用这样的函数时,我必须预定义返回的内容,并从SQL语句的一部分整体上使用它。是否有任何方法可以将UDF推广到只
select * from xyz where mydomain IN ('foobar.com', 'www.example.com')
我想写一个函数,比如
select * from xyz where one_of_my_domains(select mydomain as from_site)
但我希望能够对多个表中的任意url重用此函数。目前,当我使用这样的函数时,我必须预定义返回的内容,并从SQL语句的一部分整体上使用它。是否有任何方法可以将UDF推广到只在一列上使用它,而不是在所有行上操作它。这是我现在可以使用的代码,但是我必须预定义每个输出列,这使得它不可重用
domains = ['foobar.com', 'www.example.com'];
// The UDF
function has_domain(row, emit) {
var has_domain = false;
if (row.to_site !== null && row.to_site !== undefined) {
for (var i = 0; i < domains.length; i++){
if (domains[i] === String.prototype.toLowerCase.call(row.to_site)){
has_domain = true;
break;
}
}
}
return emit({has_domain: has_domain, trackingEventId: row.trackingEventId, date: row.date, from_site: row.from_site, to_site: row.to_site});
}
// UDF registration
bigquery.defineFunction(
'has_domain', // Name used to call the function from SQL
['from_site'], // Input column names
// JSON representation of the output schema
[{name: 'has_domain', type: 'boolean'}],
has_domain // The function reference
);
它可能看起来有点凌乱-但下面的内容正是您要求的! 确保您使用的是标准SQL,请参阅
它可能看起来有点凌乱-但下面的内容正是您要求的! 确保您使用的是标准SQL,请参阅
您正在寻找使用。与传统SQL相比,它们使用起来不那么麻烦。您正在寻找使用它们的方法。与传统SQL相比,它们使用起来不那么麻烦。标量UDF正是我想要的。标量UDF正是我想要的。
CREATE TEMPORARY FUNCTION one_of_my_domains(x STRING, a ARRAY<STRING>)
RETURNS BOOLEAN AS
(x IN (SELECT * FROM UNNEST(a)));
WITH xyz AS (
SELECT 1 AS id, 'foobar.com' AS mydomain UNION ALL
SELECT 2 AS id, 'www.google.com' AS mydomain
),
site AS (
SELECT 'foobar.com' AS domain UNION ALL
SELECT 'www.example.com' AS domain
)
SELECT *
FROM xyz
WHERE one_of_my_domains(mydomain, ARRAY((SELECT domain FROM site)))