首页 > 解决方案 > 使用 python 和 postgres 更快地运行一组查询

问题描述

在我的示例中,我有一个要在数据库中搜索的 3000 个单词的列表,因此使用此 pyhton 代码(我正在使用 django),该操作需要花费大量时间,并且在 3.5 分钟内完成,平均查询时间为 120 毫秒。有没有一种方法可以使用脚本 python 使用线程或类似的东西来加速这些查询的执行?

 def my_custom_sql(ent):
    for e in ent:
        with connection.cursor() as cursor:
            entity=e.replace("'","''")
         
            cursor.execute("SELECT object FROM yagofacts WHERE subject='{}' AND object LIKE '<wordnet_%>';".format(entity))
         
            row = cursor.fetchall()
            print(row)
               

标签: pythonpostgresql

解决方案


修改您的方法,如下所示。它将使用相同的游标来触发所有查询,因此会更快。

with connection.cursor() as cursor:    
    for e in ent:
        entity=e.replace("'","''")
        cursor.execute("SELECT object FROM yagofacts WHERE subject='{}' AND object LIKE '<wordnet_%>';".format(entity)) 
        row = cursor.fetchall()
        print(row)

如果这没有帮助,请尝试连接池。它可能对您的情况有所帮助。


推荐阅读