3
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 1 year has passed since last update.

createOrReplaceTempViewの代わりにパラメータ化クエリを使う備忘録

Posted at

はじめに

自分用メモ。

複雑な変換をするとき、
SELECT結果をデータフレームに→データフレームをTempViewに→TempViewから新しいSELECT を作成→・・・ というようなことをしていたが、今はパラメータ化クエリが推奨されているらしい。
テキスト→日付などの型変換もpython内ででき、SQLインジェクションにも対応できてよいとか

参考:
https://www.databricks.com/jp/blog/parameterized-queries-pyspark

今までのやり方

CTEのようにViewを使って多段での変換をしていた。

image.png

pyspark

df = spark.sql("SELECT * FROM <テーブル名>")
display(df)
pyspark
df.createOrReplaceTempView("tempV1")
df2 = spark.sql("""
SELECT 
    *,quantity * 1.1 as `110% QTY`
FROM 
   tempV1
""")

display(df2) 

パラメータ化クエリを使ってデータフレームをソースにする

spark.sql はpythonオブジェクトをそのまま埋め込みできるのでちょっと楽ちん

image.png

pyspark

df = spark.sql("SELECT * FROM <テーブル名>")
display(df)

pyspark

df2 = spark.sql("""
    SELECT 
        *,quantity * 1.1 as `110% QTY`
    FROM 
        {df}
    """
    ,df=df)

display(df2) 
3
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
3
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?