由于计划时间少于执行时间,如何减少查询的执行时间?

时间:2019-06-14 10:00:21

标签: postgresql query-performance

EXPLAIN ANALYSE
SELECT  "conversations".*
FROM "conversations"
   INNER JOIN "messages"
      ON "messages"."conversation_identifier" = "conversations"."conversation_identifier"
WHERE "conversations"."project_id" = 2
  AND (person_messages_count > 0 and deleted IS NULL)
  AND (conversations.status = 'closed')
  AND ((messages.tsv_message_content)
      @@ (to_tsquery('simple', ''' ' || 'help' || ' ''' || ':*')))
ORDER BY conversations.updated_at DESC LIMIT 30;
                                                                                  QUERY PLAN                                                                                   
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=6895.78..6895.85 rows=30 width=398) (actual time=197364.691..197364.730 rows=30 loops=1)
   ->  Sort  (cost=6895.78..6895.86 rows=34 width=398) (actual time=197364.688..197364.702 rows=30 loops=1)
         Sort Key: conversations.updated_at DESC
         Sort Method: top-N heapsort  Memory: 32kB
         ->  Nested Loop  (cost=1.12..6894.91 rows=34 width=398) (actual time=9.625..197314.491 rows=24971 loops=1)
               ->  Index Scan using indexing_by_conversations_status on conversations  (cost=0.56..704.27 rows=64 width=398) (actual time=2.832..14181.496 rows=25362 loops=1)
                     Index Cond: ((project_id = 2) AND (person_messages_count > 0) AND (deleted IS NULL) AND ((status)::text = 'closed'::text))
               ->  Index Scan using index_messages_on_conversation_identifier on messages  (cost=0.56..96.63 rows=10 width=46) (actual time=3.709..7.217 rows=1 loops=25362)
                     Index Cond: ((conversation_identifier)::text = (conversations.conversation_identifier)::text)
                     Filter: (tsv_message_content @@ '''help'':*'::tsquery)
                     Rows Removed by Filter: 15
 Planning time: 46.814 ms
 Execution time: 197366.064 ms

计划时间似乎比实际执行时间要短。有什么方法可以减少执行时间?

1 个答案:

答案 0 :(得分:1)

您有两个问题:

  1. conversations上的估算结果是错误的:

    ANALYZE conversations;
    
  2. 您应该为选择性全文搜索条件建立索引:

    CREATE INDEX ON messages USING gin (tsv_message_content);
    

如果ANALYZE(即使default_statistics_target升高了)也不能改善误估计,则可能是由列之间的相关性引起的。 尝试扩展统计信息以改善这一点:

CREATE STATISTICS conversations_stats (dependencies)
   ON project_id, deleted, status FROM conversations;

随后的ANALYZE应该可以改善估算值。