了解如何通过Postgres/rails解释数据来优化一个查询[英] Understanding how to optimize a query via the Postgres/rails explain data

本文是小编为大家收集整理的关于了解如何通过Postgres/rails解释数据来优化一个查询的处理方法,想解了了解如何通过Postgres/rails解释数据来优化一个查询的问题怎么解决?了解如何通过Postgres/rails解释数据来优化一个查询问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我有以下疑问:

c = Invite.where(:invite_method => 'email', :email => email, :created_at => Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).count

此查询需要一些时间,因为该表有 1m 多条记录.这是查询输出:

> invites_sent_today = Invite.where(:invite_method => 'email', :email => email, :created_at => Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).exp 

Invite Load (62.3ms)  SELECT "invites".* FROM "invites" WHERE "invites"."invite_method" = 'email' AND "invites"."email" = 'santa@site.com' AND ("invites"."created_at" BETWEEN '2013-01-20 00:00:00.000000' AND '2013-01-20 23:59:59.999999')

EXPLAIN (2.2ms)  EXPLAIN SELECT "invites".* FROM "invites" WHERE "invites"."invite_method" = 'email' AND "invites"."email" = 'santa@site.com' AND ("invites"."created_at" BETWEEN '2013-01-20 00:00:00.000000' AND '2013-01-20 23:59:59.999999')

=> EXPLAIN for:

SELECT \"invites\".*
  FROM \"invites\"
 WHERE \"invites\".\"invite_method\" = 'email' 
   AND \"invites\".\"email\" = 'santa@site.com'
   AND (\"invites\".\"created_at\"
    BETWEEN '2013-01-2000:00:00.000000'                                                             
       AND'2013-01-20 23:59:59.999999'
      ;

QUERY PLAN\n------------------------------------------------------------------------------------------------------------------------------------------------------------------\n 
Index Scan using index_invites_on_created_at on invites  (cost=0.00..17998.11 rows=2 width=129)\n   
Index Cond: ((created_at >= '2013-01-20 00:00:00'::timestamp without time zone) AND (created_at <= '2013-01-20 23:59:59.999999'::timestamp without time zone))\n   
Filter: (((invite_method)::text = 'email'::text) AND ((email)::text = 'santa@site.com'::text))\n(3 rows)\n"

关于如何可能提高此查询性能的任何建议?谢谢

推荐答案

按照 Igor 的建议,尝试使用复合索引:

CREATE INDEX index_invites_email_created_at on invites(email,created_at);

本文地址:https://www.itbaoku.cn/post/1763977.html