Skip to content

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

PERF: Add `index_topics_on_category_id` (#37022)

Alan Guo Xiang Tan42a94eb6a559
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 24a61a2f08c..7714b7da354 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -2304,6 +2304,7 @@ end
# idxtopicslug (slug) WHERE ((deleted_at IS NULL) AND (slug IS NOT NULL))
# index_topics_on_bannered_until (bannered_until) WHERE (bannered_until IS NOT NULL)
# index_topics_on_bumped_at_public (bumped_at) WHERE ((deleted_at IS NULL) AND ((archetype)::text <> 'private_message'::text))
+# index_topics_on_category_id (category_id) WHERE ((deleted_at IS NULL) AND ((archetype)::text <> 'private_message'::text))
# index_topics_on_created_at_and_visible (created_at,visible) WHERE ((deleted_at IS NULL) AND ((archetype)::text <> 'private_message'::text))
# index_topics_on_external_id (external_id) UNIQUE WHERE (external_id IS NOT NULL)
# index_topics_on_id_and_deleted_at (id,deleted_at)
diff --git a/db/migrate/20260109041508_add_index_category_on_topics.rb b/db/migrate/20260109041508_add_index_category_on_topics.rb
new file mode 100644
index 00000000000..e5f4599d9cb
--- /dev/null
+++ b/db/migrate/20260109041508_add_index_category_on_topics.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+class AddIndexCategoryOnTopics < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ def up
+ execute "DROP INDEX IF EXISTS index_topics_on_category_id;"
+ execute "CREATE INDEX CONCURRENTLY index_topics_on_category_id ON topics (category_id) WHERE deleted_at IS NULL AND (archetype <> 'private_message');"
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end