22from fastapi import FastAPI
33from fastapi .middleware .cors import CORSMiddleware
44from src .routers import movies
5- from src .utils .errorHandler import register_error_handlers
65from src .database .mongo_client import db , get_collection
76
87import os
1514@asynccontextmanager
1615async def lifespan (app : FastAPI ):
1716 # Startup: Create search indexes
18- await ensure_search_index ()
19- await vector_search_index ()
17+ await ensure_mongodb_search_index ()
18+ await ensure_vector_search_index ()
19+ await ensure_standard_index ()
2020
2121 # Print server information
2222 print (f"\n { '=' * 60 } " )
@@ -30,10 +30,9 @@ async def lifespan(app: FastAPI):
3030 # Add any cleanup code here
3131
3232
33- async def ensure_search_index ():
33+ async def ensure_mongodb_search_index ():
3434 try :
3535 movies_collection = db .get_collection ("movies" )
36- comments_collection = db .get_collection ("comments" )
3736
3837 # Check and create search index for movies collection
3938 result = await movies_collection .list_search_indexes ()
@@ -71,7 +70,7 @@ async def ensure_search_index():
7170 )
7271
7372
74- async def vector_search_index ():
73+ async def ensure_vector_search_index ():
7574 """
7675 Creates vector search index on application startup if it doesn't already exist.
7776 This ensures the index is ready before any vector search requests are made.
@@ -114,6 +113,26 @@ async def vector_search_index():
114113 f"and verify the 'embedded_movies' collection exists with the required embedding field."
115114 )
116115
116+ async def ensure_standard_index ():
117+ """
118+ Creates a standard MongoDB index on the comments collection on application startup.
119+ This improves performance for queries filtering by movie_id such as ReportingByComments().
120+ """
121+
122+ try :
123+ comments_collection = db .get_collection ("comments" )
124+
125+ existing_indexes_cursor = await comments_collection .list_indexes ()
126+ existing_indexes = [index async for index in existing_indexes_cursor ]
127+ index_names = [index .get ("name" ) for index in existing_indexes ]
128+ standard_index_name = "movie_id_index"
129+ if standard_index_name not in index_names :
130+ await comments_collection .create_index ([("movie_id" , 1 )], name = standard_index_name )
131+
132+ except Exception as e :
133+ print (f"Failed to create standard index on 'comments' collection: { str (e )} . " )
134+ print (f"Performance may be degraded. Please check your MongoDB configuration." )
135+
117136
118137app = FastAPI (lifespan = lifespan )
119138
@@ -127,6 +146,5 @@ async def vector_search_index():
127146 allow_headers = ["*" ],
128147)
129148
130- register_error_handlers (app )
131149app .include_router (movies .router , prefix = "/api/movies" , tags = ["movies" ])
132150
0 commit comments