Skip to content

A platform for community discussion. Free, open, simple.

PERF: Optimise query for excluding topics in certain categories in TopicsFilter (#27027)

Alan Guo Xiang Tan2134ca903178
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index e1cefed5112..c360f928dac 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -270,9 +270,14 @@ class TopicsFilter
)
end
- if exclude_category_ids.present?
- @scope = @scope.where("topics.category_id NOT IN (?)", exclude_category_ids)
- end
+ # Use `NOT EXISTS` instead of `NOT IN` to avoid performance issues with large arrays.
+ @scope = @scope.where(<<~SQL) if exclude_category_ids.present?
+ NOT EXISTS (
+ SELECT 1
+ FROM unnest(array[#{exclude_category_ids.join(",")}]) AS excluded_categories(category_id)
+ WHERE topics.category_id IS NULL OR excluded_categories.category_id = topics.category_id
+ )
+ SQL
end
def filter_created_by_user(usernames:)