[英]Recommendation for writing data from SQLite file via Python sqlite3
我已经生成了一个巨大的SQLite数据库,需要从中获取一些数据。 为此,我编写了一些脚本,并进行了分析,得出一个不幸的结论,即写入过程大约需要花费大约30%的时间。 当前设置为3天。 我写的脚本尽可能简单,以使其尽可能快。
我想知道您是否有一些技巧可以加快整个过程。 该数据库具有唯一索引,但我正在查询的列却没有(因为这些重复的行)。
在这里使用任何多处理Python库是否有意义?
该脚本将是这样的:
import sqlite3
def write_from_query(db_name, table_name, condition, content_column, out_file):
'''
Writes contents from a SQLite database column to an output file
Keyword arguments:
db_name (str): Path of the .sqlite database file.
table_name (str): Name of the target table in the SQLite file.
condition (str): Condition for querying the SQLite database table.
content_colum (str): Name of the column that contains the content for the output file.
out_file (str): Path of the output file that will be written.
'''
# Connecting to the database file
conn = sqlite3.connect('zinc12_drugnow_nrb(copy).sqlite')
c = conn.cursor()
# Querying the database and writing the output file
c.execute('SELECT ({}) FROM {} WHERE {}'.format(content_column, table_name, condition))
with open(out_file, 'w') as outf:
for row in c:
outf.write(row[0])
# Closing the connection to the database
conn.close()
if __name__ == '__main__':
write_from_query(
db_name='my_db.sqlite',
table_name='my_table',
condition='variable1=1 AND variable2<=5 AND variable3="Zinc_Plus"',
content_column='variable4',
out_file='sqlite_out.txt'
)
感谢您的帮助,我期待您的建议!
编辑:有关数据库的更多信息:
我假设您正在运行write_from_query函数进行大量查询。
如果是这样,问题是您的过滤条件缺少索引
结果如下:对于您执行的每个查询,sqlite将循环遍历整个50GB数据并检查您的条件是否成立。 那是非常低效的。
最简单的方法是在列上拍索引
一种替代方法是制定较少的查询,其中包含多个案例,然后再次遍历该数据以将其拆分为不同的文件。 但是,这能否完成取决于您的数据结构。
我不确定多处理/线程,sqlite并不是真正为并发而设计的,但是我猜它可以解决,因为您只读取数据...
您可以转储内容并在自己的程序中进行过滤-或向条件中使用的所有列添加索引。
将索引添加到所有列将花费很长时间。 但是对于许多不同的查询,别无选择。
没有多重处理可能无济于事。 SSD可能是64GiB Ram。 但是索引不需要它们,查询在普通磁盘上也很快。
最后,您创建了一个数据库,但没有为要查询的列创建索引。 与8Mio行将无法正常工作。
我将看一下唯一索引! 但是与此同时,我偶然发现了另一件事...很抱歉在这里为我的问题写了自己的答案,但我认为这对组织来说更好...
我当时以为.fetchall()
命令也可以加快整个过程,但是我发现关于sqlite3的文档有点简短...类似
with open(out_file, 'w') as outf:
c.excecute ('SELECT * ...')
results = c.fetchmany(10000)
while results:
for row in results:
outf.write(row[0])
results = c.fetchmany(10000)
说得通?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.