postgresql 索引未在查询中使用

问题描述 投票:0回答:1

我有 AWS RDS PostgreSQL 作为数据库。我有一个表用于存储当前 5M 记录的

childbirth_data
数据,另一个表用于存储具有 30M 记录的子统计信息(不是实际的消息)。每月约有 30 万条人员记录和 300 万条消息记录添加到这些表中

查询

SELECT message_date, message_from, sms_type,  message_type, direction, status,
 cd.state ,cd.date_uploaded,
FROM "Suvita".messages m, "Suvita".childbirth_data cd
where m.contact_record_id = cd.id

解释分析结果:

Hash Join  (cost=568680.28..6272284.94 rows=29688640 width=319) (actual time=5473.787..96501.807 rows=30893261 loops=1)
  Hash Cond: (m.contact_record_id = cd.id)
  ->  Seq Scan on messages m  (cost=0.00..2739237.50 rows=29719350 width=174) (actual time=2.364..41071.274 rows=30936614 loops=1)
  ->  Hash  (cost=402612.68..402612.68 rows=5347568 width=121) (actual time=5448.157..5448.158 rows=5349228 loops=1)
        Buckets: 32768  Batches: 256  Memory Usage: 3518kB
        ->  Seq Scan on childbirth_data cd  (cost=0.00..402612.68 rows=5347568 width=121) (actual time=0.011..3013.382 rows=5349228 loops=1)
Planning Time: 18.349 ms
Execution Time: 97849.004 ms

我为需要聚合统计数据的仪表板制作了聚合表,并根据报告需求为不同状态或消息类型制作了物化视图。 我对这些表的写入是通过每晚运行的计划作业进行的,因此即使由于索引较多而写入速度相对较慢,也不会成为问题。

我已经放入以下索引

person - id,state, mother name, mother phone, rchid, telerivet_contact_id Messages - id, contact_record_id, message_date and state
我的

查询仍然非常,并且索引在查询中没有使用,看起来。如何让 PostgreSQL 使用索引?

分区有帮助吗?问题是我正在考虑按州分区,但其中一个州拥有 90% 的数据,所以我认为这不会有帮助。另外,我不想触及执行数据输入的代码。

我不是数据库专家,所以请告知我是否可以做任何其他事情来使表上的

读取更快

postgresql amazon-rds materialized-views database-indexes
1个回答
0
投票

一个问题是

work_mem

设置得太小,无法有效处理。您可以使用

EXPLAIN (ANALYZE, BUFFERS)
查看临时文件的使用情况。如果您可以努力增加此查询的
work_mem
,它应该会有所帮助。
令我惊讶的是,如果你给它那么少的内存,PostgreSQL 不会考虑合并连接。如果您在 

childbirth_data.id

messages.contact_record_id
上创建索引,计划会是什么样子?如果您在会话中临时将
enable_hashjoin
enable_nestloop
设置为
off
,那么执行计划会是什么样子?
    

© www.soinside.com 2019 - 2024. All rights reserved.