LoginSignup
0
2

More than 3 years have passed since last update.

pythonから Amazon Athenaへクエリ実行(名前付きプロファイル使用)

Posted at

はじめに

windows command lineにて、AWS CLIでAthenaに接続させることがあるが、
どうせなら、
クエリ結果を取得してグラフ描画まで出来ればなと思い、pythonで行うと思ったのだけれども
名前付きプロファイルの部分で行き詰まった個所があったので、整理

マニュアル記載の方法(名前付きprofile未使用)

windows command lineでの方法

aws athena start-query-execution
  --query-string "select * from table_name"
  --result-configuration "s3://path/to/query/bucket/"

AWSドキュメント:
https://docs.aws.amazon.com/cli/latest/reference/athena/start-query-execution.html

pythonでの方法


athena = boto3.client('athena')

# クエリ実行
exec_run = athena.start_query_execution(
    QueryString="select * from table_name",
    QueryExecutionContext={'Database': 'database_name'},
    ResultConfiguration={'OutputLocation': 's3://path/to/query/bucket/'})

AWSドキュメント:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/athena.html

今回行いたいこと 

名前付きプロファイルの情報を用いて、クエリ実行を行いたい。

名前付きプロファイルの設定方法が
「windows command line」と「python」で異なることに気が付かず無駄に時間を使ってしまった。

名前付きプロファイルの設定方法は
windows command line:awsコマンドのパラメータとして設定
python        :boto3.sessionクラスを使ってプロファイル情報を設定

windows command lineでの方法(名前付きprofile使用)

aws athena start-query-execution
  --query-string "select * from table_name"
  --result-configuration "s3://path/to/query/bucket/"
 --profile "NRP"

AWSドキュメント:
https://docs.aws.amazon.com/cli/latest/reference/athena/start-query-execution.html
https://docs.aws.amazon.com/cli/latest/reference/athena/start-query-execution.html

pythonでの方法(名前付きprofile使用)


session = boto3.Session(profile_name='NRP')
athena = session.client('athena')

# 処理実行
exec_run = athena.start_query_execution(
    QueryString="select * from table_name",
    QueryExecutionContext={'Database': 'database_name'},
    ResultConfiguration={'OutputLocation': 's3://path/to/query/bucket/'})

AWSドキュメント:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/athena.html
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/session.html
S3の接続についての記事:
boto3 で デフォルトprofile以外を使う

最後に

boto3.sessionにたどり着くのが大変だった。エラー文ベースで調べてたのも良くなかった。
マニュアルにもしっかり書いてあったし
たどり着いてしまえば、いろいろとわかってくるもんだなと再認識。

ただ、今度は取得結果が全件なかったりと課題はたくさん

以上。

参考情報

各箇所に記載

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