"""
Add HNSW index to NodeEntry.embedding for fast approximate nearest neighbor search.

Without a vector index, pgvector performs a sequential scan of the entire table
for every query (O(n)). HNSW turns this into O(log n), reducing query time from
~20s to <100ms for 150k nodes.

Requires pgvector >= 0.5.0 (released 2023-05-23).
"""

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ("application", "0001_initial"),
    ]

    operations = [
        migrations.RunSQL(
            sql="""
                CREATE INDEX IF NOT EXISTS application_nodeentry_hnsw_cosine_idx
                ON application_nodeentry
                USING hnsw (embedding vector_cosine_ops)
                WITH (m = 16, ef_construction = 64);
            """,
            reverse_sql="""
                DROP INDEX IF EXISTS application_nodeentry_hnsw_cosine_idx;
            """,
        ),
    ]
