From b7695f6c2a6bb0aab12581be12820191f1c0b228 Mon Sep 17 00:00:00 2001 From: Jamie Gaskins Date: Thu, 25 Mar 2021 05:22:08 -0400 Subject: [PATCH] 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. --- ...40245_add_trigram_index_to_comments_ancestry.rb | 14 ++++++++++++++ db/schema.rb | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20210325040245_add_trigram_index_to_comments_ancestry.rb diff --git a/db/migrate/20210325040245_add_trigram_index_to_comments_ancestry.rb b/db/migrate/20210325040245_add_trigram_index_to_comments_ancestry.rb new file mode 100644 index 000000000..2e9f02b92 --- /dev/null +++ b/db/migrate/20210325040245_add_trigram_index_to_comments_ancestry.rb @@ -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 diff --git a/db/schema.rb b/db/schema.rb index eb7a1ec2a..fd137f8f6 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -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"