Understanding how to optimize a query via the Postgres/rails explain data

十年热恋 提交于 2020-01-13 16:57:32

问题


I have the following query:

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

This query is taking some time as the table has 1m+ records. Here is the query output:

> 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"

Any suggestions on how to possibly improve this query performance? Thanks


回答1:


As suggested by Igor, try a composite index :

CREATE INDEX index_invites_email_created_at on invites(email,created_at);


来源:https://stackoverflow.com/questions/14428547/understanding-how-to-optimize-a-query-via-the-postgres-rails-explain-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!