Skip to content

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

PERF: Reduce cold block reads in post searches (#44321)

Alan Guo Xiang Tanf7814d5bca3e
diff --git a/app/models/post.rb b/app/models/post.rb
index b8cffeef82e..7d982dd6391 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -1340,6 +1340,7 @@ end
#
# idx_posts_created_at_topic_id (created_at,topic_id) WHERE (deleted_at IS NULL)
# idx_posts_deleted_posts (topic_id,post_number) WHERE (deleted_at IS NOT NULL)
+# idx_posts_search_covering (id) WHERE ((deleted_at IS NULL) AND (NOT hidden))
# idx_posts_user_id_deleted_at (user_id) WHERE (deleted_at IS NULL)
# index_for_rebake_old (id DESC) WHERE (((baked_version IS NULL) OR (baked_version < 2)) AND (deleted_at IS NULL))
# index_posts_on_deleted_by_id (deleted_by_id) WHERE (deleted_by_id IS NOT NULL)
diff --git a/db/migrate/20261007082151_add_covering_index_for_post_search.rb b/db/migrate/20261007082151_add_covering_index_for_post_search.rb
new file mode 100644
index 00000000000..0b8ba09138c
--- /dev/null
+++ b/db/migrate/20261007082151_add_covering_index_for_post_search.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+class AddCoveringIndexForPostSearch < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ def up
+ remove_index :posts,
+ name: "idx_posts_search_covering",
+ algorithm: :concurrently,
+ if_exists: true
+
+ add_index :posts,
+ :id,
+ name: "idx_posts_search_covering",
+ include: %i[topic_id post_number post_type],
+ where: "deleted_at IS NULL AND NOT hidden",
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :posts,
+ name: "idx_posts_search_covering",
+ algorithm: :concurrently,
+ if_exists: true
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index cfd2e30d497..b53d2cdb89a 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -20021,6 +20021,13 @@ CREATE INDEX idx_posts_created_at_topic_id ON public.posts USING btree (created_
CREATE INDEX idx_posts_deleted_posts ON public.posts USING btree (topic_id, post_number) WHERE (deleted_at IS NOT NULL);
+--
+-- Name: idx_posts_search_covering; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_posts_search_covering ON public.posts USING btree (id) INCLUDE (topic_id, post_number, post_type) WHERE ((deleted_at IS NULL) AND (NOT hidden));
+
+
--
-- Name: idx_posts_user_id_deleted_at; Type: INDEX; Schema: public; Owner: -
--
@@ -25568,6 +25575,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20261007082151'),
('20261006113418'),
('20261005091527'),
('20261005091447'),