2016-10-28 140 views
0

而不是寫一個查詢像如何製作可在單列上操作的可重用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語句的整個FROM部分中使用它。有沒有什麼辦法可以將UDF推廣到我可以在1列上使用它的位置,而不是在所有行上操作它。這裏是我的代碼現在可以工作,但我必須預定義每個輸出列,使其不可重用。

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 
); 

回答

1

您使用standard SQL尋找scalar UDFs。與傳統SQL相比,它們使用起來更加笨拙。

+0

標量UDF正是我想要的。 –

2

它可能看起來有點雜亂 - 但下面的確是你問的!
確保你是在標準SQL(見Enabling Standard SQL

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))) 
+0

謝謝米哈伊爾 –

相關問題