【发布时间】:2023-04-04 10:45:01
【问题描述】:
我知道有很多关于这个主题的问题,但我找不到我的任何案例。我的问题很简单。
在我的 influencer 应用程序中,我有 Note 模型,其中包含大约 30 个字段:
class Note(models.Model):
desc = models.TextField()
likeCount = models.PositiveIntegerField()
commentCount = models.PositiveIntegerField()
...
tags = models.ManyToManyField(Tag)
postTs = models.DateTimeField(null=True)
AWS RDS 托管的我的 PostgreSQL 数据库中有超过 100 万 Notes。
现在当我执行以下代码时:
notes = (
Note.objects.filter(desc__icontains='some word')
.values("likeCount", "collectCount", "shareCount", "commentCount", "postTs")[:10]
)
print(len(notes)) # Output: 10
大约需要 7 秒。
生成的 SQL 查询是:
SELECT "influencer_note"."likeCount",
"influencer_note"."collectCount",
"influencer_note"."shareCount",
"influencer_note"."commentCount",
"influencer_note"."postTs"
FROM "influencer_note"
WHERE UPPER("influencer_note"."desc"::text) LIKE UPPER('%some word%')
LIMIT 10
我想我已经做了很多事情来优化查询(例如选择唯一必要的字段并限制数据的数量——10 显然是一个小数字),但它仍然需要时间异常。
此问题的可能原因是什么,我该如何进一步优化?
最终,我需要使用过滤后的查询集制作图表,这就是为什么我需要分页或LIMIT以外的解决方案。
提前谢谢你。
【问题讨论】:
-
你在那个专栏上创建了
index,它不应该那么慢..
标签: python django postgresql