From ac80360bea2ce4c9e93a38395d16e2ecc2cee2ed Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Thu, 21 Jun 2018 13:26:26 +0800 Subject: [PATCH] PERF: Help postgres make use of index in `Post.summary`. --- app/models/post.rb | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/app/models/post.rb b/app/models/post.rb index f37a9cf1510..5e736977101 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -349,13 +349,22 @@ class Post < ActiveRecord::Base # percent rank has tons of ties where(topic_id: topic_id) - .where(["(post_number = 1) or id in ( - SELECT p1.id - FROM posts p1 - WHERE p1.percent_rank <= ? AND - p1.topic_id = #{topic_id} - ORDER BY p1.percent_rank - LIMIT ? + .where([ + "id = ANY( + ( + SELECT posts.id + FROM posts + WHERE posts.topic_id = #{topic_id.to_i} + AND post_number = 1 + ) UNION + ( + SELECT p1.id + FROM posts p1 + WHERE p1.percent_rank <= ? + AND p1.topic_id = #{topic_id.to_i} + ORDER BY p1.percent_rank + LIMIT ? + ) )", SiteSetting.summary_percent_filter.to_f / 100.0, SiteSetting.summary_max_results