postgresql - How do I make 'SELECT COUNT(*) from clicks' faster?
问题描述
I'm using Postgres.
I have queries of the form:
`SELECT COUNT(*) from clicks where link_id=1`
Clicks is millions of rows.
These queries are taking 10-20 seconds.
Are there any elegant ways to accelerate this?
Indexes
CREATE INDEX clicks_link_id_index
ON public.clicks USING btree
(link_id ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX clicks_link_workspace_id_index
ON public.clicks USING btree
(link_workspace_id ASC NULLS LAST)
TABLESPACE pg_default;
CREATE INDEX index_date_trunc
ON public.clicks USING btree
(date_trunc('day'::text, inserted_at) ASC NULLS LAST)
TABLESPACE pg_default;
SET ENABLE_SEQSCAN TO OFF
:
解决方案
它认为仅索引扫描将比顺序扫描便宜 4 倍,所以我很困惑为什么它没有首先选择仅索引扫描(在您设置 enable_seqscan=off 之前)。现在,如果您将其设置回默认值,它会再次使用 seq 扫描吗?
如果您刚刚对表进行 VACUUM,那么仅索引扫描会变得更快吗?虽然 99% 的行是在没有堆提取的情况下提取的,但其余 1% 可能占大部分时间。
或者也许你应该投入更多的硬件。拥有更多用于缓存数据的 RAM(在 shared_buffers 或文件系统缓存中)不会受到伤害。
推荐阅读
- css - 使用显示内联后提交按钮不起作用
- graphql - 如何使用 GraphQL 在页面组件中查询多个数据集?
- c++ - 为什么在这种情况下递归解决方案比迭代解决方案更快?
- macos - macOS:有什么方法可以知道用户何时尝试通过其 Dock 图标退出应用程序?
- django - 出现错误:'admin' 不是注册的命名空间,在尝试访问密码重置视图时
- azure-devops - 如何从查询结果工具栏菜单 VSTS 扩展访问查询?
- excel - 以条件格式将 xlExpression 与“And”一起使用
- rest - OpenAPI / Swagger Spec:如何指定整个示例请求正文?
- javascript - 如果使用格式化程序进行显示,如何对 bootstrap-vue 中的日期列进行排序?
- react-native - 如何在水平平面列表的末尾进行模糊处理?