LoginSignup
6
3

More than 1 year has passed since last update.

Amazon Athenaでパラメータ化されたクエリが使えるようになったので試してみた

Posted at

はじめに

Amazon Athenaで、パラメータ化されたクエリが使えるようになったとの事。
という事で、早速試してみました。

早速試してみる

今回は、既に作成済みのVPCフローログのデータベースに対するクエリをパラメータ指定して実行してみます。
VPCフローログのデータをAthenaで解析できるようにする方法は、以下などを参照ください。

まずは、パラメータ化せず、starttimeの期間だけを指定した簡単なクエリを実行します。
実行したクエリは以下です。

select
 from_unixtime(starttime,9,0) AS "starttime_jst",
 from_unixtime(endtime,9,0) AS "endtime_jst",
 sourceaddress AS "Source IP Address",
 sourceport AS "Source Port",
 destinationaddress AS "Destination IP Address",
 destinationport AS "Destination Port",
 protocol,
 action,
 logstatus
from default.vpc_flow_logs
where date_trunc('month',now())  = date_trunc('month',from_iso8601_timestamp(dt))
and from_unixtime(starttime, 9, 0) >= cast('2022-07-15 09:00:00 +09:00' as timestamp with time zone)
and from_unixtime(starttime, 9, 0) <  cast('2022-07-15 10:00:00 +09:00' as timestamp with time zone)
;

実行結果

aaa.png
これまでは、上記のようなクエリで指定する期間を変えたい場合、エディタで直接クエリを編集して実行する必要がありました。

しかし、今回の機能追加で、変更したいクエリの絞り込み条件をパラメータする事で、クエリを都度変更しなくてもよくなりました。

では、このクエリの期間指定している部分をパラメータ化して実行してみます。
パラメータ化するには、パラメータ化したい値の箇所を 「?」 に置き換えます。

先程実行したクエリを以下のように変更し、期間指定部分をパラメータ化します。

※文字列をパラメータ化する場合、シングルクォーテーションで囲う部分も含めて「?」を指定しないと実行時にエラーになります。

select
 from_unixtime(starttime,9,0) AS "starttime_jst",
 from_unixtime(endtime,9,0) AS "endtime_jst",
 sourceaddress AS "Source IP Address",
 sourceport AS "Source Port",
 destinationaddress AS "Destination IP Address",
 destinationport AS "Destination Port",
 protocol,
 action,
 logstatus
from default.vpc_flow_logs
where date_trunc('month',now())  = date_trunc('month',from_iso8601_timestamp(dt))
and from_unixtime(starttime, 9, 0) >= cast(? as timestamp with time zone) --日時部分をパラメータ化
and from_unixtime(starttime, 9, 0) <  cast(? as timestamp with time zone) --日時部分をパラメータ化
;

クエリを変更後、クエリを実行すると、今度は右側でパラメータの値の入力を求められます。
image.png
パラメータに以下の値を入力後、「実行」するとパラメータ化する前のクエリと同じ結果が出力されました。

  • パラメータ1:'2022-07-15 09:00:00 +09:00'
  • パラメータ2:'2022-07-15 10:00:00 +09:00'

※文字列を条件として指定する場合は、値をシングルクォーテーションで囲う必要があります。

実行結果

aaa.png
問題無く使えそうですね。

おわりに

Athenaでパラメータ化されたクエリを簡単に試してみました。

検索条件のパターン毎にクエリを保存していると、色々なバリエーションのクエリが大量にでき、運用上分かりにくくなる事もありましたが、パラメータ指定ができるようになった事で、クエリをテンプレート化してより活用できるようになるのではないかと思います。

6
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
6
3