簡體   English   中英

將 Pandas 數據幀寫入 AWS athena 數據庫

[英]Write pandas dataframe into AWS athena database

我已經使用 pyathena 運行了一個查詢,並創建了一個 Pandas 數據框。 有沒有辦法將 Pandas 數據幀直接寫入 AWS athena 數據庫? 就像 MYSQL 數據庫的 data.to_sql 一樣。

下面分享一個需要寫入AWS athena數據庫的dataframe代碼示例供參考:

data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})

實現此目標的另一種現代(至 2020 年 2 月)方法是使用aws-data-wrangler庫。 它使數據處理中的許多常規(有時是煩人的)任務自動化。

結合問題中的案例,代碼如下所示:

import pandas as pd
import awswrangler as wr

data=pd.DataFrame({'id':[1,2,3,4,5,6],'name':['a','b','c','d','e','f'],'score':[11,22,33,44,55,66]})

# Typical Pandas, Numpy or Pyarrow transformation HERE!

wr.pandas.to_parquet(  # Storing the data and metadata to Data Lake
    dataframe=data,
    database="database",
    path="s3://your-s3-bucket/path/to/new/table",
    partition_cols=["name"],
)

這非常有用,因為aws-data-wrangler知道從路徑解析表名(但您可以在參數中提供表名)並根據數據幀在 Glue 目錄中定義適當的類型。

它還有助於將 Athena 的數據直接查詢到 Pandas 數據幀:

df = wr.pandas.read_table(database="dataase", table="table")

所有的過程都將是快速和方便的。

AWS Athena 的存儲是S3 它僅從 S3 文件中讀取數據。 是不可能更早的數據直接寫入Athena數據庫就像任何其他數據庫。

It was missing support supportinsert into ... It was missing support support

作為workaround ,用戶可以完成以下步驟以使其工作。

1. You need to write the pandas output to a file, 
2. Save the file to S3 location, from where the AWS Athena is reading.

我希望它能給你一些提示。

2020 年 5 月 1 日更新。

2019 年 9 月 19 日, AWS宣布支持 insert 到Athena ,在上面的答案中做出了一個incorrect的陳述,雖然我提供的上述解決方案仍然有效,但隨着AWS公告添加了另一個可能的解決方案。

正如AWS Documentation建議的那樣,此功能將允許您發送insert語句,而Athena會將數據寫回source table S3 location新文件。 從本質AWSAWS解決了您將數據寫入S3文件的頭痛問題。

請注意, Athena會將插入的數據寫入單獨的文件。 這里是 文檔

一種選擇是使用:

pandas_df.to_parquet(file, engine="pyarrow) 

首先將其保存為鑲木地板格式的臨時文件。 為此,您需要安裝 pyarrow 依賴項。 將此文件保存在本地后,您可以使用適用於 python 的 aws sdk 將其推送到 S3。

現在可以通過執行以下查詢在 Athena 中創建一個新表:

    CREATE EXTERNAL TABLE IF NOT EXISTS 'your_new_table'
        (col1 type1, col2 type2)
    PARTITIONED BY (col_partitions_if_neccesary)
    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
    LOCATION 's3 location of your parquet file'
    tblproperties ("parquet.compression"="snappy");

另一種選擇是為此使用 pyathena。 以他們的官方文檔為例:

import pandas as pd
from urllib.parse import quote_plus
from sqlalchemy import create_engine

conn_str = "awsathena+rest://:@athena.{region_name}.amazonaws.com:443/"\
           "{schema_name}?s3_staging_dir={s3_staging_dir}&s3_dir={s3_dir}&compression=snappy"

engine = create_engine(conn_str.format(
    region_name="us-west-2",
    schema_name="YOUR_SCHEMA",
    s3_staging_dir=quote_plus("s3://YOUR_S3_BUCKET/path/to/"),
    s3_dir=quote_plus("s3://YOUR_S3_BUCKET/path/to/")))

df = pd.DataFrame({"a": [1, 2, 3, 4, 5]})
df.to_sql("YOUR_TABLE", engine, schema="YOUR_SCHEMA", index=False, if_exists="replace", method="multi")

在這種情況下,需要依賴 sqlalchemy。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM