Spaces:
Running

File size: 6,466 Bytes
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""
MongoDB Atlas Vector Search Index Setup
========================================
Run this ONCE to create the vector search index in your Atlas cluster.

This script:
1. Connects to your MongoDB Atlas cluster
2. Creates the "trajectory_vector_index" Atlas Vector Search index
3. Creates regular indexes for performance (outcome, thermal_risk)
4. Verifies the index was created

After running this script, your Atlas cluster can perform semantic similarity
search across all trajectory documents using cosine distance on 768-dim vectors.

Usage:
    python setup_vector_index.py

Note: Index creation takes 1-2 minutes to propagate across Atlas nodes.
      You'll see "ACTIVE" status in Atlas UI when it's ready.
"""

import os
import time
import json
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel
from dotenv import load_dotenv
import certifi

load_dotenv()

MONGO_URI = os.getenv("MONGO_URI")
DB_NAME = "libratio"
COLLECTION_NAME = "trajectories"

# The vector search index definition.
# - field: "embedding" β€” where we store the 768-dim vector
# - similarity: "cosine" β€” measures angle between vectors (best for semantic text)
# - dimensions: 768 β€” must match Gemini's text-embedding-004 output
VECTOR_INDEX_DEFINITION = {
    "fields": [
        {
            "type": "vector",
            "path": "embedding",          # Document field name
            "numDimensions": 768,          # Gemini text-embedding-004 = 768 dims
            "similarity": "cosine",        # Cosine similarity (ideal for semantic text)
        }
    ]
}

# The standard Full-Text Search index definition.
# Uses dynamic mappings to index all text fields (like failure_reason and source_text)
# to support keyword searches, fuzzy match, and autocomplete.
TEXT_SEARCH_INDEX_DEFINITION = {
    "mappings": {
        "dynamic": True
    }
}

# Regular indexes for fast filtering (non-vector queries)
REGULAR_INDEXES = [
    [("outcome", 1)],               # Filter by outcome (SUCCESS/CRASH)
    [("thermal_risk", 1)],          # Filter by thermal risk level
    [("memory_used_gb", -1)],       # Sort by memory usage
    [("episode_id", 1)],            # Lookup by episode
]


def setup_indexes():
    print("=" * 60)
    print("  MongoDB Atlas Search & Vector Search Index Setup")
    print("  Libratio Fleet β€” Trajectory Collection")
    print("=" * 60)

    if not MONGO_URI:
        print("[ERROR] MONGO_URI not set in .env")
        return False

    print("\n[1/4] Connecting to MongoDB Atlas...")
    try:
        client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)
        client.admin.command("ping")
        print("  [OK] Connected successfully")
    except Exception as e:
        print(f"  [ERROR] Connection failed: {e}")
        return False

    db = client[DB_NAME]
    collection = db[COLLECTION_NAME]

    # ── Check if data exists ──
    count = collection.count_documents({})
    print(f"\n[2/4] Found {count} documents in '{COLLECTION_NAME}' collection")
    if count == 0:
        print("  [WARN] No documents found. Run upload_to_mongodb.py first!")
        print("     Vector Search requires documents with 'embedding' fields.")

    # ── Create regular indexes ──
    print("\n[3/4] Creating regular performance indexes...")
    for index_spec in REGULAR_INDEXES:
        try:
            collection.create_index(index_spec)
            field = index_spec[0][0]
            print(f"  [OK] Index on '{field}' created")
        except Exception as e:
            print(f"  [WARN] Index creation note: {e}")

    # ── Create Atlas Search Indexes ──
    print("\n[4/4] Creating Atlas Search indexes...")

    # 1. Create Vector Search Index
    print("\n  - Setting up 'trajectory_vector_index' (type: vectorSearch)...")
    try:
        existing_indexes = list(collection.list_search_indexes())
        index_names = [idx.get("name") for idx in existing_indexes]

        if "trajectory_vector_index" in index_names:
            print("    [INFO] Index 'trajectory_vector_index' already exists")
            for idx in existing_indexes:
                if idx.get("name") == "trajectory_vector_index":
                    print(f"       Status: {idx.get('status', 'UNKNOWN')}")
        else:
            search_index_model = SearchIndexModel(
                definition=VECTOR_INDEX_DEFINITION,
                name="trajectory_vector_index",
                type="vectorSearch",
            )
            collection.create_search_index(model=search_index_model)
            print("    [OK] Vector Search index creation initiated!")
    except Exception as e:
        print(f"    [WARN] Vector Search index creation failed: {e}")

    # 2. Create Full-Text Search Index
    print("\n  - Setting up 'trajectory_text_search_index' (type: search)...")
    try:
        existing_indexes = list(collection.list_search_indexes())
        index_names = [idx.get("name") for idx in existing_indexes]

        if "trajectory_text_search_index" in index_names:
            print("    [INFO] Index 'trajectory_text_search_index' already exists")
            for idx in existing_indexes:
                if idx.get("name") == "trajectory_text_search_index":
                    print(f"       Status: {idx.get('status', 'UNKNOWN')}")
        else:
            search_index_model = SearchIndexModel(
                definition=TEXT_SEARCH_INDEX_DEFINITION,
                name="trajectory_text_search_index",
                type="search",
            )
            collection.create_search_index(model=search_index_model)
            print("    [OK] Full-Text Search index creation initiated!")
    except Exception as e:
        print(f"    [WARN] Full-Text Search index creation failed: {e}")

    # Wait and check status
    print("\n  Waiting 10 seconds for indexes to start building...")
    time.sleep(10)
    try:
        indexes = list(collection.list_search_indexes())
        print("\n  Current Search Indexes Status:")
        for idx in indexes:
            name = idx.get("name")
            status = idx.get("status", "UNKNOWN")
            print(f"  - {name} ({idx.get('type', 'UNKNOWN')}): {status}")
    except Exception as e:
        print(f"  Could not list search indexes status: {e}")

    print("\n" + "=" * 60)
    print("  Setup complete!")
    print("=" * 60)
    client.close()
    return True


if __name__ == "__main__":
    setup_indexes()