mirror of
https://github.com/discourse/discourse.git
synced 2024-11-22 10:57:04 +08:00
PERF: Add index on topic_id and created_at to posts table (#22818)
Why this change? In `PostDestroyer#make_previous_post_the_last_one` and `Topic.reset_highest`, we have a query that looks something like this: ``` SELECT user_id FROM posts WHERE topic_id = :topic_id AND deleted_at IS NULL AND post_type <> 4 #{post_type} ORDER BY created_at desc LIMIT 1 ``` However, we currently don't have an index that caters directly to this query. As a result, we have seen this query performing poorly on large sites if the PG planner ends up using an index that is suboptimal for the query. This commit adds an index to the `posts` table on `topic_id` and then `created_at`. For the query above, PG will be able to do a backwards index scan efficiently.
This commit is contained in:
parent
0a56274596
commit
fe5cd479eb
|
@ -1320,6 +1320,7 @@ end
|
|||
# index_posts_on_id_topic_id_where_not_deleted_or_empty (id,topic_id) WHERE ((deleted_at IS NULL) AND (raw <> ''::text))
|
||||
# index_posts_on_image_upload_id (image_upload_id)
|
||||
# index_posts_on_reply_to_post_number (reply_to_post_number)
|
||||
# index_posts_on_topic_id_and_created_at (topic_id,created_at)
|
||||
# index_posts_on_topic_id_and_percent_rank (topic_id,percent_rank)
|
||||
# index_posts_on_topic_id_and_post_number (topic_id,post_number) UNIQUE
|
||||
# index_posts_on_topic_id_and_sort_order (topic_id,sort_order)
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
class AddIndexTopicIdCreatedAtOnPosts < ActiveRecord::Migration[7.0]
|
||||
disable_ddl_transaction!
|
||||
|
||||
def up
|
||||
remove_index :posts, %i[topic_id created_at], algorithm: :concurrently, if_exists: true
|
||||
add_index :posts, %i[topic_id created_at], algorithm: :concurrently
|
||||
end
|
||||
|
||||
def down
|
||||
remove_index :posts, %i[topic_id created_at], algorithm: :concurrently, if_exists: true
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue
Block a user