PERF: N+1 query when searching with tags enabled.

This commit is contained in:
Guo Xiang Tan 2017-05-31 08:14:09 +09:00
parent ce57ff9fcf
commit 137f91d1cf

View File

@ -777,8 +777,7 @@ class Search
def aggregate_posts(post_sql) def aggregate_posts(post_sql)
return [] unless post_sql return [] unless post_sql
Post.includes(:topic => :category) posts_eager_loads(Post)
.includes(:user)
.joins("JOIN (#{post_sql}) x ON x.id = posts.topic_id AND x.post_number = posts.post_number") .joins("JOIN (#{post_sql}) x ON x.id = posts.topic_id AND x.post_number = posts.post_number")
.order('row_number') .order('row_number')
end end
@ -806,9 +805,9 @@ class Search
def topic_search def topic_search
if @search_context.is_a?(Topic) if @search_context.is_a?(Topic)
posts = posts_query(@limit).where('posts.topic_id = ?', @search_context.id) posts = posts_eager_loads(posts_query(@limit))
.includes(:topic => :category) .where('posts.topic_id = ?', @search_context.id)
.includes(:user)
posts.each do |post| posts.each do |post|
@results.add(post) @results.add(post)
end end
@ -817,4 +816,15 @@ class Search
end end
end end
def posts_eager_loads(query)
query = query.includes(:user)
topic_eager_loads = [:category]
if SiteSetting.tagging_enabled
topic_eager_loads << :tags
end
query.includes(topic: topic_eager_loads)
end
end end