-- 97_objective_backfill_indexes.sql
-- Issue #203 — Backfill objective_complex_mapping (114 → ~1500 EKB ЖК).
--
-- pg_trgm уже установлен в prod, но CREATE EXTENSION IF NOT EXISTS идемпотентен.
-- Trigram GIST index на comm_name (DOM.РФ) ускоряет LATERAL similarity() join
-- при поиске кандидатов для fuzzy match (domrf_kn_objects ↔ objective_corpus_room_month).
--
-- Dependencies: domrf_kn_objects, objective_corpus_room_month (уже существуют).
-- Applied: automatically via deploy.yml in NN order.

BEGIN;

CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- Trigram GIST index для fuzzy match comm_name (DOM.РФ) ↔ project_name (Objective).
-- Фильтр is_ekb = true: только ЕКБ объекты (~1285 строк).
CREATE INDEX IF NOT EXISTS idx_domrf_kn_objects_comm_name_trgm
    ON domrf_kn_objects USING gist (comm_name gist_trgm_ops)
    WHERE is_ekb = true;

-- B-tree index на project_name в objective для JOIN performance.
CREATE INDEX IF NOT EXISTS idx_objective_corpus_room_month_project_name
    ON objective_corpus_room_month (project_name);

COMMENT ON INDEX idx_domrf_kn_objects_comm_name_trgm IS
    'Trigram GIST index для fuzzy match с objective_complex_mapping (#203 backfill)';

COMMENT ON INDEX idx_objective_corpus_room_month_project_name IS
    'B-tree index на project_name для JOIN performance (#203 backfill)';

COMMIT;
