LoginSignup
8
3

More than 1 year has passed since last update.

BigQueryでSTRING型のJOINを高速化する方法

Last updated at Posted at 2022-12-07

BigQueryでJOINをする際にSTRING型のカラムを使って結合すると、クエリに時間がかかることがあります。
実際にBigQueryのベストプラクティスにもSTRING型ではなくINT型を使うことが推奨されています。

select ...
from table1
join table2 on table1.str_key = table2.str_key -- 遅い

とはいえ、分析の要件によってはSTRING型でのJOINが必須な場合もあります。
そのようなときのためにSTRING型のJOINを高速化する方法を紹介します。

BigQueryには FARM_FINGERPRINT というハッシュ関数があり、この関数を使うことでSTRING型をINT型に変換できるので、この関数の適用結果を使ってJOINを行います。
また、ハッシュ関数を使っているので関数適用前の値が一致しなくても適用後の値が一致してしまうことが極稀に発生します。
そのため、where句でそのようなレコードを除外しています。

select ... 
from table1
join table2 on farm_fingerprint(table1.str_key) = farm_fingerprint(table2.str_key)
where table1.str_key = table2.str_key -- joinの方が先に処理されるのでwhere句の処理対象のレコードは多くない
8
3
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
8
3