python - 使用 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)
解决方案
修改您的方法,如下所示。它将使用相同的游标来触发所有查询,因此会更快。
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)
如果这没有帮助,请尝试连接池。它可能对您的情况有所帮助。
推荐阅读
- javascript - 在 Node.js 中更快地解析大文件,逐行读取文件,目前运行速度太慢
- javascript - 确保在过滤器运行之前填充 Observable Array
- javascript - React render array of objects in cells of Bootstrap grid
- c# - 不同API控制器Autofac的服务接口的多重实现
- c# - 如何将单元测试添加到我的流利验证类?
- php - 无法上传大文件
- ios - Xcode 9 布局:有没有办法为 iPad 构建一个与 iPhone 相同内容的新故事板?
- c++ - C++ 将 wwn 字符串转换为识别为十六进制的数据类型
- c# - Xamarin 上的 ListView 中的空间过多
- kubernetes - 在 Kubernetes 节点上重启后删除 iptables 规则