我正在尝试从AWS服务器上托管的PostgreSQL数据库加载1100万条记录。我尝试使用pandas read_sql,并且在4小时内得到了结果。我的笔记本电脑以及第七代Core i7拥有32 GB的RAM。我还将块大小设置为10000,但这并不能改善疯狂的时间。我在网上查看了许多文章,并尝试了所有文章,但是没有一篇文章可以加快我的过程。我希望在可能的情况下或最短的时间内,在20分钟以内加载此数据。我需要在数据帧中使用此数据,以便可以与已有的其他文件进行一些合并,如果可以在Python中获取数据,则可以使过程自动化。我的代码显示在下面:
from io import StringIO
import psycopg2
import psycopg2.sql as sql
import pandas as pd
import numpy as np
import time
connection = psycopg2.connect(user="abc",
password="efg",
host="123.amazonaws.com",
port="5432",
database="db")
date='2020-03-01'
columns= '"LastName","FirstName","DateOfBirth","PatientGender","Key"'
postgreSQL_select_Query = 'select ' + columns + ' from "Table" where "CreatedDate"::date>=' + "'" + date + "'" + 'limit 11000000'
x=pd.read_sql_query(postgreSQL_select_Query, connection, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=10000)
请提出可以改善此代码并减少运行时间的建议。
我还附加了另一个代码段,这是我用来执行此操作的段,但结果与在HOURS中获取行的结果相同。任何指导将不胜感激。
第二种方法:
# -*- coding: utf-8 -*-
@author: ssullah
"""
from io import StringIO
import psycopg2
import psycopg2.sql as sql
import pandas as pd
import numpy as np
import time
start = time.time()
print("Started")
#Retreiving records from DB
def getdata():
try:
start = time.time()
print("Started")
connection = psycopg2.connect(user="a"
password="as",
host="aws",
port="5432",
database="as")
cur= connection.cursor()
date='2020-03-01'
columns= '"LastName","FirstName","DateOfBirth","PatientGender","Key"'
postgreSQL_select_Query = 'select ' + columns + ' from "ALLADTS" where "CreatedDate"::date>=' + "'" + date + "'" + 'limit 11000000'
cur = connection.cursor('cursor-name') # server side cursor
cur.itersize = 10000 # how much records to buffer on a client
cur.execute(postgreSQL_select_Query)
mobile_records = cur.fetchall()
#Column names as per schema, defined above
col_names=["LastName","FirstName","DateOfBirth","PatientGender","Key"]
# Create the dataframe, passing in the list of col_names extracted from the description
records = pd.DataFrame(mobile_records,col_names)
return records;
except (Exception, psycopg2.Error) as error :
print ("Error while fetching data from PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
records=getdata()
end = time.time()
print("The total time:", (end - start)/60, 'minutes')
更新:
不是决定使用Python加载数据,而是决定使用Python在postgresql中创建一个临时表,并将新文件从熊猫加载到Postgresql。使用python中的查询填充表格后,我就可以查询并获得所需的输出,并将最终结果返回到panda数据框中。
全部花费了1.4分钟,在Pgadmin中运行相同的查询需要30分钟,因此通过利用Python,并使用以Python编写的sql查询来进行计算,我能够以指数方式加快该过程,并且同时不必处理我记忆中的1100万条记录。谢谢您的建议。