16
17

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.

Presto で JSON の ARRAY を集計する

Last updated at Posted at 2015-03-12

効率よい方法ではないですが、Fluentd 経由で S3 に送り込んだ JSON のログを Presto で集計するときにこんなやり方もできるというメモ。

下記のような構造のログが S3 に置いてあり、Hive の external table として raw_impressions というテーブルを定義して読めるようになっているとします。

{
  "user_id": 12345,
  "data": {
    "imp_ids": [1,2,3,4,5]
  }
}

ここで下記のように view を定義してあげます。view を定義しなくてもできますが、可読性がよくなるので、今回はそうしてます。

CREATE VIEW impressions AS
  SELECT
    cast(json_extract(json, '$.user_id') as bigint) as user_id,
    cast(json_extract(json, '$.data.imp_ids') as array<bigint>) as imp_ids
  FROM raw_impressions
;

ここまで来れば UNNEST 構文を使って、集計できます。

SELECT id, count(id)
FROM impressions
CROSS JOIN UNNEST(imp_ids) AS t (id)
GROUP BY id;

JSON のパースに時間がかかって、ログ量によってはだいぶツラいので、実用上は必要に応じてサンプリングしてみたりするといいのかもしれません。

SELECT
  link_id, count(link_id)
FROM impressions
CROSS JOIN UNNEST(imp_ids) AS t (id)
WHERE user_id % 1000 = 0
GROUP BY id;
16
17
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
16
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?