【问题标题】:Slow query using Django and PostgreSQL with > 40 million rows使用超过 4000 万行的 Django 和 PostgreSQL 进行慢速查询
【发布时间】:2020-09-28 16:50:44
【问题描述】:

我正在使用 PostgreSQL 处理具有超过 4000 万行的模型(表)并且查询非常慢(> 2 分钟)。

模型:

class ModelA(...):
    source = models.ForeignKey(ModelB, related_name='source', ...)
    target = models.ForeignKey(ModelB, related_name='target', ...)

class ModelB(...):
    c = models.ForeignKey(ModelC, ...)
    ...

Django 过滤器:

ModelA.objects.filter(source__isnull=True, target__c=my_c)

查询:

SELECT "model_a"."id", ... 
FROM "model_a" 
INNER JOIN "model_b" T3 ON ("model_a"."target_id" = T3."id") 
WHERE ("model_a"."removed" = False AND "model_a"."source_id" IS NULL AND T3."c_id" = 389)

解释查询:

                                                            QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1001.26..2498957.37 rows=12277 width=71)
   Workers Planned: 3
   ->  Nested Loop  (cost=1.26..2496729.67 rows=3960 width=71)
         ->  Parallel Index Scan using model_b_model_c_removed_filename on model_b t3  (cost=0.69..2481771.88 rows=5907 width=4)
               Index Cond: (c_id = 389)
         ->  Index Scan using model_a_source_target_idx on model_a  (cost=0.56..2.52 rows=1 width=71)
               Index Cond: (target_id = t3.id)
               Filter: (NOT removed)
(8 rows)

如何优化它?

我有优化问题,我想知道不同的解决方案等。

【问题讨论】:

  • 运行EXPLAIN YOU QUERY并将查询执行平面放在这里
  • @SlavaRozhnev 添加了EXPLAIN。谢谢

标签: django postgresql performance


【解决方案1】:
  1. 在 Django 中,您可以使用 select_related 和 prefetch_related 来 优化了您的查询。
  2. 您可以在模型中添加索引。
  3. 使用 Redis 或 Memcached 作为缓存层以优化读取访问。

What's the difference between select_related and prefetch_related in Django ORM? Stack over flow

select_related Django official doc

prefetch_related Django official doc

Solving Performance Problems in the Django ORM

Django Database Optimization Tips

【讨论】:

  • 我尝试使用 select_relatedprefetch_related 但仍然很慢。感谢所有文档
  • 您也可以尝试使用 NoSql 数据库进行快速数据访问。多种技术用于解决此类任务。一个因素是系统规格。
猜你喜欢
  • 2011-03-22
  • 1970-01-01
  • 2021-11-26
  • 2019-07-27
  • 2021-10-11
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多