Skip to content

Instantly share code, notes, and snippets.

@CarolHsu
Last active March 19, 2019 04:52
Show Gist options
  • Save CarolHsu/4946a27b5309c745b1167e80a15f5fc9 to your computer and use it in GitHub Desktop.
Save CarolHsu/4946a27b5309c745b1167e80a15f5fc9 to your computer and use it in GitHub Desktop.

Index order matters!

For exapmle polymor, Rails 4 or older created the index such as

add_index "http_responses", ["originator_type", "originator_id"], name: "index_http_responses_on_originator_id_and_originator_type", using: :btree

it's certainly slower than

add_index "http_responses", ["originator_id", "originator_type"], name: "index_http_responses_on_originator_id_and_originator_type", using: :btree

Algorthm concurrently

And when you try to remove the indexes on production, it might be locked because it's using. Try to add index by data migration such as

add_index :tables, ["originator_id", "originator_type"], algorithm: :concurrently 

by append algorithm: :concurrently to avoid potential crushes.

The caveat is that concurrent indexes must be created outside a transaction. By default, ActiveRecord migrations are run inside a transaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment