为单个Django查询关闭Postgres并行查询

时间:2019-02-14 23:03:22

标签: django postgresql query-optimization

我需要在Django应用程序中进行手动优化的查询。但是让查询快速运行意味着我需要能够告诉Postgres“不要对此使用并行处理”。

我认为可行的是:

from django.db import connection

cursor = connection.cursor()

# start a transaction so that PGBouncer runs the next statements
# on the same connection
cursor.execute("begin")

# turn off parallelism for this next query
cursor.execute("set max_parallel_workers_per_gather = 0")

# run my query
cursor.execute("HAND-TUNED SELECT QUERY GOES HERE")

# process the cursor results

# Put this connection back in the PGBouncer pool, and reset 
# max_parallel_workers_per_gather.
cursor.execute("rollback")

但是它似乎没有用。通过Django站点运行查询时,查询继续显示在“慢查询”日志中,并且性能仍然很差(并行4秒钟以上,无并行0.5秒钟)。

有没有办法做我需要做的事?

1 个答案:

答案 0 :(得分:0)

首先,您应该使用SET LOCAL,以便将影响仅限于交易。

然后,我建议您使用auto_explain来查找用于查询的实际计划。也许有其他原因导致经济放缓。