简体   繁体   中英

In google bigquery, how to use javascript UDF using google python client

I am writing a query in bigquery using standard SQL and javascript UDF. I am able to implement this using WebUI and bigquery command line tool but my requirement is to make this query using google python client. Not able to achieve this. Please can someone help.

from google.cloud import bigquery
bigquery_client = bigquery.Client()
client = bigquery.Client()
query_results = client.run_sync_query("""

CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b    array<STRING>)
RETURNS string
LANGUAGE js AS """

var values = {};

 var counter = 0;

 for(i=0;i<a.length;i++)

 { var temp;

   temp = a[i];

   a[i] = counter;

   values[temp] = counter;

   counter ++;
  }

for(i=0;i<b.length;i++)
  {

for(var key in values)
  {
   if(b[i] == key)
   {
    b[i] = values[key];
   }
  }
}

return b;
""";

SELECT
CategoriesToNumerical(ARRAY(SELECT DISTINCT ProspectStage from   lsq.lsq_dest),ARRAY(SELECT ProspectStage from lsq.lsq_dest)) as prospectstageds

;""")

query_results.use_legacy_sql = False

query_results.run()

page_token = None

while True:
    rows1, total_rows, page_token = query_results.fetch_data(
        max_results=100,
        page_token=page_token)
    for row1 in rows1:
        print "row",row1
    if not page_token:
        break

This is not working for me.Please can someone help with how should I be going about it.

The problem seems to be you have here 2 sets of conflicting """. Replace one of these sets for a triple ''', and the code should work.

So instead of

query_results = client.run_sync_query("""

CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b    array<STRING>)
RETURNS string
LANGUAGE js AS """
  javacript code
"""
SELECT *
FROM 
"""

write

query_results = client.run_sync_query('''

CREATE TEMPORARY FUNCTION CategoriesToNumerical(a array<STRING>,b    array<STRING>)
RETURNS string
LANGUAGE js AS """
  javacript code
"""
SELECT *
FROM 
'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM