dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

BigQuery で "{属性名}: {属性値}, ..." の属性値を取得するユーザ関数

2024-02-18 00:05:14 | BigQuery
BigQuery で "{属性名}: {属性値}, ..." の形式の文字列から指定の属性名の属性値を取得する関数のメモ。
以下のような文字列から指定の属性名の属性値を取得するユーザ関数を作成します。
price: positive, function: negative, quality: neutral

関数定義は以下の通り。
create or replace function
  dataset.get_attribute_value(text string, name string)
returns
  string
as (
    regexp_extract(
      text
      , concat('(?:^|,[ ]*)', name, ':[ ]*([^, ]+)')
    )
);

以下で属性値を取得する。
select
  dataset.get_attribute_value('price: neutral, quality: positive', 'price') as attr1
  , dataset.get_attribute_value('price: neutral, quality: positive', 'function') as attr2;

実行結果は以下の通り。
[{
  "attr1": "neutral",
  "attr2": null
}]