Skip to content

Instantly share code, notes, and snippets.

@mdesantis
Last active July 23, 2020 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdesantis/ce8100f617073a09dd0e96f3ce3a7cc8 to your computer and use it in GitHub Desktop.
Save mdesantis/ce8100f617073a09dd0e96f3ce3a7cc8 to your computer and use it in GitHub Desktop.
Rails migration adding PostgreSQL index for LIKE when the pattern is both left-anchored and right-anchored
# It supports queries like:
# ModelName.where(ModelName.arel_table[:columnname].lower.matches 'searchterm')
class PostgresqlLikeIIndex < ActiveRecord::Migration
def up
enable_extension 'pg_trgm'
execute <<~SQL
CREATE INDEX index_tablename_on_columnname_lower
ON tablename USING gin (lower(columnname) gin_trgm_ops)
SQL
end
def down
execute 'DROP INDEX index_tablename_on_columnname_lower'
disable_extension 'pg_trgm'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment