Slow DB access (FastAPI + Firebase)

Viewed 244

I am trying to build a backend service (FastAPI) which is connected to Firebase using Pyrebase Helper Library (as suggested by Firebase documentation). The Firebase Realtime Database has a structure of:

"myproject_db" : {
        "movies":
            "key1": {
                "movie_id": 33
                "other_id": 44
            },
        "ratings":
            "key1": {
                "user_id" : 1
                "rating" : 5
                "movie_id" : 33
            },
    }

The movies and ratings db have more than 10,000 fields.

Now my method /getRatedMovies for a specific user is described below. Even though it works , it requires way more than 30 seconds to complete. The main reason is the iteration of the movies. Seems like everytime I need to find a specific movie I need to go through the entire table. Is there an alternative solution I am missing ? Thank you.

@app.get("/getRatedMovies")
async def ratedMovies():
    try:
        ratings = db.child("ratings").order_by_child("user_id").equal_to(username).get()

        restructuredMovies: List[Movie] = []
        for rating in ratings.each():
            movieid: int = rating.val()["movie_id"]
            movies = db.child("movies").order_by_child("movie_id").equal_to(movie_id).get()
            for movie in movies:
                movieid: int = movie.val()['movie_id']
                other_id: Optional[str] = movie.val()["other_id"]
                restructuredMovie: Movie = Movie(title = movie.val()["title"], movieid = movieid, other_id = other_id)
                restructuredMovies.append(restructuredMovie)
        return {"Movies": restructuredMovies}
    except Exception as error:
        return {"error": "Something went wrong."}
0 Answers
Related