LoginSignup
3

More than 5 years have passed since last update.

BigQueryのStandardSQLのUDFでSTRUCT型を返すときは`<...>`で型を指定する

Posted at

はじめに

BigQueryのStandardSQL では、CREATE [TEMPORARY] FUNCTION でちょっとした関数を定義できますが、STRUCT型を返すときの書き方がなかなかググれなかったのでメモです。

書き方

STRUCT型の中身を < > で囲って指定すればOKです。

CREATE TEMPORARY FUNCTION parse_json(json_str STRING) 
RETURNS STRUCT<name STRING, birthday STRING, mail STRING> 
LANGUAGE js AS """
  return JSON.parse(json_str);
""";

SELECT parse_json('{"name": "hogehoge", "birthday": "2000-01-01", "pref": 31}') as user

↓ 結果

Row user.name user.birthday user.mail
1 hogehoge 2000-01-01 null

となります。

<> で指定しなかった列 pref は出力されませんし、キーが無かったmailnullになります。

さいごに

一応、ここ https://cloud.google.com/bigquery/docs/reference/standard-sql/migrating-from-legacy-sql には書いてあるんですが、みつけるまでに時間がかかりました。。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3