In Rails, how can I add an index in a migration to a Postgres database with a specific sort order?
Ultimately wanting to pull off this query:
CREATE INDEX index_apps_kind_release_date_rating ON apps(kind, itunes_release_date DESC, rating_count DESC);
But right now in my migration I have this:
add_index :apps, [:kind, 'itunes_release_date desc', 'rating_count desc'], name: 'index_apps_kind_release_date_rating'
Which spits out this:
CREATE INDEX "index_apps_kind_release_date_rating" ON "apps" ("kind", "itunes_release_date desc", "rating_count desc")
Which errors out:
PG::Error: ERROR: column "itunes_release_date desc" does not exist
Rails now supports specifying index order in migrations:
def change
add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
end
From http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index
You do not need to specify DESC
in the index. It will give a small speed benefit for the queries, that use this particular ordering, but in general - an index can be used for any oredring of a column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With