1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Bigquery のarray_aggを使うと rowの上限に引っかかることがある

Last updated at Posted at 2019-11-21

なにこれ

Bigqueryのarray_aggには気をつけよという自戒

詳細

とある処理でarray_aggを使用していたのだが、rowの100MBの上限に引っかかってしまった。
別に対してカラム数が多いわけではなかった。
array_aggを外したら問題なかった。array_aggが悪さをしているようだ。

やったこと

こんなテーブルがあった時に、IDごとに最新の日付のnameを取りたい。

id name date
1 a 2019-1-1
1 b 2019-1-2
1 c 2019-1-3
2 d 2019-1-2
2 e 2019-1-4
2 2019-1-5

こんな処理を書いた

with t as (
select * from unnest([
struct(1 as id, "a" as name, date("2019-1-1") as date),
(1,"b", "2019-1-2"),
(1,"c", "2019-1-3"),
(2,"d", "2019-1-2"),
(2,"e", "2019-1-4"),
(2,null, "2019-1-5")
])
)

select 
 id,
  array_agg(name IGNORE NULLS ORDER BY date desc )[offset(0)]
from t
group by 1

結果

id name
1 c
2 e

何が問題か

array_aggを使ってoffset等で指定をすれば値は1つしかとれないが、
BQの状態としては、 配列をrowに展開した後、位置を指定している (と思う。)
要素が多ければ多いほど1rowのサイズが増える。結果、rowの上限に引っかかった。

代替案

カッコつけずにwindow関数使おうね
というは易しだが他の値を集計しつつ、出したい時もあると思う

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?