Amazon Redshift Python コネクタの使用例 - Amazon Redshift

Amazon Redshift は、パッチ 198 以降、新しい Python UDF の作成をサポートしなくなります。既存の Python UDF は、2026 年 6 月 30 日まで引き続き機能します。詳細については、ブログ記事を参照してください。

Amazon Redshift Python コネクタの使用例

Amazon Redshift Python コネクタの使用例を次に示します。これを実行するには、まず Python コネクタをインストールする必要があります。Amazon Redshift Python コネクタのインストールの詳細については、「Amazon Redshift Python コネクタのインストール」を参照してください。Python コネクタで使用できる設定オプションの詳細については、「Amazon Redshift Python コネクタの設定オプション」を参照してください。

AWS 認証情報を使用した Amazon Redshift クラスターへの接続およびクエリ

以下の例は、AWS 認証情報を使用して Amazon Redshift クラスターに接続し、次にテーブルをクエリしてクエリ結果を取得する手順を示しています。

#Connect to the cluster >>> import redshift_connector >>> conn = redshift_connector.connect( host='examplecluster.abc123xyz789.us-west-1.redshift.amazonaws.com', database='dev', port=5439, user='awsuser', password='my_password' ) # Create a Cursor object >>> cursor = conn.cursor() # Query a table using the Cursor >>> cursor.execute("select * from book") #Retrieve the query result set >>> result: tuple = cursor.fetchall() >>> print(result) >> (['One Hundred Years of Solitude', 'Gabriel García Márquez'], ['A Brief History of Time', 'Stephen Hawking'])

オートコミットの有効化

オートコミットプロパティは、Python データベース API 仕様に従って、デフォルトではオフになっています。ロールバックコマンドの実行後に以下のコマンドを使用して、接続の自動コミットプロパティをオンにして、トランザクションが進行中でないことを確認できます。

#Connect to the cluster >>> import redshift_connector >>> conn = redshift_connector.connect(...) # Run a rollback command >>> conn.rollback() # Turn on autocommit >>> conn.autocommit = True >>> conn.run("VACUUM") # Turn off autocommit >>> conn.autocommit = False

カーソルのパラメータスタイルの設定

カーソルのパラメータスタイルは cursor.paramstyle で変更できます。デフォルトとして使用されるパラメータスタイルは format です。パラメータスタイルの有効な値は、qmarknumericnamedformat、および pyformat です。

さまざまなパラメータスタイルを使用してパラメータをサンプル SQL ステートメントに渡す例を以下に示します。

# qmark redshift_connector.paramstyle = 'qmark' sql = 'insert into foo(bar, jar) VALUES(?, ?)' cursor.execute(sql, (1, "hello world")) # numeric redshift_connector.paramstyle = 'numeric' sql = 'insert into foo(bar, jar) VALUES(:1, :2)' cursor.execute(sql, (1, "hello world")) # named redshift_connector.paramstyle = 'named' sql = 'insert into foo(bar, jar) VALUES(:p1, :p2)' cursor.execute(sql, {"p1":1, "p2":"hello world"}) # format redshift_connector.paramstyle = 'format' sql = 'insert into foo(bar, jar) VALUES(%s, %s)' cursor.execute(sql, (1, "hello world")) # pyformat redshift_connector.paramstyle = 'pyformat' sql = 'insert into foo(bar, jar) VALUES(%(bar)s, %(jar)s)' cursor.execute(sql, {"bar": 1, "jar": "hello world"})

Amazon S3 バケットからデータをコピーする COPY と Amazon S3 バケットへデータを書き込む UNLOAD の使用

以下の例は、Amazon S3 バケットからテーブルにデータをコピーしてから、テーブルからバケットにアンロードする方法を示しています。

以下のデータを含む category_csv.txt という名前のテキストファイルをAmazon S3 バケットにアップロードします。

12,Shows,Musicals,Musical theatre 13,Shows,Plays,"All ""non-musical"" theatre" 14,Shows,Opera,"All opera, light, and ""rock"" opera" 15,Concerts,Classical,"All symphony, concerto, and choir concerts"

次に、最初に Amazon Redshift データベースに接続する Python コードの例を示します。次に、categoryという名前のテーブルを作成し、S3 バケットから CSV データをテーブルにコピーします。

#Connect to the cluster and create a Cursor >>> import redshift_connector >>> with redshift_connector.connect(...) as conn: >>> with conn.cursor() as cursor: #Create an empty table >>> cursor.execute("create table category (catid int, cargroup varchar, catname varchar, catdesc varchar)") #Use COPY to copy the contents of the S3 bucket into the empty table >>> cursor.execute("copy category from 's3://testing/category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") #Retrieve the contents of the table >>> cursor.execute("select * from category") >>> print(cursor.fetchall()) #Use UNLOAD to copy the contents of the table into the S3 bucket >>> cursor.execute("unload ('select * from category') to 's3://testing/unloaded_category_csv.txt' iam_role 'arn:aws:iam::123:role/RedshiftCopyUnload' csv;") #Retrieve the contents of the bucket >>> print(cursor.fetchall()) >> ([12, 'Shows', 'Musicals', 'Musical theatre'], [13, 'Shows', 'Plays', 'All "non-musical" theatre'], [14, 'Shows', 'Opera', 'All opera, light, and "rock" opera'], [15, 'Concerts', 'Classical', 'All symphony, concerto, and choir concerts'])

autocommit を true に設定していない場合は、execute() ステートメントの実行後に conn.commit() でコミットします。

データは S3 バケット内にあるファイル unloaded_category_csv.text0000_part00 にアンロードされ、次のコンテンツが含まれます。

12,Shows,Musicals,Musical theatre 13,Shows,Plays,"All ""non-musical"" theatre" 14,Shows,Opera,"All opera, light, and ""rock"" opera" 15,Concerts,Classical,"All symphony, concerto, and choir concerts"