paper_server/apps/resm/migrations/0006_pg_trgm_index.py

38 lines
1.5 KiB
Python

"""为 SearchFilter 的 title / first_author / first_author_institution 三列建 pg_trgm GIN 索引。
原因:DRF SearchFilter 走 `column ILIKE '%keyword%'` 前后通配,B-tree 索引救不了;
高频关键词 + 几十万行表会 30s+ timeout。pg_trgm 给 trigram 建 GIN 索引,
ILIKE '%xxx%' 走索引,降到几十 ms。
pg_trgm 是 PostgreSQL contrib 扩展,首次启用需要 DB superuser 权限;
CREATE EXTENSION IF NOT EXISTS 幂等,迁移可安全重跑。
"""
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resm', '0005_alter_paper_fetch_status'),
]
operations = [
migrations.RunSQL(
sql=[
"CREATE EXTENSION IF NOT EXISTS pg_trgm;",
"CREATE INDEX IF NOT EXISTS paper_title_trgm "
"ON resm_paper USING gin (title gin_trgm_ops);",
"CREATE INDEX IF NOT EXISTS paper_first_author_trgm "
"ON resm_paper USING gin (first_author gin_trgm_ops);",
"CREATE INDEX IF NOT EXISTS paper_first_author_institution_trgm "
"ON resm_paper USING gin (first_author_institution gin_trgm_ops);",
],
reverse_sql=[
"DROP INDEX IF EXISTS paper_first_author_institution_trgm;",
"DROP INDEX IF EXISTS paper_first_author_trgm;",
"DROP INDEX IF EXISTS paper_title_trgm;",
# pg_trgm 扩展不 drop —— 其他 app / 表可能也在用
],
),
]