0
1

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] Key-Vlue形式でクエリ結果を吐き出してみた話

Posted at

Key-Value形式でクエリ結果を吐き出してみた話

SendGrid Projectにおいて、Web APIを導入するなら差込文字をJSONで送らないといけないということで、PrestoでどうやったらKey-Value型でデータが持てるんだろうというのを頑張ってみました。

結論

ものすごく簡単で

select
  map(
      array['pref_id','pref_name']
    , array[cast(id as varchar), name]
  )
from
  pref

結果は

{"pref_id":"1","pref_name":"北海道"}
{"pref_id":"2","pref_name":"青森県"}
{"pref_id":"3","pref_name":"岩手県"}
{"pref_id":"4","pref_name":"宮城県"}
{"pref_id":"5","pref_name":"秋田県"}
...etc

的な感じでGetできます! すごい。

道具

array[ ]

詳しくは公式ドキュメントを読んでください。
array[x]で [x]という配列を作れます。
そして、 array[x,y]で [x,y] 。以下同様。

これ、一点だけ注意である配列のすべての要素のデータ型は全部同じようです。
なので [2, 'name'] みたいなのはNGっぽい!

map( array, array )

こちらも公式ドキュメントを読んでもらえれば。

map(array<K>, array<V>) → map
Returns a map created using the given key/value arrays.

だそうです。。。???
ようは、Keyを詰め込んだ array<K> とValueを詰め込んだ array<V> を用意してぶち込め! あとは処理しちゃる!
ってことみたいですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?