Add a GIN index on comments.ancestry (#13120)

We have a btree index on this table but it is not invoked with a `LIKE`
operation that uses `%` - only when using `LIKE` with an exact match.

This query is DEV's second-most intense query by total time spent with
a p50 latency of ~130ms. This index brings it down to 5ms at p90.
This commit is contained in:
Jamie Gaskins 2021-03-25 05:22:08 -04:00 committed by GitHub
parent e382a086bc
commit b7695f6c2a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 1 deletions

View file

@ -0,0 +1,14 @@
class AddTrigramIndexToCommentsAncestry < ActiveRecord::Migration[6.0]
disable_ddl_transaction!
def change
add_index :comments, :ancestry,
# There is already a btree index on this column, so we need to specify a different name
name: 'index_comments_on_ancestry_trgm',
# Using trigram operations requires a GIN index
using: :gin,
# Indexing for LIKE operations requires trigram operations
opclass: :gin_trgm_ops,
algorithm: :concurrently
end
end

View file

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2021_03_24_031738) do
ActiveRecord::Schema.define(version: 2021_03_25_040245) do
# These are extensions that must be enabled in order to support this database
enable_extension "citext"
@ -387,6 +387,7 @@ ActiveRecord::Schema.define(version: 2021_03_24_031738) do
t.bigint "user_id"
t.index "digest(body_markdown, 'sha512'::text), user_id, ancestry, commentable_id, commentable_type", name: "index_comments_on_body_markdown_user_ancestry_commentable", unique: true
t.index ["ancestry"], name: "index_comments_on_ancestry"
t.index ["ancestry"], name: "index_comments_on_ancestry_trgm", opclass: :gin_trgm_ops, using: :gin
t.index ["commentable_id", "commentable_type"], name: "index_comments_on_commentable_id_and_commentable_type"
t.index ["created_at"], name: "index_comments_on_created_at"
t.index ["score"], name: "index_comments_on_score"